Compare commits

..

95 Commits

Author SHA1 Message Date
RadekSabacky 1cfb0a2d4a / move uwf rules into iptables 2025-11-20 14:28:44 +01:00
import this 4fdbcb051a Merge pull request #6218 from nymtech/docs/tools-rewamp - [DOCs/operators]: Tools rewamp documentation 2025-11-20 13:03:48 +00:00
serinko 47c6006bb7 ready to merge back 2025-11-20 13:52:41 +01:00
serinko dcfd0f77ad debug trace ticks 2025-11-20 13:39:11 +01:00
serinko 78fb779010 write wg exit policy testing steps 2025-11-20 13:33:06 +01:00
serinko b4544c2b48 wg exit policy setup 2025-11-20 13:17:40 +01:00
serinko 37e3a101b1 fix routing test 2025-11-19 17:41:35 +01:00
serinko 45a1074377 remove redundant 2025-11-19 17:35:33 +01:00
serinko 1b9af19e20 update routing configuration steps and make components 2025-11-19 17:14:44 +01:00
RadekSabacky bdc0f5022d / move ensure_jq where needed 2025-11-18 16:38:01 +01:00
serinko 4f991061dd fix nginx errors 2025-11-14 16:22:58 +01:00
serinko e5aef76256 non-interactive 2025-11-14 15:27:44 +01:00
serinko 6acc54d2bc syntax fix 2025-11-14 15:03:36 +01:00
serinko ab6e08dd13 fix logic of landing-page lookup 2025-11-14 14:27:38 +01:00
serinko e09066858c bump up version 2025-11-14 14:21:50 +01:00
RadekSabacky 842ce93a60 remove duplicate ufw rule 2025-11-14 13:24:20 +01:00
RadekSabacky ce26105986 typo 2025-11-14 13:24:05 +01:00
serinko cc95358385 add email to a fallback 2025-11-14 13:08:05 +01:00
serinko cc04a09ed7 remove redundant work 2025-11-14 12:58:03 +01:00
serinko ae47d53f0c enforce root 2025-11-14 12:49:10 +01:00
serinko e0ff09f323 enforce root 2025-11-14 12:44:57 +01:00
serinko 10707fd2c5 convention Y/n 2025-11-14 12:43:54 +01:00
serinko 9bdd2af14c enforce root 2025-11-14 12:42:05 +01:00
serinko 228ef8b158 add else 2025-11-14 12:40:14 +01:00
import this d820131d2c arg consistency
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-11-14 10:36:45 +00:00
import this 054715a600 robust error handling
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-11-14 10:36:23 +00:00
import this 3f560180b7 remove redundant
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-11-14 10:35:42 +00:00
import this f62dbbdae0 ensure idempotency for the iptable rules
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-11-14 10:33:23 +00:00
import this edecc4ba01 remove redundant detect interface
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-11-14 10:31:26 +00:00
serinko 58c0e289c2 syntax fix 2025-11-13 20:56:04 +01:00
serinko 6d8edc4bc7 replace y to Y and '' 2025-11-13 20:46:33 +01:00
serinko a44cdf1c7c flush nginx script anew 2025-11-13 20:37:35 +01:00
serinko 6b8a6283a4 fix nginx script 2025-11-13 20:27:43 +01:00
import this 94151965bb string to dict fix
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-11-13 17:55:09 +00:00
import this e8ca490db1 style
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-11-13 17:54:42 +00:00
import this fe7470ea44 address comment
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-11-13 17:54:17 +00:00
serinko 21d52244cb sync up with new tunnel manager 2025-11-13 18:49:53 +01:00
import this c0c58026a8 Merge pull request #6197 from nymtech/serinko/ip-tables-rewamp
one ring rules over all
2025-11-13 17:27:56 +00:00
import this 0fe863c889 delete to resolve merge conflict 2025-11-13 17:27:04 +00:00
import this 4e5d88f64c deleting to resolve merge confilict 2025-11-13 17:26:20 +00:00
serinko 1559f6a912 bugfix 2025-11-13 17:55:57 +01:00
serinko 766024be27 break into args 2025-11-13 17:51:39 +01:00
serinko 5ba181b118 break into args 2025-11-13 17:47:58 +01:00
import this 76fc9f4a90 syntax fix
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-11-13 16:23:38 +00:00
import this 8ca6af7c86 syntax fix
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-11-13 16:23:18 +00:00
import this 45e14a7fb1 address comments
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-11-13 16:22:57 +00:00
import this a38917cb9b address comments
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-11-13 16:22:34 +00:00
serinko cf8a399089 remove subshell 2025-11-13 17:07:20 +01:00
import this ba01820586 address comment
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-11-13 16:05:10 +00:00
import this 8c799b2976 address comment
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-11-13 16:04:34 +00:00
import this de4fb6291c address comments
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-11-13 16:03:50 +00:00
import this 81fd37e5c0 address comments
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-11-13 16:02:56 +00:00
serinko 219f3af967 remove subshell 2025-11-13 16:57:34 +01:00
import this aea7442525 add status
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-11-13 15:56:52 +00:00
import this 1525aed657 expand pattern to common naming conventions
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-11-13 15:56:18 +00:00
import this 943b5fa8bc address comment
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-11-13 15:51:01 +00:00
import this 71e0c025c6 address comment
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-11-13 15:50:42 +00:00
import this 239c6c701b address comment
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-11-13 15:50:19 +00:00
import this 91d0b7bdad address comment
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-11-13 15:49:49 +00:00
import this 99b28b2b6f address comment
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-11-13 15:49:32 +00:00
import this 5627ada57e address comment
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-11-13 15:49:02 +00:00
serinko 4e1228fff0 ensure cars passing in a shell 2025-11-13 16:43:39 +01:00
serinko 04be5624fa ensure cars passing in a shell 2025-11-13 16:41:42 +01:00
serinko a6fe1b1de7 fix logic to ensure to more robust 2025-11-13 16:32:40 +01:00
import this c5971d0e9d align space
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-11-13 15:18:54 +00:00
import this 06dd74ba34 address comments
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-11-13 15:18:38 +00:00
serinko c6a0256b03 remove wrong stdout 2025-11-13 16:13:25 +01:00
import this d04b61a88b spacing
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-11-13 15:10:01 +00:00
import this 70a119ac58 address comment
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-11-13 15:09:38 +00:00
import this e2fe3a60a6 address comment
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-11-13 15:01:23 +00:00
serinko 71301ee0cc sync ipv4 w ipv6 2025-11-13 15:08:34 +01:00
serinko aba6c9d4ac fix exit message 2025-11-13 15:04:17 +01:00
serinko c617bbb240 fix jq 2025-11-13 14:59:36 +01:00
serinko 1f8144eb11 add a safeguard 2025-11-13 14:47:02 +01:00
import this 694135c81b address comment
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-11-13 13:38:45 +00:00
import this e815f08505 address comment
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-11-13 13:38:15 +00:00
serinko f402da8e60 add new top manager tool 2025-11-13 14:28:38 +01:00
serinko 34a500d0a2 refactor completely 2025-11-13 14:26:49 +01:00
serinko ef52f25564 address comment 2025-11-13 11:20:13 +01:00
import this 010b013094 comment fix
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-11-13 10:17:04 +00:00
benedettadavico c503a5f0e8 few more tweaks 2025-11-13 10:21:37 +01:00
serinko 781afd3522 add arg 2025-11-12 17:36:29 +01:00
serinko 58083df0b0 fix QUIC helper script 2025-11-12 17:36:29 +01:00
benedettadavico 4e8d29d0c5 Merge remote-tracking branch 'origin/operators/tools-rewamp' into operators/tools-rewamp 2025-11-12 17:19:32 +01:00
benedettadavico 66797efa80 test new order of events.. 2025-11-12 17:18:59 +01:00
serinko 5a26fa262e add uplink override arg 2025-11-12 16:58:10 +01:00
serinko 73a34935ae trims 2025-11-12 16:29:52 +01:00
serinko a8086675d9 metadata port inside nymwg 2025-11-12 15:34:00 +01:00
serinko 0453345d65 address comments 2025-11-12 15:32:41 +01:00
serinko b56d9505e6 address comments 2025-11-12 15:31:08 +01:00
serinko bdacc72003 rm redundant 2025-11-12 15:22:26 +01:00
benedettadavico 9eca9efd82 fix direction and add test 2025-11-12 13:45:33 +01:00
serinko cc74d218fc rm redundant fn 2025-11-11 21:56:15 +01:00
serinko dea8a287e6 add arguments for env vars 2025-11-11 19:42:03 +01:00
serinko fc5d310935 add QUIC setup script to nym-node-cli 2025-11-11 15:04:09 +01:00
104 changed files with 2534 additions and 3269 deletions
-54
View File
@@ -4,60 +4,6 @@ Post 1.0.0 release, the changelog format is based on [Keep a Changelog](https://
## [Unreleased]
## [2025.21-mozzarella] (2025-11-25)
- [bugfix] Tunnel not waiting on MixnetClient to shut down cleanly ([#6225])
- bugfix: fix credential proxy upgrade mode attestation url arg ([#6202])
- HTTP API resilience enable & domain rotation conditions ([#6200])
- Remove debug feature from http-macro spec in gateway probe ([#6195])
- DNS relibility and troubleshooting ([#6179])
- [bugfix] Distinguish authenticator errors by credential spent ([#6176])
- Typescript SDK 1.4.1 ([#6146])
- Enable URL rotation and retries for mixnet gateway init ([#6126])
- Feature/credential proxy jwt ([#5957])
[#6225]: https://github.com/nymtech/nym/pull/6225
[#6202]: https://github.com/nymtech/nym/pull/6202
[#6200]: https://github.com/nymtech/nym/pull/6200
[#6195]: https://github.com/nymtech/nym/pull/6195
[#6179]: https://github.com/nymtech/nym/pull/6179
[#6176]: https://github.com/nymtech/nym/pull/6176
[#6146]: https://github.com/nymtech/nym/pull/6146
[#6126]: https://github.com/nymtech/nym/pull/6126
[#5957]: https://github.com/nymtech/nym/pull/5957
## [2025.20-leerdammer] (2025-11-12)
- Max/tweak ts sdk actions ([#6185])
- chore: resolve clippy 1.91 warnings ([#6168])
- [chore] Remove unused dependencies ([#6151])
- Use typed-builder for registration client builder config ([#6150])
- tommy is too quick ([#6149])
- configurable mixnet client startup timeout ([#6148])
- [Feature/operators]: QUIC bridge deployment script v2 ([#6145])
- Bugfix: Add circuit breaker ([#6143])
- bugfix: update internal owner address in transferred share ([#6139])
- Update quic_bridge_deployment.sh for IPv4 and .deb package ([#6138])
- feat: expose more explicit new_with_fronted_urls builder for http API client ([#6136])
- bugfix: update stored epoch share when changing ownership ([#6135])
- Domain fronting ([#6134])
- bugfix: update stored epoch share when changing announce address ([#6131])
[#6185]: https://github.com/nymtech/nym/pull/6185
[#6168]: https://github.com/nymtech/nym/pull/6168
[#6151]: https://github.com/nymtech/nym/pull/6151
[#6150]: https://github.com/nymtech/nym/pull/6150
[#6149]: https://github.com/nymtech/nym/pull/6149
[#6148]: https://github.com/nymtech/nym/pull/6148
[#6145]: https://github.com/nymtech/nym/pull/6145
[#6143]: https://github.com/nymtech/nym/pull/6143
[#6139]: https://github.com/nymtech/nym/pull/6139
[#6138]: https://github.com/nymtech/nym/pull/6138
[#6136]: https://github.com/nymtech/nym/pull/6136
[#6135]: https://github.com/nymtech/nym/pull/6135
[#6134]: https://github.com/nymtech/nym/pull/6134
[#6131]: https://github.com/nymtech/nym/pull/6131
## [2025.19-kase] (2025-10-30)
- update ns agent workflow ([#6154])
Generated
+7 -8
View File
@@ -4825,7 +4825,7 @@ dependencies = [
[[package]]
name = "nym-api"
version = "1.1.70"
version = "1.1.68"
dependencies = [
"anyhow",
"async-trait",
@@ -5051,7 +5051,7 @@ dependencies = [
[[package]]
name = "nym-cli"
version = "1.1.67"
version = "1.1.65"
dependencies = [
"anyhow",
"base64 0.22.1",
@@ -5134,7 +5134,7 @@ dependencies = [
[[package]]
name = "nym-client"
version = "1.1.67"
version = "1.1.65"
dependencies = [
"bs58",
"clap",
@@ -6058,7 +6058,6 @@ dependencies = [
"thiserror 2.0.12",
"tokio",
"tracing",
"tracing-subscriber",
"url",
"wasmtimer",
]
@@ -6363,7 +6362,7 @@ dependencies = [
[[package]]
name = "nym-network-requester"
version = "1.1.68"
version = "1.1.66"
dependencies = [
"addr",
"anyhow",
@@ -6413,7 +6412,7 @@ dependencies = [
[[package]]
name = "nym-node"
version = "1.22.0"
version = "1.20.0"
dependencies = [
"anyhow",
"arc-swap",
@@ -6940,7 +6939,7 @@ dependencies = [
[[package]]
name = "nym-socks5-client"
version = "1.1.67"
version = "1.1.65"
dependencies = [
"bs58",
"clap",
@@ -7681,7 +7680,7 @@ dependencies = [
[[package]]
name = "nymvisor"
version = "0.1.32"
version = "0.1.30"
dependencies = [
"anyhow",
"bytes",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "nym-client"
version = "1.1.67"
version = "1.1.65"
authors = ["Dave Hrycyszyn <futurechimp@users.noreply.github.com>", "Jędrzej Stuczyński <andrew@nymtech.net>"]
description = "Implementation of the Nym Client"
edition = "2021"
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "nym-socks5-client"
version = "1.1.67"
version = "1.1.65"
authors = ["Dave Hrycyszyn <futurechimp@users.noreply.github.com>"]
description = "A SOCKS5 localhost proxy that converts incoming messages to Sphinx and sends them to a Nym address"
edition = "2021"
+1 -1
View File
@@ -45,7 +45,7 @@ pub enum ClientCoreError {
#[cfg(not(target_arch = "wasm32"))]
#[error("resolution failed: {0}")]
ResolutionFailed(#[from] nym_http_api_client::ResolveError),
ResolutionFailed(#[from] nym_http_api_client::HickoryDnsError),
#[error("no gateways on network")]
NoGatewaysOnNetwork,
@@ -30,6 +30,7 @@ pub(crate) async fn connect_async(
resolver
.resolve_str(domain)
.await?
.into_iter()
.map(|a| SocketAddr::new(a, port))
.collect()
}
@@ -39,6 +39,7 @@ pub(crate) async fn connect_async(
resolver
.resolve_str(domain)
.await?
.into_iter()
.map(|a| SocketAddr::new(a, port))
.collect()
}
@@ -54,7 +54,7 @@ pub enum GatewayClientError {
#[cfg(not(target_arch = "wasm32"))]
#[error("resolution failed: {0}")]
ResolutionFailed(#[from] nym_http_api_client::ResolveError),
ResolutionFailed(#[from] nym_http_api_client::HickoryDnsError),
#[error("No shared key was provided or obtained")]
NoSharedKeyAvailable,
-8
View File
@@ -168,14 +168,6 @@ pub enum CredentialProxyError {
device_id: String,
credential_id: String,
},
#[error(
"the attestation check url has not been provided through either the CLI nor the default .env config"
)]
AttestationCheckUrlNotSet,
#[error("the provided attestation check url is malformed: {source}")]
MalformedAttestationCheckUrl { source: url::ParseError },
}
impl From<NymAPIError> for CredentialProxyError {
+3 -2
View File
@@ -32,7 +32,7 @@ thiserror = { workspace = true }
tracing = { workspace = true }
itertools = { workspace = true }
inventory = { workspace = true }
tokio = { workspace = true, features = ["rt", "macros", "time"] }
# used for decoding text responses (they were already implicitly included)
bytes = { workspace = true }
encoding_rs = { workspace = true }
@@ -52,4 +52,5 @@ workspace = true
features = ["tokio"]
[dev-dependencies]
tracing-subscriber.workspace = true
tokio = { workspace = true, features = ["rt", "macros"] }
+92 -319
View File
@@ -30,26 +30,19 @@
use crate::ClientBuilder;
use std::{
collections::HashMap,
net::{IpAddr, SocketAddr},
str::FromStr,
net::SocketAddr,
sync::{Arc, LazyLock},
time::Duration,
};
use hickory_resolver::{
TokioResolver,
config::{LookupIpStrategy, NameServerConfigGroup, ResolverConfig},
lookup_ip::LookupIpIntoIter,
ResolveError, TokioResolver,
config::{LookupIpStrategy, NameServerConfigGroup, ResolverConfig, ServerOrderingStrategy},
lookup_ip::{LookupIp, LookupIpIntoIter},
name_server::TokioConnectionProvider,
};
use once_cell::sync::OnceCell;
use reqwest::dns::{Addrs, Name, Resolve, Resolving};
use tracing::*;
mod constants;
mod static_resolver;
pub use static_resolver::*;
use tracing::warn;
impl ClientBuilder {
/// Override the DNS resolver implementation used by the underlying http client.
@@ -66,6 +59,10 @@ impl ClientBuilder {
}
}
struct SocketAddrs {
iter: LookupIpIntoIter,
}
// n.b. static items do not call [`Drop`] on program termination, so this won't be deallocated.
// this is fine, as the OS can deallocate the terminated program faster than we can free memory
// but tools like valgrind might report "memory leaks" as it isn't obvious this is intentional.
@@ -75,24 +72,11 @@ static SHARED_RESOLVER: LazyLock<HickoryDnsResolver> = LazyLock::new(|| {
});
#[derive(Debug, thiserror::Error)]
#[allow(missing_docs)]
#[error("hickory-dns resolver error: {hickory_error}")]
/// Error occurring while resolving a hostname into an IP address.
pub enum ResolveError {
#[error("invalid name: {0}")]
InvalidNameError(String),
#[error("hickory-dns resolver error: {0}")]
ResolveError(#[from] hickory_resolver::ResolveError),
#[error("high level lookup timed out")]
Timeout,
#[error("hostname not found in static lookup table")]
StaticLookupMiss,
}
impl ResolveError {
/// Returns true if the error is a timeout.
pub fn is_timeout(&self) -> bool {
matches!(self, ResolveError::Timeout)
}
pub struct HickoryDnsError {
#[from]
hickory_error: ResolveError,
}
/// Wrapper around an `AsyncResolver`, which implements the `Resolve` trait.
@@ -103,118 +87,71 @@ impl ResolveError {
/// The default initialization uses a shared underlying `AsyncResolver`. If a thread local resolver
/// is required use `thread_resolver()` to build a resolver with an independently instantiated
/// internal `AsyncResolver`.
#[derive(Debug, Clone)]
#[derive(Debug, Default, Clone)]
pub struct HickoryDnsResolver {
// Since we might not have been called in the context of a
// Tokio Runtime in initialization, so we must delay the actual
// construction of the resolver.
state: Arc<OnceCell<TokioResolver>>,
fallback: Option<Arc<OnceCell<TokioResolver>>>,
static_base: Option<Arc<OnceCell<StaticResolver>>>,
dont_use_shared: bool,
/// Overall timeout for dns lookup associated with any individual host resolution. For example,
/// use of retries, server_ordering_strategy, etc. ends absolutely if this timeout is reached.
overall_dns_timeout: Duration,
}
impl Default for HickoryDnsResolver {
fn default() -> Self {
Self {
state: Default::default(),
fallback: Default::default(),
static_base: Default::default(),
dont_use_shared: Default::default(),
overall_dns_timeout: Duration::from_secs(10),
}
}
}
impl Resolve for HickoryDnsResolver {
fn resolve(&self, name: Name) -> Resolving {
let resolver = self.state.clone();
let maybe_fallback = self.fallback.clone();
let maybe_static = self.static_base.clone();
let independent = self.dont_use_shared;
let overall_dns_timeout = self.overall_dns_timeout;
Box::pin(async move {
resolve(
name,
resolver,
maybe_fallback,
maybe_static,
independent,
overall_dns_timeout,
)
.await
.map_err(|e| Box::new(e) as Box<dyn std::error::Error + Send + Sync>)
let resolver = resolver.get_or_try_init(|| {
// using a closure here is slightly gross, but this makes sure that if the
// lazy-init returns an error it can be handled by the client
if independent {
new_resolver()
} else {
Ok(SHARED_RESOLVER.state.get_or_try_init(new_resolver)?.clone())
}
})?;
// try the primary DNS resolver that we set up (DoH or DoT or whatever)
let lookup = match resolver.lookup_ip(name.as_str()).await {
Ok(res) => res,
Err(e) => {
if let Some(ref fallback) = maybe_fallback {
// on failure use the fall back system configured DNS resolver
if !e.is_no_records_found() {
warn!("primary DNS failed w/ error {e}: using system fallback");
}
let resolver = fallback.get_or_try_init(|| {
// using a closure here is slightly gross, but this makes sure that if the
// lazy-init returns an error it can be handled by the client
if independent {
new_resolver_system()
} else {
Ok(SHARED_RESOLVER
.fallback
.as_ref()
.ok_or(e)? // if the shared resolver has no fallback return the original error
.get_or_try_init(new_resolver_system)?
.clone())
}
})?;
resolver.lookup_ip(name.as_str()).await?
} else {
return Err(e.into());
}
}
};
let addrs: Addrs = Box::new(SocketAddrs {
iter: lookup.into_iter(),
});
Ok(addrs)
})
}
}
async fn resolve(
name: Name,
resolver: Arc<OnceCell<TokioResolver>>,
maybe_fallback: Option<Arc<OnceCell<TokioResolver>>>,
maybe_static: Option<Arc<OnceCell<StaticResolver>>>,
independent: bool,
overall_dns_timeout: Duration,
) -> Result<Addrs, ResolveError> {
let resolver = resolver.get_or_try_init(|| HickoryDnsResolver::new_resolver(independent))?;
// Attempt a lookup using the primary resolver
let resolve_fut = tokio::time::timeout(overall_dns_timeout, resolver.lookup_ip(name.as_str()));
let primary_err = match resolve_fut.await {
Err(_) => ResolveError::Timeout,
Ok(Ok(lookup)) => {
let addrs: Addrs = Box::new(SocketAddrs {
iter: lookup.into_iter(),
});
return Ok(addrs);
}
Ok(Err(e)) => {
// on failure use the fall back system configured DNS resolver
if !e.is_no_records_found() {
warn!("primary DNS failed w/ error: {e}");
}
e.into()
}
};
// If the primary resolver encountered an error, attempt a lookup using the fallback
// resolver if one is configured.
if let Some(ref fallback) = maybe_fallback {
let resolver =
fallback.get_or_try_init(|| HickoryDnsResolver::new_resolver_system(independent))?;
let resolve_fut =
tokio::time::timeout(overall_dns_timeout, resolver.lookup_ip(name.as_str()));
if let Ok(Ok(lookup)) = resolve_fut.await {
let addrs: Addrs = Box::new(SocketAddrs {
iter: lookup.into_iter(),
});
return Ok(addrs);
}
}
// If no record has been found and a static map of fallback addresses is configured
// check the table for our entry
if let Some(ref static_resolver) = maybe_static {
debug!("checking static");
let resolver =
static_resolver.get_or_init(|| HickoryDnsResolver::new_static_fallback(independent));
if let Ok(addrs) = resolver.resolve(name).await {
return Ok(addrs);
}
}
Err(primary_err)
}
struct SocketAddrs {
iter: LookupIpIntoIter,
}
impl Iterator for SocketAddrs {
type Item = SocketAddr;
@@ -225,22 +162,28 @@ impl Iterator for SocketAddrs {
impl HickoryDnsResolver {
/// Attempt to resolve a domain name to a set of ['IpAddr']s
pub async fn resolve_str(
&self,
name: &str,
) -> Result<impl Iterator<Item = IpAddr> + use<>, ResolveError> {
let n =
Name::from_str(name).map_err(|_| ResolveError::InvalidNameError(name.to_string()))?;
resolve(
n,
self.state.clone(),
self.fallback.clone(),
self.static_base.clone(),
self.dont_use_shared,
self.overall_dns_timeout,
)
.await
.map(|addrs| addrs.map(|socket_addr| socket_addr.ip()))
pub async fn resolve_str(&self, name: &str) -> Result<LookupIp, HickoryDnsError> {
let resolver = self.state.get_or_try_init(|| self.new_resolver())?;
// try the primary DNS resolver that we set up (DoH or DoT or whatever)
let lookup = match resolver.lookup_ip(name).await {
Ok(res) => res,
Err(e) => {
if let Some(ref fallback) = self.fallback {
// on failure use the fall back system configured DNS resolver
if !e.is_no_records_found() {
warn!("primary DNS failed w/ error {e}: using system fallback");
}
let resolver = fallback.get_or_try_init(|| self.new_resolver_system())?;
resolver.lookup_ip(name).await?
} else {
return Err(e.into());
}
}
};
Ok(lookup)
}
/// Create a (lazy-initialized) resolver that is not shared across threads.
@@ -251,20 +194,16 @@ impl HickoryDnsResolver {
}
}
fn new_resolver(dont_use_shared: bool) -> Result<TokioResolver, ResolveError> {
// using a closure here is slightly gross, but this makes sure that if the
// lazy-init returns an error it can be handled by the client
if dont_use_shared {
fn new_resolver(&self) -> Result<TokioResolver, HickoryDnsError> {
if self.dont_use_shared {
new_resolver()
} else {
Ok(SHARED_RESOLVER.state.get_or_try_init(new_resolver)?.clone())
}
}
fn new_resolver_system(dont_use_shared: bool) -> Result<TokioResolver, ResolveError> {
// using a closure here is slightly gross, but this makes sure that if the
// lazy-init returns an error it can be handled by the client
if dont_use_shared || SHARED_RESOLVER.fallback.is_none() {
fn new_resolver_system(&self) -> Result<TokioResolver, HickoryDnsError> {
if self.dont_use_shared || SHARED_RESOLVER.fallback.is_none() {
new_resolver_system()
} else {
Ok(SHARED_RESOLVER
@@ -276,18 +215,8 @@ impl HickoryDnsResolver {
}
}
fn new_static_fallback(dont_use_shared: bool) -> StaticResolver {
if !dont_use_shared && let Some(ref shared_resolver) = SHARED_RESOLVER.static_base {
shared_resolver
.get_or_init(new_default_static_fallback)
.clone()
} else {
new_default_static_fallback()
}
}
/// Enable fallback to the system default resolver if the primary (DoX) resolver fails
pub fn enable_system_fallback(&mut self) -> Result<(), ResolveError> {
pub fn enable_system_fallback(&mut self) -> Result<(), HickoryDnsError> {
self.fallback = Some(Default::default());
let _ = self
.fallback
@@ -302,51 +231,22 @@ impl HickoryDnsResolver {
pub fn disable_system_fallback(&mut self) {
self.fallback = None;
}
/// Get the current map of hostname to address in use by the fallback static lookup if one
/// exists.
pub fn get_static_fallbacks(&self) -> Option<HashMap<String, Vec<IpAddr>>> {
Some(self.static_base.as_ref()?.get()?.get_addrs())
}
/// Set (or overwrite) the map of addresses used in the fallback static hostname lookup
pub fn set_static_fallbacks(&mut self, addrs: HashMap<String, Vec<IpAddr>>) {
let cell = OnceCell::new();
cell.set(StaticResolver::new(addrs))
.expect("infallible assign");
self.static_base = Some(Arc::new(cell));
}
}
/// Create a new resolver with a custom DoT based configuration. The options are overridden to look
/// up for both IPv4 and IPv6 addresses to work with "happy eyeballs" algorithm.
///
/// Timeout Defaults to 5 seconds
/// Number of retries after lookup failure before giving up Defaults to 2
///
/// Caches successfully resolved addresses for 30 minutes to prevent continual use of remote lookup.
/// This resolver is intended to be used for OUR API endpoints that do not rapidly rotate IPs.
fn new_resolver() -> Result<TokioResolver, ResolveError> {
info!("building new configured resolver");
fn new_resolver() -> Result<TokioResolver, HickoryDnsError> {
let mut name_servers = NameServerConfigGroup::quad9_tls();
name_servers.merge(NameServerConfigGroup::quad9_https());
name_servers.merge(NameServerConfigGroup::cloudflare_tls());
name_servers.merge(NameServerConfigGroup::cloudflare_https());
configure_and_build_resolver(name_servers)
}
fn configure_and_build_resolver(
name_servers: NameServerConfigGroup,
) -> Result<TokioResolver, ResolveError> {
let config = ResolverConfig::from_parts(None, Vec::new(), name_servers);
let mut resolver_builder =
TokioResolver::builder_with_config(config, TokioConnectionProvider::default());
resolver_builder.options_mut().ip_strategy = LookupIpStrategy::Ipv4AndIpv6;
// Cache successful responses for queries received by this resolver for 30 min minimum.
resolver_builder.options_mut().positive_min_ttl = Some(Duration::from_secs(1800));
resolver_builder.options_mut().server_ordering_strategy = ServerOrderingStrategy::RoundRobin;
Ok(resolver_builder.build())
}
@@ -354,27 +254,20 @@ fn configure_and_build_resolver(
/// Create a new resolver with the default configuration, which reads from the system DNS config
/// (i.e. `/etc/resolve.conf` in unix). The options are overridden to look up for both IPv4 and IPv6
/// addresses to work with "happy eyeballs" algorithm.
fn new_resolver_system() -> Result<TokioResolver, ResolveError> {
fn new_resolver_system() -> Result<TokioResolver, HickoryDnsError> {
let mut resolver_builder = TokioResolver::builder_tokio()?;
resolver_builder.options_mut().ip_strategy = LookupIpStrategy::Ipv4AndIpv6;
Ok(resolver_builder.build())
}
fn new_default_static_fallback() -> StaticResolver {
StaticResolver::new(constants::default_static_addrs())
}
#[cfg(test)]
mod test {
use super::*;
use itertools::Itertools;
use std::collections::HashMap;
#[tokio::test]
async fn reqwest_with_custom_dns() {
let var_name = HickoryDnsResolver::default();
let resolver = var_name;
async fn reqwest_hickory_doh() {
let resolver = HickoryDnsResolver::default();
let client = reqwest::ClientBuilder::new()
.dns_resolver(resolver.into())
.build()
@@ -393,7 +286,7 @@ mod test {
}
#[tokio::test]
async fn dns_lookup() -> Result<(), ResolveError> {
async fn dns_lookup() -> Result<(), HickoryDnsError> {
let resolver = HickoryDnsResolver::default();
let domain = "ifconfig.me";
@@ -403,124 +296,4 @@ mod test {
Ok(())
}
#[tokio::test]
async fn static_resolver_as_fallback() -> Result<(), ResolveError> {
let example_domain = "non-existent.nymvpn.com";
let mut resolver = HickoryDnsResolver {
..Default::default()
};
let result = resolver.resolve_str(example_domain).await;
assert!(result.is_err()); // should be NXDomain
resolver.static_base = Some(Default::default());
let mut addr_map = HashMap::new();
let example_ip4: IpAddr = "10.10.10.10".parse().unwrap();
let example_ip6: IpAddr = "dead::beef".parse().unwrap();
addr_map.insert(example_domain.to_string(), vec![example_ip4, example_ip6]);
resolver.set_static_fallbacks(addr_map);
let mut addrs = resolver.resolve_str(example_domain).await?;
assert!(addrs.contains(&example_ip4));
assert!(addrs.contains(&example_ip6));
Ok(())
}
}
#[cfg(test)]
mod failure_test {
use super::*;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
/// IP addresses guaranteed to fail attempts to resolve
///
/// Addresses drawn from blocks set off by RFC5737 (ipv4) and RFC3849 (ipv6)
const GUARANTEED_BROKEN_IPS_1: &[IpAddr] = &[
IpAddr::V4(Ipv4Addr::new(192, 0, 2, 1)),
IpAddr::V4(Ipv4Addr::new(198, 51, 100, 1)),
IpAddr::V6(Ipv6Addr::new(0x2001, 0x0db8, 0, 0, 0, 0, 0, 0x1111)),
IpAddr::V6(Ipv6Addr::new(0x2001, 0x0db8, 0, 0, 0, 0, 0, 0x1001)),
];
// Create a resolver that behaves the same as the custom configured router, except for the fact
// that it is guaranteed to fail.
fn build_broken_resolver() -> Result<TokioResolver, ResolveError> {
info!("building new faulty resolver");
let mut broken_ns_group = NameServerConfigGroup::from_ips_tls(
GUARANTEED_BROKEN_IPS_1,
853,
"cloudflare-dns.com".to_string(),
true,
);
let broken_ns_https = NameServerConfigGroup::from_ips_https(
GUARANTEED_BROKEN_IPS_1,
443,
"cloudflare-dns.com".to_string(),
true,
);
broken_ns_group.merge(broken_ns_https);
configure_and_build_resolver(broken_ns_group)
}
#[tokio::test]
async fn dns_lookup_failures() -> Result<(), ResolveError> {
let time_start = std::time::Instant::now();
let r = OnceCell::new();
r.set(build_broken_resolver().expect("failed to build resolver"))
.expect("broken resolver init error");
// create a new resolver that won't mess with the shared resolver used by other tests
let resolver = HickoryDnsResolver {
dont_use_shared: true,
state: Arc::new(r),
overall_dns_timeout: Duration::from_secs(5),
..Default::default()
};
build_broken_resolver()?;
let domain = "ifconfig.me";
let result = resolver.resolve_str(domain).await;
assert!(result.is_err_and(|e| matches!(e, ResolveError::Timeout)));
let duration = time_start.elapsed();
assert!(duration < resolver.overall_dns_timeout + Duration::from_secs(1));
Ok(())
}
#[tokio::test]
async fn fallback_to_static() -> Result<(), ResolveError> {
let r = OnceCell::new();
r.set(build_broken_resolver().expect("failed to build resolver"))
.expect("broken resolver init error");
// create a new resolver that won't mess with the shared resolver used by other tests
let resolver = HickoryDnsResolver {
dont_use_shared: true,
state: Arc::new(r),
static_base: Some(Default::default()),
overall_dns_timeout: Duration::from_secs(5),
..Default::default()
};
build_broken_resolver()?;
// successful lookup using fallback to static resolver
let domain = "nymvpn.com";
let _ = resolver
.resolve_str(domain)
.await
.expect("failed to resolve address in static lookup");
// unsuccessful lookup - primary times out, and not in
let domain = "non-existent.nymtech.net";
let result = resolver.resolve_str(domain).await;
assert!(result.is_err_and(|e| matches!(e, ResolveError::Timeout)));
Ok(())
}
}
@@ -1,95 +0,0 @@
#![allow(missing_docs)]
use std::collections::HashMap;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
pub const NYM_API_DOMAIN: &str = "validator.nymtech.net";
pub const NYM_API_IPS: &[IpAddr] = &[IpAddr::V4(Ipv4Addr::new(212, 71, 233, 232))];
pub const NYM_VPN_API_DOMAIN: &str = "nymvpn.com";
pub const NYM_VPN_API_IPS: &[IpAddr] = &[IpAddr::V4(Ipv4Addr::new(76, 76, 21, 21))];
pub const NYM_FRONTDOOR_VERCEL_DOMAIN: &str = "nym-frontdoor.vercel.app";
pub const NYM_FRONTDOOR_VERCEL_IPS: &[IpAddr] = &[
IpAddr::V4(Ipv4Addr::new(64, 29, 17, 195)),
IpAddr::V4(Ipv4Addr::new(216, 198, 79, 195)),
];
pub const NYM_FRONTDOOR_FASTLY_DOMAIN: &str = "nym-frontdoor.global.ssl.fastly.net";
pub const NYM_FRONTDOOR_FASTLY_IPS: &[IpAddr] = &[
IpAddr::V4(Ipv4Addr::new(151, 101, 193, 194)),
IpAddr::V4(Ipv4Addr::new(151, 101, 129, 194)),
IpAddr::V4(Ipv4Addr::new(151, 101, 1, 194)),
IpAddr::V4(Ipv4Addr::new(151, 101, 65, 194)),
];
pub const NYMVPN_FRONTDOOR_FASTLY_DOMAIN: &str = "nymvpn-frontdoor.global.ssl.fastly.net";
pub const NYMVPN_FRONTDOOR_FASTLY_IPS: &[IpAddr] = &[
IpAddr::V4(Ipv4Addr::new(151, 101, 193, 194)),
IpAddr::V4(Ipv4Addr::new(151, 101, 129, 194)),
IpAddr::V4(Ipv4Addr::new(151, 101, 1, 194)),
IpAddr::V4(Ipv4Addr::new(151, 101, 65, 194)),
];
pub const YELP_FASTLY_DOMAIN: &str = "yelp.global.ssl.fastly.net";
pub const YELP_FASTLY_IPS: &[IpAddr] = &[
IpAddr::V4(Ipv4Addr::new(151, 101, 193, 194)),
IpAddr::V4(Ipv4Addr::new(151, 101, 129, 194)),
IpAddr::V4(Ipv4Addr::new(151, 101, 1, 194)),
IpAddr::V4(Ipv4Addr::new(151, 101, 65, 194)),
];
pub const VERCEL_APP_DOMAIN: &str = "vercel.app";
pub const VERCEL_APP_IPS: &[IpAddr] = &[
IpAddr::V4(Ipv4Addr::new(64, 29, 17, 195)),
IpAddr::V4(Ipv4Addr::new(216, 198, 79, 195)),
];
pub const VERCEL_COM_DOMAIN: &str = "vercel.com";
pub const VERCEL_COM_IPS: &[IpAddr] = &[
IpAddr::V4(Ipv4Addr::new(198, 169, 2, 129)),
IpAddr::V4(Ipv4Addr::new(198, 169, 1, 193)),
];
pub const NYM_COM_DOMAIN: &str = "nym.com";
pub const NYM_COM_IPS: &[IpAddr] = &[IpAddr::V4(Ipv4Addr::new(76, 76, 21, 22))];
pub const NYM_STATS_API_DOMAIN: &str = "nym-statistics-api.nymtech.cc";
pub const NYM_STATS_API_IPS: &[IpAddr] = &[IpAddr::V4(Ipv4Addr::new(91, 92, 153, 96))];
pub const NYM_RPC_DOMAIN: &str = "rpc.nymtech.net";
pub const NYM_RPC_IPS: &[IpAddr] = &[
IpAddr::V4(Ipv4Addr::new(194, 182, 169, 49)),
IpAddr::V4(Ipv4Addr::new(91, 92, 200, 116)),
IpAddr::V6(Ipv6Addr::new(
0x2a04, 0xc43, 0xe00, 0x6f28, 0x400, 0xd8ff, 0xfe00, 0x1483,
)),
IpAddr::V6(Ipv6Addr::new(
0x2a04, 0xc46, 0xe00, 0x6f28, 0x4b3, 0x68ff, 0xfe00, 0x460,
)),
];
pub fn default_static_addrs() -> HashMap<String, Vec<IpAddr>> {
let mut m = HashMap::new();
m.insert(NYM_API_DOMAIN.to_string(), NYM_API_IPS.to_vec());
m.insert(NYM_VPN_API_DOMAIN.to_string(), NYM_VPN_API_IPS.to_vec());
m.insert(
NYM_FRONTDOOR_VERCEL_DOMAIN.to_string(),
NYM_FRONTDOOR_VERCEL_IPS.to_vec(),
);
m.insert(
NYM_FRONTDOOR_FASTLY_DOMAIN.to_string(),
NYM_FRONTDOOR_FASTLY_IPS.to_vec(),
);
m.insert(
NYMVPN_FRONTDOOR_FASTLY_DOMAIN.to_string(),
NYMVPN_FRONTDOOR_FASTLY_IPS.to_vec(),
);
m.insert(YELP_FASTLY_DOMAIN.to_string(), YELP_FASTLY_IPS.to_vec());
m.insert(VERCEL_APP_DOMAIN.to_string(), VERCEL_APP_IPS.to_vec());
m.insert(VERCEL_COM_DOMAIN.to_string(), VERCEL_COM_IPS.to_vec());
m.insert(NYM_COM_DOMAIN.to_string(), NYM_COM_IPS.to_vec());
m.insert(NYM_STATS_API_DOMAIN.to_string(), NYM_STATS_API_IPS.to_vec());
m.insert(NYM_RPC_DOMAIN.to_string(), NYM_RPC_IPS.to_vec());
m
}
@@ -1,89 +0,0 @@
use crate::dns::ResolveError;
use std::{
collections::HashMap,
net::{IpAddr, SocketAddr},
sync::{Arc, Mutex},
};
use reqwest::dns::{Addrs, Name, Resolve, Resolving};
use tracing::*;
#[derive(Debug, Default, Clone)]
pub struct StaticResolver {
static_addr_map: Arc<Mutex<HashMap<String, Vec<IpAddr>>>>,
}
impl StaticResolver {
pub fn new(static_entries: HashMap<String, Vec<IpAddr>>) -> StaticResolver {
debug!("building static resolver");
Self {
static_addr_map: Arc::new(Mutex::new(static_entries)),
}
}
pub fn get_addrs(&self) -> HashMap<String, Vec<IpAddr>> {
self.static_addr_map.lock().unwrap().clone()
}
}
impl Resolve for StaticResolver {
fn resolve(&self, name: Name) -> Resolving {
debug!("looking up {name:?} in static resolver");
let addr_map = self.static_addr_map.clone();
Box::pin(async move {
let addr_map = addr_map.lock().unwrap();
let lookup = match addr_map.get(name.as_str()) {
None => return Err(ResolveError::StaticLookupMiss.into()),
Some(addrs) => addrs,
};
let addrs: Addrs = Box::new(
lookup
.clone()
.into_iter()
.map(|ip_addr| SocketAddr::new(ip_addr, 0)),
);
Ok(addrs)
})
}
}
#[cfg(test)]
mod test {
use itertools::Itertools;
use super::*;
use std::error::Error as StdError;
use std::str::FromStr;
#[tokio::test]
async fn lookup_using_static_resolver() -> Result<(), Box<dyn StdError + Send + Sync>> {
let example_domain = String::from("static.nymvpn.com");
// lookup for domain for which there is no entry
let resolver = StaticResolver::new(HashMap::new());
let url = reqwest::dns::Name::from_str(&example_domain).unwrap();
let result = resolver.resolve(url).await;
assert!(result.is_err());
match result {
Ok(_) => panic!("lookup with empty map should fail"),
Err(e) => assert_eq!(e.to_string(), ResolveError::StaticLookupMiss.to_string()),
}
// Successful lookup
let mut addr_map = HashMap::new();
let example_ip4: IpAddr = "10.10.10.10".parse().unwrap();
let example_ip6: IpAddr = "dead::beef".parse().unwrap();
addr_map.insert(example_domain.clone(), vec![example_ip4, example_ip6]);
let url = reqwest::dns::Name::from_str(&example_domain).unwrap();
let resolver = StaticResolver::new(addr_map);
let mut addrs = resolver.resolve(url).await?;
assert!(addrs.contains(&SocketAddr::new(example_ip4, 0)));
assert!(addrs.contains(&SocketAddr::new(example_ip6, 0)));
Ok(())
}
}
-85
View File
@@ -121,89 +121,4 @@ mod tests {
// println!("{response:?}");
assert_eq!(response.status(), 200);
}
#[tokio::test]
async fn fallback_on_failure() {
let url1 = Url::new(
"https://fake-domain.nymtech.net",
Some(vec![
"https://fake-front-1.nymtech.net",
"https://fake-front-2.nymtech.net",
]),
)
.unwrap();
let url2 = Url::new(
"https://validator.global.ssl.fastly.net",
Some(vec!["https://yelp.global.ssl.fastly.net"]),
)
.unwrap(); // fastly
let client = ClientBuilder::new_with_urls(vec![url1, url2])
.expect("bad url")
.with_fronting(FrontPolicy::Always)
.build()
.expect("failed to build client");
// Check that the initial configuration has the broken domain and front.
assert_eq!(
client.current_url().as_str(),
"https://fake-domain.nymtech.net/",
);
assert_eq!(
client.current_url().front_str(),
Some("fake-front-1.nymtech.net"),
);
let result = client
.send_request::<_, (), &str, &str>(
reqwest::Method::GET,
&["api", "v1", "network", "details"],
NO_PARAMS,
None,
)
.await;
assert!(result.is_err());
// Check that the host configuration updated the front on error.
assert_eq!(
client.current_url().as_str(),
"https://fake-domain.nymtech.net/",
);
assert_eq!(
client.current_url().front_str(),
Some("fake-front-2.nymtech.net"),
);
let result = client
.send_request::<_, (), &str, &str>(
reqwest::Method::GET,
&["api", "v1", "network", "details"],
NO_PARAMS,
None,
)
.await;
assert!(result.is_err());
// Check that the host configuration updated the domain and front on error.
assert_eq!(
client.current_url().as_str(),
"https://validator.global.ssl.fastly.net/",
);
assert_eq!(
client.current_url().front_str(),
Some("yelp.global.ssl.fastly.net"),
);
let response = client
.send_request::<_, (), &str, &str>(
reqwest::Method::GET,
&["api", "v1", "network", "details"],
NO_PARAMS,
None,
)
.await
.expect("failed get request");
assert_eq!(response.status(), 200);
}
}
+17 -89
View File
@@ -179,7 +179,7 @@ mod dns;
mod path;
#[cfg(not(target_arch = "wasm32"))]
pub use dns::{HickoryDnsResolver, ResolveError};
pub use dns::{HickoryDnsError, HickoryDnsResolver};
// helper for generating user agent based on binary information
#[cfg(not(target_arch = "wasm32"))]
@@ -395,13 +395,6 @@ pub enum HttpClientError {
#[error("failed to resolve request to {url} due to data inconsistency: {details}")]
InternalResponseInconsistency { url: ::url::Url, details: String },
#[cfg(not(target_arch = "wasm32"))]
#[error("encountered dns failure: {inner}")]
DnsLookupFailure {
#[from]
inner: ResolveError,
},
#[error("Failed to encode bincode: {0}")]
Bincode(#[from] bincode::Error),
@@ -428,8 +421,6 @@ impl HttpClientError {
HttpClientError::ReqwestClientError { source } => source.is_timeout(),
HttpClientError::RequestSendFailure { source, .. } => source.0.is_timeout(),
HttpClientError::ResponseReadFailure { source, .. } => source.0.is_timeout(),
#[cfg(not(target_arch = "wasm32"))]
HttpClientError::DnsLookupFailure { inner } => inner.is_timeout(),
#[cfg(target_arch = "wasm32")]
HttpClientError::RequestTimeout => true,
_ => false,
@@ -784,7 +775,6 @@ impl ClientBuilder {
base_urls: self.urls,
current_idx: Arc::new(AtomicUsize::new(0)),
reqwest_client,
using_secure_dns: self.use_secure_dns,
#[cfg(feature = "tunneling")]
front: self.front,
@@ -805,7 +795,6 @@ pub struct Client {
base_urls: Vec<Url>,
current_idx: Arc<AtomicUsize>,
reqwest_client: reqwest::Client,
using_secure_dns: bool,
#[cfg(feature = "tunneling")]
front: Option<fronted::Front>,
@@ -863,7 +852,6 @@ impl Client {
base_urls: vec![new_url],
current_idx: Arc::new(Default::default()),
reqwest_client: self.reqwest_client.clone(),
using_secure_dns: self.using_secure_dns,
#[cfg(feature = "tunneling")]
front: self.front.clone(),
@@ -895,34 +883,8 @@ impl Client {
self.retry_limit = limit;
}
fn matches_current_host(&self, url: &Url) -> bool {
if cfg!(feature = "tunneling") {
if let Some(ref front) = self.front
&& front.is_enabled()
{
url.host_str() == self.current_url().front_str()
} else {
url.host_str() == self.current_url().host_str()
}
} else {
url.host_str() == self.current_url().host_str()
}
}
/// If multiple base urls are available rotate to next (e.g. when the current one resulted in an error)
///
/// Takes an optional URL argument. If this is none, the current host will be updated automatically.
/// If a url is provided first check that the CURRENT host matches the hostname in the URL before
/// triggering a rotation. This is meant to prevent parallel requests that fail from rotating the host
/// multiple times.
fn update_host(&self, maybe_url: Option<Url>) {
// If a causal url is provided and it doesn't match the hostname currently in use, skip update.
if let Some(err_url) = maybe_url
&& !self.matches_current_host(&err_url)
{
return;
}
fn update_host(&self) {
#[cfg(feature = "tunneling")]
if let Some(ref front) = self.front
&& front.is_enabled()
@@ -1086,28 +1048,8 @@ impl ApiClientCore for Client {
.build()
.map_err(HttpClientError::reqwest_client_build_error)?;
self.apply_hosts_to_req(&mut req);
let url: Url = req.url().clone().into();
// try an explicit DNS resolution - if successful then it will be in cache when reqwest
// goes to execute the request. If failure then we get to handle the DNS lookup error.
#[cfg(not(target_arch = "wasm32"))]
if self.using_secure_dns
&& let Some(hostname) = req.url().domain()
// Default here will use a shared resolver instance
&& let Err(err) = HickoryDnsResolver::default().resolve_str(hostname).await
{
// on failure update host, but don't trigger fronting enable.
self.update_host(Some(url.clone()));
if attempts < self.retry_limit {
attempts += 1;
warn!(
"Retrying request due to dns error on attempt ({attempts}/{}): {err}",
self.retry_limit
);
continue;
}
}
let url = req.url().clone();
#[cfg(target_arch = "wasm32")]
let response: Result<Response, HttpClientError> = {
@@ -1125,39 +1067,25 @@ impl ApiClientCore for Client {
match response {
Ok(resp) => return Ok(resp),
Err(err) => {
// only if there was a network issue should we consider updating the host info
//
// note: for now this includes DNS resolution failure, I am not sure how I would go about
// segregating that based on the interface provided by request for errors.
#[cfg(target_arch = "wasm32")]
let is_network_err = err.is_timeout();
#[cfg(not(target_arch = "wasm32"))]
let is_network_err = err.is_timeout() || err.is_connect();
// if we have multiple urls, update to the next
self.update_host();
if is_network_err {
// if we have multiple urls, update to the next
self.update_host(Some(url.clone()));
#[cfg(feature = "tunneling")]
if let Some(ref front) = self.front {
// If fronting is set to be enabled on error, enable domain fronting as we
// have encountered an error.
let was_enabled = front.is_enabled();
front.retry_enable();
if !was_enabled && front.is_enabled() {
tracing::info!(
"Domain fronting activated after connection failure: {err}",
);
}
#[cfg(feature = "tunneling")]
if let Some(ref front) = self.front {
// If fronting is set to be enabled on error, enable domain fronting as we
// have encountered an error.
let was_enabled = front.is_enabled();
front.retry_enable();
if !was_enabled && front.is_enabled() {
tracing::info!(
"Domain fronting activated after connection failure: {err}",
);
}
}
if attempts < self.retry_limit {
warn!("Retrying request due to http error: {err}");
attempts += 1;
warn!(
"Retrying request due to http error on attempt ({attempts}/{}): {err}",
self.retry_limit
);
continue;
}
@@ -1166,7 +1094,7 @@ impl ApiClientCore for Client {
if #[cfg(target_arch = "wasm32")] {
return Err(err);
} else {
return Err(HttpClientError::request_send_error(url.into(), err));
return Err(HttpClientError::request_send_error(url, err));
}
}
}
+11 -35
View File
@@ -91,15 +91,14 @@ fn sanitizing_urls() {
#[tokio::test]
async fn api_client_retry() -> Result<(), Box<dyn std::error::Error>> {
let client = ClientBuilder::new_with_urls(vec![
"http://broken.nym.test".parse()?, // This will fail because of DNS (rotate)
"http://127.0.0.1:9".parse()?, // This will fail because of TCP refused (rotate)
"https://httpbin.org/status/200".parse()?, // This should succeed
"http://broken.nym.test".parse()?, // This will fail
"https://httpbin.org/status/200".parse()?, // This will succeed
])?
.with_retries(3)
.build()?;
let req = client.create_get_request(&[], NO_PARAMS).unwrap();
let _resp = client.send(req).await?;
let resp = client.send(req).await?;
// The main test is that we successfully retried and switched to the working URL
// We accept any response from the working endpoint since external services can be unreliable
@@ -108,9 +107,7 @@ async fn api_client_retry() -> Result<(), Box<dyn std::error::Error>> {
"https://httpbin.org/status/200"
);
// // This assert can be unreliable due to factors beyond our control and beyond the scope of
// // this test
// assert_eq!(_resp.status(), StatusCode::OK);
println!("Response status: {}", resp.status());
Ok(())
}
@@ -126,7 +123,7 @@ fn host_updating() {
assert_eq!(current_url.front_str(), None);
// update the url
client.update_host(None);
client.update_host();
// check that the url is still the same since there is one URL
assert_eq!(client.current_url().as_str(), "http://nym-api1.test/");
@@ -141,13 +138,13 @@ fn host_updating() {
client.change_base_urls(new_urls);
assert_eq!(client.current_url().as_str(), "http://nym-api1.test/");
client.update_host(None);
client.update_host();
// check that the url got updated now that there are multiple URLs
assert_eq!(client.current_url().as_str(), "http://nym-api2.test/");
assert_eq!(client.current_url().front_str(), None);
client.update_host(None);
client.update_host();
assert_eq!(client.current_url().as_str(), "http://nym-api1.test/");
// =======================================
@@ -165,33 +162,12 @@ fn host_updating() {
assert_eq!(client.current_url().as_str(), "http://nym-api1.test/");
client.update_host(None);
client.update_host();
// check that the url got updated now that there are multiple URLs
assert_eq!(client.current_url().as_str(), "http://nym-api2.test/");
}
#[test]
fn host_updating_url_conditioned() {
let url1 = Url::new("http://nym-api1.test", None).unwrap();
let url2 = Url::new("http://nym-api2.test", None).unwrap();
let urls = vec![url1.clone(), url2.clone()];
let client = ClientBuilder::new_with_urls(urls).unwrap().build().unwrap();
assert_eq!(client.current_url().as_str(), "http://nym-api1.test/");
// Try to update with a URL that does NOT match current - should result in no change
client.update_host(Some(Url::parse("http://example.com").unwrap()));
// check that the url did NOT get updated
assert_eq!(client.current_url().as_str(), "http://nym-api1.test/");
assert_eq!(client.current_url().front_str(), None);
// Try to update with a URL that DOES match current - should result in no change
client.update_host(Some(url1));
assert_eq!(client.current_url().as_str(), "http://nym-api2.test/");
}
#[test]
#[cfg(feature = "tunneling")]
fn fronted_host_updating() {
@@ -208,7 +184,7 @@ fn fronted_host_updating() {
assert_eq!(current_url.front_str(), Some("cdn1.test"));
// update the url
client.update_host(None);
client.update_host();
// check that the url is still the same since there is one URL and one front
let current_url = client.current_url();
@@ -233,7 +209,7 @@ fn fronted_host_updating() {
assert_eq!(current_url.front_str(), Some("cdn1.test"));
// update the url - this should keep the same host but change the front
client.update_host(None);
client.update_host();
let current_url = client.current_url();
// check that the url is still the same since there is one URL
@@ -241,7 +217,7 @@ fn fronted_host_updating() {
assert_eq!(current_url.front_str(), Some("cdn2.test"));
// update the url - this should wrap around to the first front as the second url is not fronted
client.update_host(None);
client.update_host();
let current_url = client.current_url();
assert_eq!(current_url.as_str(), "http://nym-api.test/");
-21
View File
@@ -54,11 +54,6 @@ pub const NYM_APIS: &[ApiUrlConst] = &[
];
pub const NYM_VPN_API: &str = "https://nymvpn.com/api/";
pub const UPGRADE_MODE_ATTESTATION_URL: &str = "https://nym.com/upgrade-mode/attestation.json";
pub const UPGRADE_MODE_ATTESTER_ED25519_BS58_PUBKEY: &str =
"3bgffBYcfFkTTXc2npNNn9MkddFZ3H2LrPjXDmnJzrqd";
#[cfg(feature = "network")]
pub const NYM_VPN_APIS: &[ApiUrlConst] = &[
ApiUrlConst {
@@ -164,14 +159,6 @@ pub fn export_to_env() {
set_var_to_default(var_names::NYXD_WEBSOCKET, NYXD_WS);
set_var_to_default(var_names::EXIT_POLICY_URL, EXIT_POLICY_URL);
set_var_to_default(var_names::NYM_VPN_API, NYM_VPN_API);
set_var_to_default(
var_names::UPGRADE_MODE_ATTESTATION_URL,
UPGRADE_MODE_ATTESTATION_URL,
);
set_var_to_default(
var_names::UPGRADE_MODE_ATTESTER_ED25519_BS58_PUBKEY,
UPGRADE_MODE_ATTESTER_ED25519_BS58_PUBKEY,
);
}
#[cfg(all(feature = "env", feature = "network"))]
@@ -212,12 +199,4 @@ pub fn export_to_env_if_not_set() {
set_var_conditionally_to_default(var_names::NYM_API, NYM_API);
set_var_conditionally_to_default(var_names::NYXD_WEBSOCKET, NYXD_WS);
set_var_conditionally_to_default(var_names::EXIT_POLICY_URL, EXIT_POLICY_URL);
set_var_conditionally_to_default(
var_names::UPGRADE_MODE_ATTESTATION_URL,
UPGRADE_MODE_ATTESTATION_URL,
);
set_var_conditionally_to_default(
var_names::UPGRADE_MODE_ATTESTER_ED25519_BS58_PUBKEY,
UPGRADE_MODE_ATTESTER_ED25519_BS58_PUBKEY,
);
}
-2
View File
@@ -25,8 +25,6 @@ pub const NYXD_WEBSOCKET: &str = "NYXD_WS";
pub const EXIT_POLICY_URL: &str = "EXIT_POLICY";
pub const NYM_VPN_API: &str = "NYM_VPN_API";
pub const CLIENT_STATS_COLLECTION_PROVIDER: &str = "CLIENT_STATS_COLLECTION_PROVIDER";
pub const UPGRADE_MODE_ATTESTATION_URL: &str = "UPGRADE_MODE_ATTESTATION_URL";
pub const UPGRADE_MODE_ATTESTER_ED25519_BS58_PUBKEY: &str = "UPGRADE_MODE_ATTESTER_ED25519_PUBKEY";
pub const DKG_TIME_CONFIGURATION: &str = "DKG_TIME_CONFIGURATION";
@@ -1,40 +0,0 @@
import Box from '@mui/material/Box';
import { Steps } from 'nextra/components'
import { Tabs } from 'nextra/components'
import { GitHubRepoSearch } from '../../code-snippets/mixfetchurl';
# Integration Options
Developers might want to either integrate a Mixnet client or just to interact with the blockchain. See the relevant section below.
## Integrating Mixnet Functionality
There are several options available to developers wanting to embed a Nym client in their application code.
<Tabs items={['Rust/Go/C++', 'Typescript/Javascript','Other']}>
<Tabs.Tab >
<>
Rust developers can rely on our Rust SDK to import Nym client functionality into their code. This can either be in the form of a standard message-based client, the `socks5` client, or the `TcpProxy` modules.
We aim to expose at least the majority of this functionality via FFI to Go and C/C++. This is detailed alongside the Rust SDK components in the [Rust SDK docs](./rust).
</>
</Tabs.Tab>
<Tabs.Tab>
<>
Typescript and Javascript developers have several options avaliable to them:
- [`mixfetch`](./typescript/examples/mix-fetch) is an almost-dropin replacement for the `fetch` library. The best way to integrate Nym's `mixFetch` into your application will be where external network calls and RPC happens, for example, something in the lines of `sendRawTransaction` if you have an ETH-compatible wallet or `JsonRpcClient` if you use CosmJS. Although you can simply search for any JS `fetch` calls in your code (using our tool below) that are easily replaceable with `mixFetch`, keep in mind that `fetch` is not the only way to make `JSONRPC` or `XHR` calls. We advise to approach the integration process in a semantic way, searching for a module that is the common denominator for external communication in the codebase. Usually these are API controllers, middlewares or repositories.
<GitHubRepoSearch />
- Otherwise, a well-modularized JS/TS codebase should permit the integration of one of our other SDK components, which will allow more flexibility and control (or if your codebase is not using something that can be covered by `fetch` for networking). Read more about our different SDK components in the [TS SDK overview page](./typescript/overview).
</ >
</Tabs.Tab>
<Tabs.Tab> If your app is not written in any of the supported languages, you might still be able to send traffic through a standalone [socks5 client](./clients/socks5) but will have to think about packaging and bundling the client binary with e.g. a `systemd` file for autostart to run the client as a daemon. If you want to discuss FFI options reach out to us via our public dev channel. </Tabs.Tab>
</Tabs>
## Interacting with Nyx
If instead of relying on the Mixnet you wish to interact with the Nyx chain, either as a payment processor or to get on-chain events, see [interacting with the chain](./chain).
> Note that depending on your setup, you might already be able to combine interacting with the chain with using the Mixnet: check the options above for more.
+4 -3
View File
@@ -9,12 +9,13 @@ import Stack from "@mui/material/Stack";
import Paper from "@mui/material/Paper";
import type { SetupMixFetchOps } from "@nymproject/mix-fetch-full-fat";
const defaultUrl =
"https://nymtech.net/.wellknown/network-requester/exit-policy.txt";
const defaultUrl = "https://nymtech.net/.wellknown/network-requester/exit-policy.txt";
const args = { mode: "unsafe-ignore-cors" };
const mixFetchOptions: SetupMixFetchOps = {
preferredGateway: "q2A2cbooyC16YJzvdYaSMH9X3cSiieZNtfBr8cE8Fi1",
preferredGateway: "2xU4CBE6QiiYt6EyBXSALwxkNvM7gqJfjHXaMkjiFmYW", // with WSS
// preferredNetworkRequester:
// "CTDxrcXgrZHWyCWnuCgjpJPghQUcEVz1HkhUr5mGdFnT.3UAww1YWNyVNYNWFQL1LaHYouQtDiXBGK5GiDZgpXkTK@2RFtU5BwxvJJXagAWAEuaPgb5ZVPRoy2542TT93Edw6v",
mixFetchOverride: {
requestTimeoutMs: 60_000,
},
@@ -0,0 +1,266 @@
import { Callout } from 'nextra/components';
import { Tabs } from 'nextra/components';
import { Steps } from 'nextra/components';
import { AccordionTemplate } from 'components/accordion-template.tsx';
export const ManagerIPOutput = () => (
<div>
Correct <code>./network-tunnel-manager.sh fetch_and_display_ipv6</code> output
</div>
);
export const ManagerTablesOutput = () => (
<div>
Correct <code>./network-tunnel-manager.sh check_nymtun_iptables</code> output
</div>
);
export const ShowTun = () => (
<div>
Correct <code>ip addr show nymtun0</code> output
</div>
);
<Callout>
We recommend operators to configure their `nym-node` with the full routing configuration.
However, most of the time the packets sent through the Mixnet are IPv4 based. The IPv6 packets are still pretty rare and therefore it's not mandatory from operational point of view to have this configuration implemented if you running only `mixnode` mode.
If you preparing to run a `nym-node` with all modes enabled in the future, this setup is required.
</Callout>
<Callout type="warning" emoji="⚠️">
Networking configuration across different ISPs and various operation systems does not have a generic solution. If the provided configuration setup doesn't solve your problem check out [IPv6 troubleshooting](/operators/troubleshooting/vps-isp.mdx#ipv6-troubleshooting) page. Be aware that you may have to do more research, customised adjustments or contact your ISP to change settings for your VPS.
</ Callout>
**Network Tunnel Manager ([`network-tunnel-manager.sh`](https://github.com/nymtech/nym/blob/develop/scripts/network_tunnel_manager.sh), NTM) is currently the one tool hadling the configuration of `nym-node` hosting server, according to the required design (node's [functionality](/operators/nodes/nym-node/setup#functionality-mode), WireGuard setup etc).**
**NTM cand administrate these areas:**
* IPv4 and IPv6 routing to the internet
* The `nymtun0` interface (Mixnet / 5-hop): dynamically managed by the `exit-gateway` service. When the service is stopped, `nymtun0` disappears, and when started, `nymtun0` is recreated.
* The `nymwg` interface (WG / 2-hop): used for creating a secure wireguard tunnel as part of the Nym Network configuration.
* `iptables` rules specific to `nymwg` to ensure proper routing and forwarding through the wireguard tunnel. The `nymwg` interface needs to be correctly configured and active for the related commands to function properly. This includes applying or removing iptables rules and running connectivity tests through the `nymwg` tunnel.
* WireGuard exit policy: Mixnet uses a common [exit policy](https://nymtech.net/.wellknown/network-requester/exit-policy.txt), to apply the same for WG, the operators need to set that one up on their server using `iptables` rules.
* Testing and validating all above
**Before starting with the following configuration, make sure you have the [latest `nym-node` binary](https://github.com/nymtech/nym/releases) installed and your [VPS setup](../preliminary-steps/vps-setup.mdx) finished properly!**
<Callout type="warning" emoji="⚠️">
**Run the following steps as root!**
</ Callout>
**Choose configuration command according your setup**
<div>
<Tabs items={[
<strong>New <code>nym-node</ code> full configuration</strong>,
<strong>Existing <code>nym-node</ code> full configuration</strong>,
<strong>Step-by-step or Pprtial configuration</strong>
]} defaultIndex={0}>
<Tabs.Tab>
This design is meant for operators setting up a new node on a fresh machine and it will result with a complete server readiness for routing as Entry Gateway and Exit Gateway in both Mixnet and WireGuard mode.
<Steps>
###### 1. Download `network-tunnel-manager.sh`, make executable and run with `--help` command:
```sh
curl -L https://raw.githubusercontent.com/nymtech/nym/refs/heads/develop/scripts/nym-node-setup/network-tunnel-manager.sh -o network-tunnel-manager.sh && \
chmod +x network-tunnel-manager.sh && \
./network-tunnel-manager.sh --help
```
###### 2. Make sure your `nym-node` service is up and running and bonded
- **If you setting up a new node and not upgrading an existing one, keep it running and [bond](/operators/nodes/nym-node/bonding.mdx) your node now! Then come back here and follow the rest of the configuration.**
###### 3. Execute complete network configuration:
```sh
./network-tunnel-manager.sh complete_networking_setup
```
</ Steps>
</Tabs.Tab>
<Tabs.Tab>
This is meant for operators configuring an existing and bonded node and it will result with a complete server readiness for routing as Entry Gateway and Exit Gateway in both Mixnet and WireGuard mode.
<Steps>
###### 1. Download `network-tunnel-manager.sh`, make executable and run with `--help` command:
```sh
curl -L https://raw.githubusercontent.com/nymtech/nym/refs/heads/develop/scripts/nym-node-setup/network-tunnel-manager.sh -o network-tunnel-manager.sh && \
chmod +x network-tunnel-manager.sh && \
./network-tunnel-manager.sh --help
```
###### 2. Execute complete network configuration:
```sh
./network-tunnel-manager.sh complete_networking_setup
```
</ Steps>
</Tabs.Tab>
<Tabs.Tab>
<Steps>
This design is meant for operators who want to do their server configuration step by step or choose only some parts of the setup.
###### 1. Download `network-tunnel-manager.sh`, make executable and run with `--help` command:
```sh
curl -L https://raw.githubusercontent.com/nymtech/nym/refs/heads/develop/scripts/nym-node-setup/network-tunnel-manager.sh -o network-tunnel-manager.sh && \
chmod +x network-tunnel-manager.sh && \
./network-tunnel-manager.sh --help
```
###### 2. Make sure your `nym-node` service is up and running and bonded
- **If you setting up a new node and not upgrading an existing one, keep it running and [bond](/operators/nodes/nym-node/bonding.mdx) your node now! Then come back here and follow the rest of the configuration.**
###### 3. Choose steps according your need
> You should be certain in your selection when configuring only various parts of the server.
###### Setup IP tables rules
- Delete IP tables rules for IPv4 and IPv6 and apply new ones:
```sh
./network-tunnel-manager.sh remove_duplicate_rules nymtun0
./network-tunnel-manager.sh apply_iptables_rules
```
- The process may prompt you if you want to save current IPv4 and IPv6 rules, choose yes.
![](/images/operators/ip_table_prompt.png)
- At this point you should see a `global ipv6` address.
```sh
./network-tunnel-manager.sh fetch_and_display_ipv6
```
<br />
<AccordionTemplate name={<ManagerTablesOutput/>}>
```sh
iptables-persistent is already installed.
Using IPv6 address: 2001:db8:a160::1/112 #the address will be different for you
operation fetch_ipv6_address_nym_tun completed successfully.
```
</AccordionTemplate>
###### Check Nymtun IP tables:
```sh
./network-tunnel-manager.sh check_nymtun_iptables
```
- If there's no process running it wouldn't return anything.
- In case you see `nymtun0` but not active, this is probably because you are setting up a new (never bonded) node and not upgrading an existing one.
<br />
<AccordionTemplate name={<ManagerIPOutput/>}>
```sh
iptables-persistent is already installed.
network Device: eth0
---------------------------------------
inspecting IPv4 firewall rules...
Chain FORWARD (policy DROP 0 packets, 0 bytes)
0 0 ufw-reject-forward all -- * * 0.0.0.0/0 0.0.0.0/0
0 0 ACCEPT all -- nymtun0 eth0 0.0.0.0/0 0.0.0.0/0
0 0 ACCEPT all -- eth0 nymtun0 0.0.0.0/0 0.0.0.0/0 state RELATED,ESTABLISHED
0 0 ACCEPT all -- nymtun0 eth0 0.0.0.0/0 0.0.0.0/0
0 0 ACCEPT all -- eth0 nymtun0 0.0.0.0/0 0.0.0.0/0 state RELATED,ESTABLISHED
0 0 ACCEPT all -- nymtun0 eth0 0.0.0.0/0 0.0.0.0/0
0 0 ACCEPT all -- eth0 nymtun0 0.0.0.0/0 0.0.0.0/0 state RELATED,ESTABLISHED
---------------------------------------
inspecting IPv6 firewall rules...
Chain FORWARD (policy DROP 0 packets, 0 bytes)
0 0 ufw6-reject-forward all * * ::/0 ::/0
0 0 ACCEPT all eth0 nymtun0 ::/0 ::/0 state RELATED,ESTABLISHED
0 0 ACCEPT all nymtun0 eth0 ::/0 ::/0
0 0 ACCEPT all eth0 nymtun0 ::/0 ::/0 state RELATED,ESTABLISHED
0 0 ACCEPT all nymtun0 eth0 ::/0 ::/0
0 0 ACCEPT all eth0 nymtun0 ::/0 ::/0 state RELATED,ESTABLISHED
0 0 ACCEPT all nymtun0 eth0 ::/0 ::/0
operation check_nymtun_iptables completed successfully.
```
</AccordionTemplate>
###### Remove old and apply new rules for wireguad routing
```sh
../network-tunnel-manager.sh remove_duplicate_rules nymwg
./network-tunnel-manager.sh apply_iptables_rules_wg
```
###### Apply rules to configure DNS routing and allow ICMP piung test for node probing (network testing)
```sh
./network-tunnel-manager.sh configure_dns_and_icmp_wg
```
###### Adjust and validate IP forwarding
```sh
./network-tunnel-manager.sh adjust_ip_forwarding
./network-tunnel-manager.sh check_ipv6_ipv4_forwarding
```
###### Check `nymtun0` interface and test routing configuration
```sh
ip addr show nymtun0
```
<br />
<AccordionTemplate name={<ShowTun/>}>
```sh
# your addresses will be different
8: nymtun0: <POINTOPOINT,MULTICAST,NOARP,UP,LOWER_UP> mtu 1420 qdisc fq_codel state UNKNOWN group default qlen 500
link/none
inet 10.0.0.1/16 scope global nymtun0
valid_lft forever preferred_lft forever
inet6 fc00::1/112 scope global
valid_lft forever preferred_lft forever
inet6 fe80::ad08:d167:5700:8c7c/64 scope link stable-privacy
valid_lft forever preferred_lft forever`
```
</AccordionTemplate>
- Validate your IPv6 and IPv4 networking by running a joke test via Mixnet:
```sh
./network-tunnel-manager.sh joke_through_the_mixnet
```
- Validate your tunneling by running a joke test via WG:
```sh
../network-tunnel-manager.sh joke_through_wg_tunnel
```
###### Enable wireguard
Now you can run your node with the `--wireguard-enabled true` flag or add it to your [systemd service config](#systemd). Restart your `nym-node` or [systemd](#2-following-steps-for-nym-nodes-running-as-systemd-service) service (recommended):
```sh
systemctl daemon-reload && service nym-node restart
```
- Optionally, you can check if the node is running correctly by monitoring the service logs:
```sh
journalctl -u nym-node.service -f -n 100
```
</ Steps>
</Tabs.Tab>
</Tabs>
</div>
<Callout type="info" emoji="️">
Note that the functionality the node runs in is decided by [arguments on the node itself / in node's `config.toml`](/operators/nodes/nym-node/setup#functionality-mode), this tool only prepares the server.
</ Callout>
Make sure that you get the validation of all connectivity. If there are still any problems, please refer to [troubleshooting section](/operators/troubleshooting/vps-isp.mdx#incorrect-gateway-network-check).
@@ -0,0 +1,68 @@
import { Callout } from 'nextra/components';
import { Tabs } from 'nextra/components';
import { Steps } from 'nextra/components';
import { AccordionTemplate } from 'components/accordion-template.tsx';
import ExitPolicyInstallOutput from 'components/operators/snippets/wg-exit-policy-install-output.mdx';
import ExitPolicyStatusOutput from 'components/operators/snippets/wg-exit-policy-status-output.mdx';
<Callout type="info" emoji="️">
**In case you had used `network-tunnel-manager.sh` with the command `complete_networking_setup`, your WireGuard exit policy is already setup. You can test it in the next chapter.**
</ Callout>
Nym Node running as Exit Gateway has contains multiple modules, one of them is Nym Network Requester(NR), routing TCP traffic to the internet. To make sure that the node is not just an open proxy, NR checks agains [Nym exit policy](https://nymtech.net/.wellknown/network-requester/exit-policy.txt) following these conditions (in this exact order):
1. Do we explicitly block those IP addresses regardless of ports?
2. Do we allow those specific ports regardless of IPs?
3. Do block EVERYTHING else!
The exit policy is same for all NRs, the content is shaped by an offchain governance of Nym Node operators on our [forum](https://forum.nym.com/t/poll-a-new-nym-exit-policy-for-exit-gateways-and-the-nym-mixnet-is-inbound/464).
There is a caveat though. NR is only routing TCP streams and therefore any other type of routing than Mixnet is *not* filtered thorugh the exit policy. To ensure that Nym Nodes follow the same exit policy when routing IP packets through WireGuard and don't act as open proxies, the operators have to set up these rules via IP tables rules.
**For all routing configuration we provide one tool [`network-tunnel-manager.sh` (NTM)](https://raw.githubusercontent.com/nymtech/nym/refs/heads/develop/scripts/wireguard-exit-policy/wireguard-exit-policy-manager.sh). This tool manages WireGuard exit policy as well.**
In case you haven't run `network-tunnel-manager.sh` with the command `complete_networking_setup` you need to use NTM for WireGuard exit policy configuration.
**Folow these steps**
<Callout type="warning" emoji="⚠️">
**Run the following steps as root!**
</ Callout>
<Steps>
###### 1. Download `network-tunnel-manager.sh`, make executable and run with `--help` command:
```sh
curl -L https://raw.githubusercontent.com/nymtech/nym/refs/heads/develop/scripts/nym-node-setup/network-tunnel-manager.sh -o network-tunnel-manager.sh && \
chmod +x network-tunnel-manager.sh && \
./network-tunnel-manager.sh --help
```
###### 2. Install exit policy
- Clear old rules and configure new ones:
```sh
./network-tunnel-manager.sh exit_policy_clear
./network-tunnel-manager.sh exit_policy_install
```
- The output should look like this:
<AccordionTemplate name="Cosole output">
<ExitPolicyInstallOutput />
</ AccordionTemplate>
###### 3. Check status of your configuration
```sh
./network-tunnel-manager.sh exit_policy_status
```
- The output should look like this:
<AccordionTemplate name="Cosole output">
<ExitPolicyStatusOutput />
</ AccordionTemplate>
</ Steps>
Now your WireGuard routing (2-hop) should have same rotuing permissions like [Nym exit policy](https://nymtech.net/.wellknown/network-requester/exit-policy.txt) used on 5-hop (Mixnet) mode of NymVPN.
@@ -0,0 +1,39 @@
import { Tabs } from 'nextra/components';
import { Steps } from 'nextra/components';
import ExitPolicyTestServer from 'components/operators/snippets/wg-exit-policy-testing-from-server.mdx';
import ExitPolicyTestOutside from 'components/operators/snippets/wg-exit-policy-testing-from-outside.mdx';
**For all routing configuration we provide one tool [`network-tunnel-manager.sh` (NTM)](https://raw.githubusercontent.com/nymtech/nym/refs/heads/develop/scripts/wireguard-exit-policy/wireguard-exit-policy-manager.sh). This tool manages WireGuard tests all configurations, including WireGuard exit policy as well.**
You can use NTM to validate the application of the IP tables routes on your `nym-node` by checking it from the server side as well as from the outside.
<div>
<Tabs items={[
<strong>From the server</strong>,
<strong>From the outside - using NymVPN</strong>
]} defaultIndex={0}>
<Tabs.Tab><ExitPolicyTestServer /></Tabs.Tab>
<Tabs.Tab><ExitPolicyTestOutside /></Tabs.Tab>
</Tabs>
</div>
If all works , your node has successfully implemented WireGuard exit policy with the same routing permissions like [Nym exit policy](https://nymtech.net/.wellknown/network-requester/exit-policy.txt) used on 5-hop (Mixnet) for TCP routing.
@@ -1,9 +1,29 @@
import { Steps } from 'nextra/components';
Here are a few ways you can ensre your WireGuard exit policy is working correctly from the outside.
<Steps>
###### 1. Using NymVPN
- Connect to NymVPN and use your node as an Exit Gateway in dVPN (2-hop) mode
- While connected to NymVPN, navigate to [`portquiz.net:12345`](http://portquiz.net:12345) and see if you can load the page
- It shouldn't load, but if you navigate to some of the accepted ports, like[`portquiz.net:443`](http://portquiz.net:443) it should all work
###### 2. Testing from your local terminal
- Install these dependencies on your local machine:
```shell
sudo apt install tcpdump
sudo tcpdump -i nymwg -n
```
- Connect to [NymVPN](https://nym.com) and select your node as an Exit Gateway (after running the exit policy [manager script](#wireguard-exit-policy-configuration))
- Connect to [NymVPN](https://nym.com) and select your node as an Exit Gateway
- Run the `tcpdump` command before registering
- Have the output of the `echo $BLOCKED_IP` from your node and try to go into your browser or a registered client and try to connect - It will not resolve.
- Have the output of the `echo $BLOCKED_IP` from your node and try to go into your browser or a registered client and try to connect - It should not resolve
</ Steps>
@@ -1,11 +1,39 @@
Run this command to define variable `BLOCKED_IP` and try to `ping` it:
import { Steps } from 'nextra/components';
import { AccordionTemplate } from 'components/accordion-template.tsx';
import ExitPolicyTestOutput from 'components/operators/snippets/wg-exit-policy-test-output.mdx';
<Steps>
###### 1. Make sure to have the latest NTM:
```sh
curl -L https://raw.githubusercontent.com/nymtech/nym/refs/heads/develop/scripts/nym-node-setup/network-tunnel-manager.sh -o network-tunnel-manager.sh && \
chmod +x network-tunnel-manager.sh && \
./network-tunnel-manager.sh --help
```
###### 2. Run tests with NTM
```sh
./network-tunnel-manager.sh exit_policy_test_connectivity
./network-tunnel-manager.sh exit_policy_tests
```
- The output should look like this:
<AccordionTemplate name="Cosole output">
<ExitPolicyTestOutput />
</ AccordionTemplate>
###### 3. Optionally you can do some manual sanity checks
- Run this command to define variable `BLOCKED_IP` and try to `ping` it:
```shell
BLOCKED_IP=$(grep "ExitPolicy reject" /etc/nym/exit-policy.txt | head -1 | sed -E 's/ExitPolicy reject ([^:]+):.*/\1/' | sed 's/\/.*$//')
ping -c 3 $BLOCKED_IP
```
You should see `100% packet loss` as an outcome.
- You should see `100% packet loss` as an outcome.
```shell
telnet $BLOCKED_IP 80
```
You should see `telnet: Unable to connect to remote host: Connection timed out`.
- You should see `telnet: Unable to connect to remote host: Connection timed out`.
</ Steps>
@@ -1 +1 @@
Thursday, November 13th 2025, 11:23:33 UTC
Thursday, November 20th 2025, 12:33:19 UTC
@@ -11,7 +11,7 @@ options:
--no_routing_history Display node stats without routing history
--no_verloc_metrics Display node stats without verloc metrics
-m, --markdown Display results in markdown format
-o, --output [OUTPUT]
-o [OUTPUT], --output [OUTPUT]
Save results to file (in current dir or supply with
path without filename)
```
@@ -13,7 +13,6 @@ import TextField from "@mui/material/TextField";
import Button from "@mui/material/Button";
const nymApiUrl = "https://validator.nymtech.net/api";
const preferredGateway = "q2A2cbooyC16YJzvdYaSMH9X3cSiieZNtfBr8cE8Fi1";
export const Traffic = () => {
const [nym, setNym] = useState<NymMixnetClient>();
@@ -32,7 +31,6 @@ export const Traffic = () => {
clientId: crypto.randomUUID(),
nymApiUrl,
forceTls: true, // force WSS
preferredGateway,
});
// check when is connected and set the self address
+1 -1
View File
@@ -1108,7 +1108,7 @@ const config = {
form-action 'self';
frame-ancestors 'none';
upgrade-insecure-requests;
connect-src 'self' wss://nym-node-cli.devrel.nymte.ch:9001 https://github.com *.vercel.app *.nymtech.net *.nymvpn.com *.nymte.ch *.nyx.network *.nym.com https://nym.com nymvpn.com https://nymvpn.com *.nymtech.cc;
connect-src 'self' wss: https://github.com *.vercel.app *.nymtech.net *.nymvpn.com *.nymte.ch *.nyx.network *.nym.com https://nym.com nymvpn.com https://nymvpn.com *.nymtech.cc;
frame-src 'self' https://vercel.live *.vercel.app *.nym.com https://nym.com;
worker-src 'self' blob: https://vercel.live *.vercel.app *.nym.com https://nym.com;
`;
+2 -2
View File
@@ -11,8 +11,8 @@
"type": "menu",
"items": {
"developers": {
"title": "Integrations",
"href": "/developers/integrations"
"title": "Developer Overview",
"href": "/developers/"
},
"rust": {
"title": "Rust SDK",
+8 -18
View File
@@ -1,28 +1,18 @@
{
"index": "Introduction",
"concepts": "Core Concepts",
"binaries": "Binaries",
"integrations": "Integration Options",
"clients": "Clients",
"tools": "Tools",
"nymvpncli": "Nym VPN CLI",
"chain": "Interacting with Nyx",
"--": {
"type": "separator",
"title": "Mixnet Integrations"
},
"integrations": "Overview - Start Here!",
"native": "Native Apps",
"browsers": "Browser Apps",
"concepts": "Nym-Specific Concepts for Integrations",
"-": {
"type": "separator",
"title": "SDKs"
"type": "separator"
},
"rust": "Rust SDK",
"typescript": "Typescript SDK",
"---": {
"type": "separator",
"title": "Misc"
},
"chain": "Interacting with Nyx Blockchain",
"tools": "Tools",
"nymvpncli": "Nym VPN CLI",
"clients": "Standlone Clients",
"----": {
"type": "separator"
},
"archive": "Archive",
@@ -1,40 +0,0 @@
import { Callout } from 'nextra/components';
# Browser-Based Apps
Browsers are a very restricted environment to work in, with limited options for external communications (websockets, Web Transport API, WebRTC), mixed content restrictions (HTTPS-only), and no access to the file system or any syscalls. These aside, the main issue when trying to capture traffic and send it via a different transport - such as the Mixnet - is the lack of access to browser TLS negotiation from JS or the CA certificate store.
This means that the functionality offered by our current browser-based solutions are quite restricted / specific. There are currently two options for interacting with the Mixnet from the browser: `mixFetch`, and the WASM SDK.
![](/images/developers/nym-browser-arch.png)
Both `mixFetch` and the WASM client are delivered to the client bundled into a web application.
## mixFetch
Drop-in replacement for browser's `fetch` API that makes HTTP(S) requests via Exit Gateways using the SOCKS Network Requester.
Uses an embedded CA certificate store to establish TLS session between `mixFetch` and the remote host, creating a client-host secure channel from the browser to the host over the Mixnet.
Internally it uses the WASM client.
- [docs](./typescript/start#mixfetch)
- [example](./typescript/playground/mixfetch)
<Callout type="warning">
### Current Limitations of `mixFetch`
It cannot currently handle concurrent requests, and comes with a pre-bundled CA store. `mixFetchv2` - which will act more like a general-purpose userspace IP stack - is currently in development.
</Callout>
## WASM Client
Makes Sphinx packets and cover traffic using WASM and sent over a Websocket to the Entry Gateway and receive responses.
This only works in messaging mode (i.e. messages sent either as text or binary data), and currently doesnt support making IP packets that are routed to the Internet by an Exit Gateway IPR, nor does it currently expose any stream-like API. If you want to send HTTP(S) requests, use `mixFetch`.
Note that the limitations of CSPs and Mixed Content restrictions (i.e HTTPS only) apply to the Websocket connection as normal in browsers or embedded WebViews.
Runs in a web worker to leave UI thread free for the user.
- [docs](./typescript/start#mixnet-client)
- [example](./typescript/playground/traffic)
@@ -1,4 +1,5 @@
{
"socks5": "SOCKS Proxy",
"websocket": "Websocket"
"socks5": "Socks5 (standalone)",
"webassembly-client": "Webassembly Client",
"websocket": "Websocket (standalone)"
}
@@ -0,0 +1,6 @@
{
"required-architecture": "Required Architecture",
"messages": "Message Based Paradigm",
"message-queue": "Message Queue",
"credentials": "Credentials"
}
@@ -1,11 +1,5 @@
import { Callout } from 'nextra/components'
# Message Queue
<Callout type="info">
Although good to understand how the Nym Client works under the hood, this information is only of practical use if you're using the `Mixnet` module of the RustSDK and interacting with the SDK Mixnet Client at a low level. This is all mostly abstracted away with the `MixSocket`, `MixStream`, and `IpMixStream` abstractions.
</Callout>
## Sphinx Packet Streams
Clients, once connected to the Mixnet, **are always sending traffic into the Mixnet**; as well as the packets that you as a developer are sending from your application logic, they send [cover traffic](../../network/concepts/cover-traffic) at a constant rate defined by a Poisson process. This is part of the network's mitigation of timing attacks.
@@ -0,0 +1,31 @@
# Message-based Paradigm
## Message Format
For the moment, Mixnet clients work assuming they will be piped atomic messages looking something like this:
```
MixnetMessage {
Message: Message_Bytes,
To: Nym_Address,
Attached_SURBS: Number_Of_Surbs
}
```
That the client will then encrypt as Sphinx packets and send through the Mixnet.
Likewise, they assume that once they have received and decrypted a Sphinx packet, they will kick back a reconstructed message to the rest of your app logic that look something like:
```
ReconstructedMessage {
Message: Message_Bytes,
From: SURB_Sender_Tag
}
```
This is obviously quite different to e.g. simply being able to read/write from a stream returned from a function call to create a TCP connection, but there are several approaches that developers can take to dealing with this right now.
## Message Abstractions
- Rust/Go (and soon C++) developers can use the `TcpProxy` [stream abstraction](../rust/tcpproxy).
- Developers who are using Typescript/Javascript can also avoid having to deal directly with messages via using [MixFetch](../typescript/examples/mix-fetch).
- As can developers who are bundling and running the standalone [socks5 client](../clients/socks5) using some form of init script.
- There is a seperate pair of binaries which other developers can use to run as a persistent secondary proxy process built using the `TcpProxy` abstraction. These simply expose a `localhost` socket port to pipe traffic to and from in the same way as you would a TCP connection and can be found [here](https://github.com/nymtech/standalone-tcp-proxies).
@@ -1,7 +1,5 @@
# Required Application Architecture
**TODO once you;ve reworked you can probably just remove this**
Due to the fact that there are a lot of components that make up the Nym network (the Mixnet, Blockchain, etc) there is often confusion / misunderstandings about what is required to run application traffic through the Mixnet and take advantage of its various privacy properties.
## What do I need?
@@ -1,2 +1,7 @@
# Introduction
Nym's developer documentation covering core concepts of integrating with the Mixnet, interacting with the Nyx blockchain, an overview of the avaliable tools, and our SDK docs.
## Where to Start?
If you are completely new to Nym, it is suggested to start with the top sections covering the core concepts, integration options, and the clients and tools available to you.
If you feel like starting with more practical examples, check out the relevent SDK docs in the sidebar to the left.
@@ -1,16 +1,40 @@
import { Callout } from 'nextra/components';
import Box from '@mui/material/Box';
import { Steps } from 'nextra/components'
import { Tabs } from 'nextra/components'
import { GitHubRepoSearch } from '../../code-snippets/mixfetchurl';
# Integrating With Nym
Any application that wants to integrate with Nym involves sending its application traffic through the Mixnet using one of the available Nym Clients. There is no single solution for this, as different environments offer different access and transport options (e.g. if operating in a web browser, you do not have access to syscalls or sockets, have to deal with content security policies, etc).
# Integration Options
Developers might want to either integrate a Mixnet client or just to interact with the blockchain. See the relevant section below.
As such, we have several solutions available for developers to choose from depending on the **environment** their application is expected to run in: native apps which are running on a desktop, or webapps running in a browser.
## Integrating Mixnet Functionality
There are several options available to developers wanting to embed a Nym client in their application code.
<Callout type="info" emoji="️">
The list of current options available to developers to do not cover all environments and setups - we are working on expanding this list and approaching more general solutions, but there is no one-size-fits-all approach when dealing with rerouting network traffic.
</Callout>
<Tabs items={['Rust/Go/C++', 'Typescript/Javascript','Other']}>
<Tabs.Tab >
<>
Integration options are then further subdivided by app **architecture**; whether the application interacts with remote hosts on the public internet running independently of the app (e.g. public blockchain RPC endpoints, third-party APIs) or whether app developers have some control over the versions of the software being run on both sides of an interaction (e.g. peer to peer apps running the same software version, or client-server architectures which are running software written by the same team).
Rust developers can rely on our Rust SDK to import Nym client functionality into their code. This can either be in the form of a standard message-based client, the `socks5` client, or the `TcpProxy` modules.
<Callout type="info" emoji="️">
This is because of the different security considerations each option offers. These are detailed in the following pages.
</Callout>
We aim to expose at least the majority of this functionality via FFI to Go and C/C++. This is detailed alongside the Rust SDK components in the [Rust SDK docs](./rust).
</>
</Tabs.Tab>
<Tabs.Tab>
<>
Typescript and Javascript developers have several options avaliable to them:
- [`mixfetch`](./typescript/examples/mix-fetch) is an almost-dropin replacement for the `fetch` library. The best way to integrate Nym's `mixFetch` into your application will be where external network calls and RPC happens, for example, something in the lines of `sendRawTransaction` if you have an ETH-compatible wallet or `JsonRpcClient` if you use CosmJS. Although you can simply search for any JS `fetch` calls in your code (using our tool below) that are easily replaceable with `mixFetch`, keep in mind that `fetch` is not the only way to make `JSONRPC` or `XHR` calls. We advise to approach the integration process in a semantic way, searching for a module that is the common denominator for external communication in the codebase. Usually these are API controllers, middlewares or repositories.
<GitHubRepoSearch />
- Otherwise, a well-modularized JS/TS codebase should permit the integration of one of our other SDK components, which will allow more flexibility and control (or if your codebase is not using something that can be covered by `fetch` for networking). Read more about our different SDK components in the [TS SDK overview page](./typescript/overview).
</ >
</Tabs.Tab>
<Tabs.Tab> If your app is not written in any of the supported languages, you might still be able to send traffic through a standalone [socks5 client](./clients/socks5) but will have to think about packaging and bundling the client binary with e.g. a `systemd` file for autostart to run the client as a daemon. If you want to discuss FFI options reach out to us via our public dev channel. </Tabs.Tab>
</Tabs>
## Interacting with Nyx
If instead of relying on the Mixnet you wish to interact with the Nyx chain, either as a payment processor or to get on-chain events, see [interacting with the chain](./chain).
> Note that depending on your setup, you might already be able to combine interacting with the chain with using the Mixnet: check the options above for more.
@@ -1,86 +0,0 @@
import { Callout } from 'nextra/components';
# Native / Desktop Apps
Developers wanting to integrate into desktop apps & CLIs can use our Rust SDK. There are two broad approaches to using the Mixnet (E2E or as a proxy), with different modules suited for each, each with their own specific usecase and limitations.
## Option 1: Mixnet End-To-End
You might want to embed Nym Clients in both sides of your app, and have them send all of your app network traffic through the Mixnet: maybe two clients in a peer to peer setup, or a client and a server where it is possible for you as a developer to release both the client and server side code, and have some ability to make sure that it is being run.
![](/images/developers/nym-arch-client-to-client.png)
There are several options available:
{ /* ### Stream Wrapper Module
Exposes `MixSocket`/`MixStream` abstractions that can be split a reader/writer halves that consumes bytes, with an interface inspired by `std::net::TcpStream`. For developers who just want to read/write bytes to/from the Mixnet working with something socket-like.
- docs TODO LINK
- example TODO LINK */ }
### Mixnet & Client Pool Modules
The Mixnet module of the SDK exposes low level connection functionality and the Mixnet Client. The Client Pool is one answer to concurrency, and allows developers to run several Nym Clients at once which can be quickly used.
{ /* This approach might be useful if you want to build custom connection logic, but **`MixSocket`/`MixStream` will probably be sufficient for the majority of usecases** where developers just want to send and receive traffic as streams. */ }
This approach might be useful if you want to build custom connection logic, but the TcpProxy Module will probably be sufficient for the majority of usecases where developers just want to send and receive traffic as streams.
- [docs](./rust/mixnet)
- [examples](./rust/mixnet/examples)
### TcpProxy Module
{ /* <Callout type="warning" emoji="⚠️">
This module has been superseded by the Stream Wrapper module, and will soon be deprecated. **New features will not be added to it.** The main drawback of this (which is fixed with `MixSocket`/`MixStream`) is that TLS is impossible, as it exposes a localhost port for the consuming process to communicate with.
</Callout> */ }
A pair of abstractions built for use in a client-server setup, which both expose a `localhost` TCP Socket which apps can read/write bytes to/from.
- [docs](./rust/tcpproxy)
- [examples](./rust/tcpproxy/examples/singleconn)
<Callout type="info" emoji="️">
There is a new abstraction coming soon mirroring the interface and use of a TCP Socket, making it easier for developers to use the Mixnet, and also perform TLS through a Mixnet connection. Stay tuned.
</Callout>
## Option 2: Mixnet-As-Proxy
For developers who are only able to control the client-side code, and/or need to communicate with a 3rd party service, such as a public blockchain RPC or a remote host they do not control.
![](/images/developers/nym-arch-ip-routing.png)
<Callout type="warning">
### Security Considerations
Since traffic is only packaged as Sphinx until it gets to the Exit Gateway, where it is unwrapped into either HTTPS packets (by a Network Requester) or IP packets (by an IP Packet Router), the last hop between the Gateway and the remote host **travels as normal internet traffic**.
As such, this option has fewer protections than the E2E option against a global passive adversary, but still grants you timing obfuscation and sender-receiver unlinkability between your client software and whatever service it is interacting with.
</Callout>
### SOCKS Client
Developers with apps that support SOCKS4,4a, or 5 can use the Socks Client exposed by the Mixnet module. This uses the Network Requester service of the chosen Exit Gateway to interact with the remote host via the chosen SOCKS proxy protocol. The Network Requester uses SURBs to anonymously reply to the original sender with whatever response it gets from the remote host.
- [docs](./rust/mixnet/examples/socks)
- [example](./rust/mixnet/examples/socks)
<Callout type="info" emoji="️">
There is a new abstraction coming soon that will allow the SDK to send IP packets, the beginning of a longer project to make a native Rust version of [`mixFetch`](./typescript/start#mixfetch). Stay tuned.
</Callout>
{ /* ### `IPMixStream`
This is a version of the `MixSocket` that consumes IP packets before wrapping them in Sphinx and forwarding through the Mixnet to the IP Packet Router of the chosen Exit Gateway, where they are unwrapped and treated as normal IP packets. The IPR uses SURBs to anonymously reply to the original sender with whatever response it gets from the remote host.
<Callout type="info" emoji="️">
Currently only consumes IP packets - those who do not want to work with IP packets directly should check `mixtcp` below for doing something with HTTP(S).
</Callout>
- docs TODO LINK
- examples TODO LINK
### `MixTCP`
A proof of concept TCP/IP crate containing a [`smoltcp`](https://docs.rs/smoltcp/latest/smoltcp/index.html) `device` that uses the Mixnet for transport. Examples of using this to make a TLS handshake and perform an HTTPS request can be found linked below.
<Callout type="info" emoji="️">
This crate is currently a proof of concept which is in active development. This crate will become the basis of a general-purpose HTTP-through-Mixnet crate in the near future.
</Callout>
- docs TODO LINK
- example TODO LINK */ }
+14 -1
View File
@@ -1,3 +1,16 @@
# Introduction
The Rust SDK allows exposes a few different modules, some more plug and play than others. Each of which handles exposes a Nym Client, which handles finding and using a route for packets through the Mixnet, encryption, and cover traffic, all under the hood.
import { Callout } from 'nextra/components';
<Callout type="warning">
There will be a breaking SDK upgrade in the coming months. This upgrade will make the SDK a lot easier to build with.
This upgrade will affect the interface of the SDK dramatically, and will be coupled with a protocol change - stay tuned for information on early access to the new protocol testnet.
It will also be coupled with the documentation of the SDK on [crates.io](https://crates.io/).
</Callout>
The Rust SDK allows developers building applications in Rust to import and interact with Nym clients as they would any other dependency, instead of running the client as a separate process on their machine.
Check the [development status](./rust/development-status) page to see the various modules that make up the SDK, and the [FFI](./rust/ffi) page for Go/C++ developers.
@@ -1,7 +1,8 @@
{
"importing": "Importing",
"tcpproxy": "TcpProxy Module",
"development-status": "Development Status",
"mixnet": "Mixnet Module",
"client-pool": "Client Pool Module",
"tcpproxy": "TcpProxy Module",
"client-pool": "Client Pool",
"ffi": "FFI"
}
@@ -2,6 +2,15 @@
import { Callout } from 'nextra/components';
<Callout type="warning">
There will be a breaking SDK upgrade in the coming months. This upgrade will make the SDK a lot easier to build with.
This upgrade will affect the interface of the SDK dramatically, and will be coupled with a protocol change - stay tuned for information on early access to the new protocol testnet.
It will also be coupled with the documentation of the SDK on [crates.io](https://crates.io/).
</Callout>
We have a configurable-size Client Pool for processes that require multiple clients in quick succession (this is used by default by the [`TcpProxyClient`](./tcpproxy) for instance)
This will be useful for developers looking to build connection logic, or just are using raw SDK clients in a sitatuation where there are multiple connections with a lot of churn.
@@ -2,6 +2,17 @@
# FFI Bindings
import { Callout } from 'nextra/components';
<Callout type="warning">
There will be a breaking SDK upgrade in the coming months. This upgrade will make the SDK a lot easier to build with.
This upgrade will affect the interface of the SDK dramatically, and will be coupled with a protocol change - stay tuned for information on early access to the new protocol testnet.
It will also be coupled with the documentation of the SDK on [crates.io](https://crates.io/).
</Callout>
<Callout type="info" emoji="️">
We are working on the intitial versions of the FFI code to allow developers to experiment and get feedback. Please get in touch if you think the FFI bindings are lacking certain functionality.
</Callout>
We currently have FFI bindings for Go and C/C++. See the table below to check the coverage of functionality we expect devs would like to see.
The [`nym/sdk/ffi`](https://github.com/nymtech/nym/tree/master/sdk/ffi) directory has the following structure:
@@ -39,7 +50,7 @@ At the time of writing the following functionality is not exposed to the shared
- `Socks5::new()`: creation and use of the [socks5/4a/4 proxy client](./mixnet/examples/socks).
## TcpProxy Module
A connection abstraction which exposes a local TCP socket which developers are able to interact with basically as expected, being able to read/write to/from a bytestream, without really having to take into account the workings of the Mixnet/Sphinx/the message-based format of the underlying client.
A connection abstraction which exposes a local TCP socket which developers are able to interact with basically as expected, being able to read/write to/from a bytestream, without really having to take into account the workings of the Mixnet/Sphinx/the [message-based](../concepts/messages) format of the underlying client.
<Callout type="info" emoji="️">
At the time of writing this functionality is **only** exposed to Go. C/C++ bindings will follow in the future in a larger update to the C FFI.
@@ -1,6 +1,14 @@
# Installation
import { Callout } from 'nextra/components';
<Callout type="warning">
There will be a breaking SDK upgrade in the coming months. This upgrade will make the SDK a lot easier to build with.
This upgrade will affect the interface of the SDK dramatically, and will be coupled with a protocol change - stay tuned for information on early access to the new protocol testnet.
It will also be coupled with the documentation of the SDK on [crates.io](https://crates.io/).
</Callout>
The `nym-sdk` crate is **not yet available via [crates.io](https://crates.io)**. As such, in order to import the crate you must specify the Nym monorepo in your `Cargo.toml` file. Since the `HEAD` of `master` is always the most recent release, we recommend developers use that for their imports, unless they have a reason to pull in a specific historic version of the code.
```toml
@@ -1,6 +1,14 @@
# Mixnet Module
import { Callout } from 'nextra/components';
<Callout type="warning">
There will be a breaking SDK upgrade in the coming months. This upgrade will make the SDK a lot easier to build with.
This upgrade will affect the interface of the SDK dramatically, and will be coupled with a protocol change - stay tuned for information on early access to the new protocol testnet.
It will also be coupled with the documentation of the SDK on [crates.io](https://crates.io/).
</Callout>
This module exposes the logic of creating and interacting with clients and Mixnet messages. This is recommended for those wanting to either start playing around with the Mixnet and how it works, or build connection logic.
> For developers wanting something more 'plug and play' we recommend the [`TcpProxy` module](./tcpproxy).
@@ -1,4 +1,11 @@
# Builder Patterns
import { Callout } from 'nextra/components';
<Callout type="warning">
There will be a breaking SDK upgrade in the coming months. This upgrade will make the SDK a lot easier to build with.
This upgrade will affect the interface of the SDK dramatically, and will be coupled with a protocol change - stay tuned for information on early access to the new protocol testnet.
It will also be coupled with the documentation of the SDK on [crates.io](https://crates.io/).
</Callout>
Since there are two ways of creating an SDK client - ephemeral and with-storage - then there are two ways of applying the Builder Pattern to client creation.
@@ -1,6 +1,13 @@
# Mixnet Client Builder with Storage
import { Callout } from 'nextra/components';
<Callout type="warning">
There will be a breaking SDK upgrade in the coming months. This upgrade will make the SDK a lot easier to build with.
This upgrade will affect the interface of the SDK dramatically, and will be coupled with a protocol change - stay tuned for information on early access to the new protocol testnet.
It will also be coupled with the documentation of the SDK on [crates.io](https://crates.io/).
</Callout>
The previous example involves ephemeral keys - if we want to create and then maintain a client identity over time, our code becomes a little more complex as we need to create, store, and conditionally load these keys.
> You can find this code [here](https://github.com/nymtech/nym/blob/master/sdk/rust/nym-sdk/examples/builder_with_storage.rs).
@@ -1,6 +1,13 @@
# Mixnet Client Builder
import { Callout } from 'nextra/components';
<Callout type="warning">
There will be a breaking SDK upgrade in the coming months. This upgrade will make the SDK a lot easier to build with.
This upgrade will affect the interface of the SDK dramatically, and will be coupled with a protocol change - stay tuned for information on early access to the new protocol testnet.
It will also be coupled with the documentation of the SDK on [crates.io](https://crates.io/).
</Callout>
You can spin up an ephemeral client like so. This client will not have a persistent identity and its keys will be dropped on restart. Since there is currently no way of reconnecting a client that has been disconnected after use, then treat disconnecting a client the same as dropping its keys entirely.
> You can find this code [here](https://github.com/nymtech/nym/blob/master/sdk/rust/nym-sdk/examples/builder.rs).
@@ -2,6 +2,14 @@
import { Callout } from 'nextra/components'
<Callout type="warning">
There will be a breaking SDK upgrade in the coming months. This upgrade will make the SDK a lot easier to build with.
This upgrade will affect the interface of the SDK dramatically, and will be coupled with a protocol change - stay tuned for information on early access to the new protocol testnet.
It will also be coupled with the documentation of the SDK on [crates.io](https://crates.io/).
</Callout>
<Callout type="warning" emoji="⚠️">
These examples are **not** the same as using a configurable network: these functions define a subset of nodes to use on a given network, whereas the [testnet](./testnet) example is an example of switching to use a different network entirely. The two can be combined, but if you are looking for how to connect your client to a testnet, see the `testnet` file.
</Callout>
@@ -1,6 +1,13 @@
# Custom Topology Provider
import { Callout } from 'nextra/components';
<Callout type="warning">
There will be a breaking SDK upgrade in the coming months. This upgrade will make the SDK a lot easier to build with.
This upgrade will affect the interface of the SDK dramatically, and will be coupled with a protocol change - stay tuned for information on early access to the new protocol testnet.
It will also be coupled with the documentation of the SDK on [crates.io](https://crates.io/).
</Callout>
If you are also running a Validator and Nym API for your network, you can specify that endpoint as such and interact with it as clients usually do (under the hood).
> You can find this code [here](https://github.com/nymtech/nym/blob/master/sdk/rust/nym-sdk/examples/custom_topology_provider.rs)
@@ -26,7 +33,7 @@ impl MyTopologyProvider {
.expect("Failed to create API client builder")
.build::<nym_validator_client::models::RequestError>()
.expect("Failed to build API client");
MyTopologyProvider {
validator_client,
}
@@ -1,6 +1,13 @@
# Manually Overwrite Topology
import { Callout } from 'nextra/components';
<Callout type="warning">
There will be a breaking SDK upgrade in the coming months. This upgrade will make the SDK a lot easier to build with.
This upgrade will affect the interface of the SDK dramatically, and will be coupled with a protocol change - stay tuned for information on early access to the new protocol testnet.
It will also be coupled with the documentation of the SDK on [crates.io](https://crates.io/).
</Callout>
If you aren't running a Validator and Nym API, and just want to import a specific sub-set of mix nodes, you can simply overwrite the grabbed topology manually.
> You can find this code [here](https://github.com/nymtech/nym/blob/master/sdk/rust/nym-sdk/examples/manually_overwrite_topology.rs)
@@ -2,6 +2,13 @@
import { Callout } from 'nextra/components'
<Callout type="warning">
There will be a breaking SDK upgrade in the coming months. This upgrade will make the SDK a lot easier to build with.
This upgrade will affect the interface of the SDK dramatically, and will be coupled with a protocol change - stay tuned for information on early access to the new protocol testnet.
It will also be coupled with the documentation of the SDK on [crates.io](https://crates.io/).
</Callout>
Lets look at a very simple example of how you can import and use the websocket client in a piece of Rust code.
Simply importing the `nym_sdk` crate into your project allows you to create a client and send traffic through the mixnet.
@@ -2,6 +2,13 @@
import { Callout } from 'nextra/components'
<Callout type="warning">
There will be a breaking SDK upgrade in the coming months. This upgrade will make the SDK a lot easier to build with.
This upgrade will affect the interface of the SDK dramatically, and will be coupled with a protocol change - stay tuned for information on early access to the new protocol testnet.
It will also be coupled with the documentation of the SDK on [crates.io](https://crates.io/).
</Callout>
If you are looking at implementing Nym as a transport layer for a crypto wallet or desktop app, this is probably the best place to start if they can speak SOCKS5, 4a, or 4.
> You can find this code [here](https://github.com/nymtech/nym/blob/master/sdk/rust/nym-sdk/examples/socks5.rs)
@@ -2,6 +2,13 @@
import { Callout } from 'nextra/components'
<Callout type="warning">
There will be a breaking SDK upgrade in the coming months. This upgrade will make the SDK a lot easier to build with.
This upgrade will affect the interface of the SDK dramatically, and will be coupled with a protocol change - stay tuned for information on early access to the new protocol testnet.
It will also be coupled with the documentation of the SDK on [crates.io](https://crates.io/).
</Callout>
If you need to split the different actions of your client across different tasks, you can do so like this. You can think of this analogously to spliting a Tcp Stream into read/write. This functionality is also useful for embedding a sending and receiving client into different tasks.
> You can find this code [here](https://github.com/nymtech/nym/blob/master/sdk/rust/nym-sdk/examples/parallel_sending_and_receiving.rs)
@@ -2,6 +2,13 @@
import { Callout } from 'nextra/components'
<Callout type="warning">
There will be a breaking SDK upgrade in the coming months. This upgrade will make the SDK a lot easier to build with.
This upgrade will affect the interface of the SDK dramatically, and will be coupled with a protocol change - stay tuned for information on early access to the new protocol testnet.
It will also be coupled with the documentation of the SDK on [crates.io](https://crates.io/).
</Callout>
If you're integrating mixnet functionality into an existing app and want to integrate saving client configs and keys into your existing storage logic, you can manually perform these actions.
> You can find this code [here](https://github.com/nymtech/nym/blob/master/sdk/rust/nym-sdk/examples/manually_handle_storage.rs)
@@ -2,6 +2,13 @@
import { Callout } from 'nextra/components'
<Callout type="warning">
There will be a breaking SDK upgrade in the coming months. This upgrade will make the SDK a lot easier to build with.
This upgrade will affect the interface of the SDK dramatically, and will be coupled with a protocol change - stay tuned for information on early access to the new protocol testnet.
It will also be coupled with the documentation of the SDK on [crates.io](https://crates.io/).
</Callout>
Both functions used to send messages through the mixnet (`send_message` and `send_plain_message`) send a pre-determined number of SURBs along with their messages by default.
You can read more about how SURBs function under the hood [here](../../../../network/traffic/anonymous-replies).
@@ -1,7 +1,13 @@
# Configurable Network
import { Callout } from 'nextra/components'
<Callout type="warning">
There will be a breaking SDK upgrade in the coming months. This upgrade will make the SDK a lot easier to build with.
This upgrade will affect the interface of the SDK dramatically, and will be coupled with a protocol change - stay tuned for information on early access to the new protocol testnet.
It will also be coupled with the documentation of the SDK on [crates.io](https://crates.io/).
</Callout>
If you want to connect your Mixnet client to a different network than Mainnet, simply pull in a file from [`nym/envs`](https://github.com/nymtech/nym/tree/master/envs) as such:
```rust
@@ -1,8 +1,15 @@
# TcpProxy Module
import { Callout } from 'nextra/components';
<Callout type="warning">
There will be a breaking SDK upgrade in the coming months. This upgrade will make the SDK a lot easier to build with.
This upgrade will affect the interface of the SDK dramatically, and will be coupled with a protocol change - stay tuned for information on early access to the new protocol testnet.
It will also be coupled with the documentation of the SDK on [crates.io](https://crates.io/).
</Callout>
This module exposes the `TcpProxyClient` and the `TcpProxyServer` which can be used to proxy traffic through the Mixnet in a way that is more familiar to developers than the methods exposed by the [`Mixnet` module](./mixnet).
Both `Client` and `Server` are intended to be initialised and then run in a background thread, exposing a configurable `localhost` socket which developers can read/write/stream to without having to worry about the message-based nature of sending and receiving traffic to/from the Mixnet.
Both `Client` and `Server` are intended to be initialised and then run in a background thread, exposing a configurable `localhost` socket which developers can read/write/stream to without having to worry about the [message-based](../concepts/messages) nature of sending and receiving traffic to/from the Mixnet.
> Non-Rust/Go developers who want to experiment with this module can start with the [standalone binaries](../tools/standalone-tcpproxy).
@@ -3,6 +3,14 @@
import { Callout } from 'nextra/components'
<Callout type="warning">
There will be a breaking SDK upgrade in the coming months. This upgrade will make the SDK a lot easier to build with.
This upgrade will affect the interface of the SDK dramatically, and will be coupled with a protocol change - stay tuned for information on early access to the new protocol testnet.
It will also be coupled with the documentation of the SDK on [crates.io](https://crates.io/).
</Callout>
## Motivations
The motivation behind the creation of the `TcpProxy` module is to allow developers to interact with the Mixnet in a way that is far more familiar to them: simply setting up a connection with a transport, being returned a socket, and then being able to stream data to/from it, similar to something like the Tor [`arti`](https://gitlab.torproject.org/tpo/core/arti/-/tree/main/crates/arti-client) client.
@@ -1,7 +1,13 @@
# Multi Connection Example
import { Callout } from 'nextra/components'
<Callout type="warning">
There will be a breaking SDK upgrade in the coming months. This upgrade will make the SDK a lot easier to build with.
This upgrade will affect the interface of the SDK dramatically, and will be coupled with a protocol change - stay tuned for information on early access to the new protocol testnet.
It will also be coupled with the documentation of the SDK on [crates.io](https://crates.io/).
</Callout>
This example starts off several Tcp connections on a loop to a remote endpoint: in this case the `TcpListener` behind the `NymProxyServer` instance on the echo server found in
[`nym/tools/echo-server/`](https://github.com/nymtech/nym/tree/develop/tools/echo-server). It pipes a few messages to it, logs the replies, and keeps track of the number of replies received per connection.
@@ -1,7 +1,13 @@
# Single Connection Example
import { Callout } from 'nextra/components'
<Callout type="warning">
There will be a breaking SDK upgrade in the coming months. This upgrade will make the SDK a lot easier to build with.
This upgrade will affect the interface of the SDK dramatically, and will be coupled with a protocol change - stay tuned for information on early access to the new protocol testnet.
It will also be coupled with the documentation of the SDK on [crates.io](https://crates.io/).
</Callout>
This is a basic example which opens a single TCP connection and writes a bunch of messages between a client and some 'echo server' logic, so only uses a single session under the hood and doesn't really show off the message ordering capabilities; this is mainly just a quick introductory illustration on how:
- the mixnet does message ordering
- the NymProxyClient and NymProxyServer can be hooked into and used to communicate between two otherwise pretty vanilla TcpStreams
@@ -1,5 +1,12 @@
# Troubleshooting
import { Callout } from 'nextra/components'
<Callout type="warning">
There will be a breaking SDK upgrade in the coming months. This upgrade will make the SDK a lot easier to build with.
This upgrade will affect the interface of the SDK dramatically, and will be coupled with a protocol change - stay tuned for information on early access to the new protocol testnet.
It will also be coupled with the documentation of the SDK on [crates.io](https://crates.io/).
</Callout>
## Lots of `duplicate fragment received` messages
You might see a lot of `WARN` level logs about duplicate fragments in your logs, depending on the log level you're using. This occurs when a packet is retransmitted somewhere in the Mixnet, but then the original makes it to the destination client as well. This is not something to do with your client logic, but instead the state of the Mixnet.
@@ -1,7 +1,7 @@
# Tools
There are a few tools available to developers for chain interaction: the `nym-cli` tool, which operates as an easier-to-use wrapper around `nyxd`, to allow operators to script interactions with their infrastructure (and those who prefer CLI tools).
There are a few tools available to developers for chain interaction: the `nym-cli` tool, which operates as an easier-to-use wrapper around `nyxd`, to allow operators to script interactions with their infrastructure (and those who prefer CLI tools ;) ).
There is also a basic echo server tool which app developers can use as a quick endpoint for traffic testing. This will be deployed onto a persistent public server in the future so devs dont have to run it themselves.
Finally, there are also a pair of standalone versions of the TcpProxy Rust SDK module for developers to begin experimenting with sending app traffic through them mixnet (**this module will soon be deprecated in place of the `MixSocket`/`MixStream` abstractions**).
Finally, there are a pair of standalone versions of the TcpProxy Rust SDK module for developers to begin experimenting with sending app traffic through them mixnet.
@@ -18,7 +18,7 @@ Sounds great, are there any catches? Well, there are a few (for now):
<Callout type="info" emoji="️">
Right now Gateways are not required to run a Secure Websocket (WSS) listener, so only a subset of nodes running in Gateway mode have configured their nodes to do so.
For the moment you have to select a Gateway that has WSS from [Harbourmaster Gateways for mixFetch list](https://harbourmaster.nymtech.net/).
For the moment you have to select a Gateway that has WSS enabled and Network Requester from [Harbourmaster Gateways for mixFetch list](https://harbourmaster.nymtech.net/).
```
curl -X 'GET' \
@@ -33,7 +33,9 @@ curl -X 'GET' \
import type { SetupMixFetchOps } from '@nymproject/mix-fetch';
const mixFetchOptions: SetupMixFetchOps = {
preferredGateway: "q2A2cbooyC16YJzvdYaSMH9X3cSiieZNtfBr8cE8Fi1", // with WSS
preferredGateway: '23A7CSaBSA2L67PWuFTPXUnYrCdyVcB7ATYsjUsfdftb', // with WSS
preferredNetworkRequester:
'HuNL1pFprNSKW6jdqppibXP5KNKCNJxDh7ivpYcoULN9.C62NahRTUf6kqpNtDVHXoVriQr6yyaU5LtxdgpbsGrtA@23A7CSaBSA2L67PWuFTPXUnYrCdyVcB7ATYsjUsfdftb',
mixFetchOverride: {
requestTimeoutMs: 60_000,
},
@@ -10,9 +10,4 @@ import { Callout } from 'nextra/components'
<MixFetch />
<Callout type="info">
Open your browser's console to see the connection and send/receive logging for this example.
</Callout>
<FormattedMixFetchExampleCode />
@@ -7,9 +7,5 @@ import FormattedTrafficExampleCode from '../../../../code-examples/sdk/typescrip
Use this tool to experiment with the mixnet: send and receive messages!
<Callout type="info">
Open your browser's console to see the connection and send/receive logging for this example.
</Callout>
<Traffic />
<FormattedTrafficExampleCode />
@@ -32,7 +32,7 @@ Upcoming:
## Nym Clients
<Callout type="info" emoji="️">
You can read about setting up and using various clients in the [Developer Docs](../../developers/clients/socks5).
You can read about setting up and using various clients in the [Developer Docs](../../developers/clients).
</Callout>
A large proportion of the Nym Mixnet's functionality is implemented client-side.
@@ -48,4 +48,4 @@ Clients perform the following actions on behalf of users:
* Send Sphinx packet [cover traffic](../concepts/cover-traffic) when no real messages are being sent
* Retransmit [un-acknowledged packet sends](../traffic/acks)
> At the moment due to the fact that Nym clients are message-based, using the Mixnet requires another client on the 'other side' of the mixet to send packets to, unless you're using the `nymvpn` client (part of the NymVPN app) or the `socks5` client, which operates as a SOCKS4,4a, or 5 proxy and is able to utilise the client embedded within the `nym-node`'s Exit Gateway functionality (prev. this functionality was a standalone service, the Network Requester). In the future we wish to remove this point of friction and have all Nym clients construct IP packets instead, easing the integration burden and abstracting away the message-based nature of client communication.
> At the moment due to the fact that Nym clients are [message-based](../../developers/concepts/messages), using the Mixnet requires another client on the 'other side' of the mixet to send packets to, unless you're using the `nymvpn` client (part of the NymVPN app) or the `socks5` client, which operates as a SOCKS4,4a, or 5 proxy and is able to utilise the client embedded within the `nym-node`'s Exit Gateway functionality (prev. this functionality was a standalone service, the Network Requester). In the future we wish to remove this point of friction and have all Nym clients construct IP packets instead, easing the integration burden and abstracting away the message-based nature of client communication.
@@ -49,76 +49,6 @@ This page displays a full list of all the changes during our release cycle from
<VarInfo />
## `v2025.20-leerdammer`
- [Release Binaries](https://github.com/nymtech/nym/releases/tag/nym-binaries-v2025.20-leerdammer)
- [`nym-node`](nodes/nym-node.mdx) version `1.21.0`
```sh
nym-node
Binary Name: nym-node
Build Timestamp: 2025-11-12T08:19:33.288341371Z
Build Version: 1.21.0
Commit SHA: babf113fe5d396fa8a84fa939ad4b1b5b4d38b83
Commit Date: 2025-11-12T08:39:48.000000000+01:00
Commit Branch: HEAD
rustc Version: 1.88.0
rustc Channel: stable
cargo Profile: release
```
### Operators Updates & Tools
- [New **Performance Measurement** page](/operators/performance-and-testing) explaining the logic behind node selection for NymVPN application
- [New **Gateway Probe Details** page](/operators/performance-and-testing/gateway-probe-details) explaining complexity and contradictions when measuring network performance
### Developer Tools
- [Typescript SDK 1.4.1](https://github.com/nymtech/nym/pull/6146): This PR is a new release of the Typescript SDK, `mixFetch` and `WASM` client. It also removes the Harbour Master client from `mixFetch`, replacing it with the Nym API's described endpoint for nym-nodes
- [Overhauled **developer integrations** pages](/developers/integrations) explaining the different restrictions for the different SDK options on offer
- [Fixed `mixFetch` and `WASM Client` playground + examples](/developers/typescript/start): new versions of the Typescript SDK and `mixFetch` have been published, examples and live playground have been updated accordingly
### Features
- [Tweak ts sdk actions](https://github.com/nymtech/nym/pull/6185): Using `taskset` to limit the number of of CPUs used by `wasm-pack` and `wasm-opt` commands used by ts linting CI
- [Configurable mixnet client startup timeout](https://github.com/nymtech/nym/pull/6148)
- [QUIC bridge deployment script v2](https://github.com/nymtech/nym/pull/6145): Script helping operators to install, configure and deploy QUIC bridge as systemd service
- [Expose more explicit `new_with_fronted_urls` builder for http API client](https://github.com/nymtech/nym/pull/6136)
- [Domain fronting](https://github.com/nymtech/nym/pull/6134): Enable URL rotation and retries for mixnet gateway [`init`](https://github.com/nymtech/nym/pull/6126)
### Bugfix
- [Add circuit breaker](https://github.com/nymtech/nym/pull/6143): When the mixnet client's `mix_tx` channel closes during network drops, `OutQueueControl` would retry sending packets through the closed channel, flooding logs and hanging the daemon. This affects all clients (VPN, SOCKS5, native clients), not just VPN .. (Read more in the [PR description](https://github.com/nymtech/nym/pull/6143))
- [Update internal owner address in transferred share](https://github.com/nymtech/nym/pull/6139)
- [Update quic_bridge_deployment.sh for IPv4 and .deb package](https://github.com/nymtech/nym/pull/6138): Updated ping commands to explicitly use IPv4 and adjusted file permission checks with sudo. Changed the forward address prompt to specify IPv4 and modified the binary download process to fetch and install the latest `.deb` release URL automatically
- [Update stored epoch share when changing ownership](https://github.com/nymtech/nym/pull/6135)
- [Update stored epoch share when changing announce address](https://github.com/nymtech/nym/pull/6131)
### Refactors & Maintenance
- [Re-merge: disconnect mixnet client if registration fails](https://github.com/nymtech/nym/pull/6169) ([\#6158](https://github.com/nymtech/nym/pull/6158))
- [Resolve `clippy 1.91` warnings](https://github.com/nymtech/nym/pull/6168)
- [Remove unused dependencies](https://github.com/nymtech/nym/pull/6151): Removing the crates that only shows up on the workspace `Cargo.toml`
- [Use typed-builder for registration client builder config](https://github.com/nymtech/nym/pull/6150)
- [tommy is too quick](https://github.com/nymtech/nym/pull/6149)
## `v2025.19-kase`
- [Release Binaries](https://github.com/nymtech/nym/releases/tag/nym-binaries-v2025.19-kase)
@@ -3,34 +3,11 @@ import { Tabs } from 'nextra/components';
import { VarInfo } from 'components/variable-info.tsx';
import { Steps } from 'nextra/components';
import { AccordionTemplate } from 'components/accordion-template.tsx';
import ExitPolicyInstallOutput from 'components/operators/snippets/wg-exit-policy-install-output.mdx';
import ExitPolicyStatusOutput from 'components/operators/snippets/wg-exit-policy-status-output.mdx';
import ExitPolicyTestOutput from 'components/operators/snippets/wg-exit-policy-test-output.mdx';
import ExitPolicyTestServer from 'components/operators/snippets/wg-exit-policy-testing-from-server.mdx';
import ExitPolicyTestOutside from 'components/operators/snippets/wg-exit-policy-testing-from-outside.mdx';
import WGExitPolicyConf from 'components/operators/snippets/wg-exit-policy-conf.mdx';
import WGExitPolicyTest from 'components/operators/snippets/wg-exit-policy-test.mdx';
import RoutingConf from 'components/operators/snippets/routing-conf.mdx';
import QuicDeploymentSteps from 'components/operators/snippets/quic-bridge-deployment-script-setup.mdx';
export const ManagerIPOutput = () => (
<div>
Correct <code>./network_tunnel_manager.sh fetch_and_display_ipv6</code> output
</div>
);
export const ManagerTablesOutput = () => (
<div>
Correct <code>./network_tunnel_manager.sh check_nymtun_iptables</code> output
</div>
);
export const ShowTun = () => (
<div>
Correct <code>ip addr show nymtun0</code> output
</div>
);
# Nym Node Configuration
<VarInfo />
@@ -222,9 +199,11 @@ This lets your operating system know it's ok to reload the service configuration
</Steps>
## Connectivity Test and Configuration
## Routing Configuration
During our ongoing testing events we found out, that after introducing IP Packet Router (IPR) and [Nym exit policy](https://nymtech.net/.wellknown/network-requester/exit-policy.txt) on embedded Network Requester (NR) by default, only a fragment of Gateways routes correctly through IPv4 and IPv6. We built a useful monitor to check out your Gateway (`nym-node --mode exit-gateway`) at [harbourmaster.nymtech.net](https://harbourmaster.nymtech.net/).
<RoutingConf />
### Quick IPv6 Check
IPv6 routing is not only a case for gateways. Imagine a rare occasion when you run a `mixnode` without IPv6 enabled and a client will sent IPv6 packets through the Mixnet through such route:
```ascii
@@ -232,19 +211,6 @@ IPv6 routing is not only a case for gateways. Imagine a rare occasion when you r
```
In this (unusual) case your `mixnode` will not be able to route the packets. The node will drop the packets and its performance would go down. For that reason it's beneficial to have IPv6 enabled when running a `mixnode` functionality.
<Callout>
We recommend operators to configure their `nym-node` with the full routing configuration.
However, most of the time the packets sent through the Mixnet are IPv4 based. The IPv6 packets are still pretty rare and therefore it's not mandatory from operational point of view to have this configuration implemented if you running only `mixnode` mode.
If you preparing to run a `nym-node` with all modes enabled in the future, this setup is required.
</Callout>
<Callout type="info" emoji="️">
For everyone participating in Delegation Program or Service Grant program, this setup is a requirement!
</Callout>
### Quick IPv6 Check
You can always check IPv6 address and connectivity by using some of these methods:
<br />
@@ -273,267 +239,13 @@ telnet -6 ipv6.telnetmyip.com
Make sure to keep your IPv4 address enabled while setting up IPv6, as the majority of routing goes through that one!
</Callout>
### Routing Configuration
While we're working on Rust implementation to have these settings as a part of the binary build, to solve these connectivity requirements in the meantime we wrote a script [`network_tunnel_manager.sh`](https://github.com/nymtech/nym/blob/develop/scripts/network_tunnel_manager.sh) to support operators to configure their servers and address all the connectivity requirements.
Networking configuration across different ISPs and various operation systems does not have a generic solution. If the provided configuration setup doesn't solve your problem check out [IPv6 troubleshooting](../../troubleshooting/vps-isp.mdx#ipv6-troubleshooting) page. Be aware that you may have to do more research, customised adjustments or contact your ISP to change settings for your VPS.
The `nymtun0` interface is dynamically managed by the `exit-gateway` service. When the service is stopped, `nymtun0` disappears, and when started, `nymtun0` is recreated.
The `nymwg` interface is used for creating a secure wireguard tunnel as part of the Nym Network configuration. Similar to `nymtun0`, the script manages iptables rules specific to `nymwg` to ensure proper routing and forwarding through the wireguard tunnel. The `nymwg` interface needs to be correctly configured and active for the related commands to function properly. This includes applying or removing iptables rules and running connectivity tests through the `nymwg` tunnel.
The script should be used in a context where `nym-node` is running to fully utilise its capabilities, particularly for fetching IPv6 addresses or applying network rules that depend on the `nymtun0` and `nymwg` interfaces and to establish a WireGuard tunnel.
**Before starting with the following configuration, make sure you have the [latest `nym-node` binary](https://github.com/nymtech/nym/releases) installed and your [VPS setup](../preliminary-steps/vps-setup.mdx) finished properly!**
<Steps>
###### 1. Download `network_tunnel_manager.sh`, make executable and run:
```sh
curl -L https://raw.githubusercontent.com/nymtech/nym/refs/heads/develop/scripts/network_tunnel_manager.sh -o network_tunnel_manager.sh && \
chmod +x network_tunnel_manager.sh && \
./network_tunnel_manager.sh
```
###### 2. Make sure your `nym-node` service is up and running and bond
- **If you setting up a new node and not upgrading an existing one, keep it running and [bond](bonding.mdx) your node now**. Then come back here and follow the rest of the configuration.
<Callout type="warning" emoji="⚠️">
**Run the following steps as root or with `sudo` prefix!**
</Callout>
###### 3. Setup IP tables rules
- Delete IP tables rules for IPv4 and IPv6 and apply new ones:
```sh
./network_tunnel_manager.sh remove_duplicate_rules nymtun0
./network_tunnel_manager.sh apply_iptables_rules
```
- The process may prompt you if you want to save current IPv4 and IPv6 rules, choose yes.
![](/images/operators/ip_table_prompt.png)
- At this point you should see a `global ipv6` address.
```sh
./network_tunnel_manager.sh fetch_and_display_ipv6
```
<br />
<AccordionTemplate name={<ManagerTablesOutput/>}>
```sh
iptables-persistent is already installed.
Using IPv6 address: 2001:db8:a160::1/112 #the address will be different for you
operation fetch_ipv6_address_nym_tun completed successfully.
```
</AccordionTemplate>
###### 4. Check Nymtun IP tables:
```sh
./network_tunnel_manager.sh check_nymtun_iptables
```
- If there's no process running it wouldn't return anything.
- In case you see `nymtun0` but not active, this is probably because you are setting up a new (never bonded) node and not upgrading an existing one.
<br />
<AccordionTemplate name={<ManagerIPOutput/>}>
```sh
iptables-persistent is already installed.
network Device: eth0
---------------------------------------
inspecting IPv4 firewall rules...
Chain FORWARD (policy DROP 0 packets, 0 bytes)
0 0 ufw-reject-forward all -- * * 0.0.0.0/0 0.0.0.0/0
0 0 ACCEPT all -- nymtun0 eth0 0.0.0.0/0 0.0.0.0/0
0 0 ACCEPT all -- eth0 nymtun0 0.0.0.0/0 0.0.0.0/0 state RELATED,ESTABLISHED
0 0 ACCEPT all -- nymtun0 eth0 0.0.0.0/0 0.0.0.0/0
0 0 ACCEPT all -- eth0 nymtun0 0.0.0.0/0 0.0.0.0/0 state RELATED,ESTABLISHED
0 0 ACCEPT all -- nymtun0 eth0 0.0.0.0/0 0.0.0.0/0
0 0 ACCEPT all -- eth0 nymtun0 0.0.0.0/0 0.0.0.0/0 state RELATED,ESTABLISHED
---------------------------------------
inspecting IPv6 firewall rules...
Chain FORWARD (policy DROP 0 packets, 0 bytes)
0 0 ufw6-reject-forward all * * ::/0 ::/0
0 0 ACCEPT all eth0 nymtun0 ::/0 ::/0 state RELATED,ESTABLISHED
0 0 ACCEPT all nymtun0 eth0 ::/0 ::/0
0 0 ACCEPT all eth0 nymtun0 ::/0 ::/0 state RELATED,ESTABLISHED
0 0 ACCEPT all nymtun0 eth0 ::/0 ::/0
0 0 ACCEPT all eth0 nymtun0 ::/0 ::/0 state RELATED,ESTABLISHED
0 0 ACCEPT all nymtun0 eth0 ::/0 ::/0
operation check_nymtun_iptables completed successfully.
```
</AccordionTemplate>
###### 5. Remove old and apply new rules for wireguad routing
```sh
/network_tunnel_manager.sh remove_duplicate_rules nymwg
./network_tunnel_manager.sh apply_iptables_rules_wg
```
###### 6. Apply rules to configure DNS routing and allow ICMP piung test for node probing (network testing)
```sh
./network_tunnel_manager.sh configure_dns_and_icmp_wg
```
###### 7. Adjust and validate IP forwarding
```sh
./network_tunnel_manager.sh adjust_ip_forwarding
./network_tunnel_manager.sh check_ipv6_ipv4_forwarding
```
###### 8. Check `nymtun0` interface and test routing configuration
```sh
ip addr show nymtun0
```
<br />
<AccordionTemplate name={<ShowTun/>}>
```sh
# your addresses will be different
8: nymtun0: <POINTOPOINT,MULTICAST,NOARP,UP,LOWER_UP> mtu 1420 qdisc fq_codel state UNKNOWN group default qlen 500
link/none
inet 10.0.0.1/16 scope global nymtun0
valid_lft forever preferred_lft forever
inet6 fc00::1/112 scope global
valid_lft forever preferred_lft forever
inet6 fe80::ad08:d167:5700:8c7c/64 scope link stable-privacy
valid_lft forever preferred_lft forever`
```
</AccordionTemplate>
- Validate your IPv6 and IPv4 networking by running a joke test via Mixnet:
```sh
./network_tunnel_manager.sh joke_through_the_mixnet
```
- Validate your tunneling by running a joke test via WG:
```sh
./network_tunnel_manager.sh joke_through_wg_tunnel
```
- **Note:** WireGuard will return only IPv4 joke, not IPv6. WG IPv6 is under development. Running IPR joke through the mixnet with `./network_tunnel_manager.sh joke_through_the_mixnet` should work with both IPv4 and IPv6!
###### 9. Enable wireguard
Now you can run your node with the `--wireguard-enabled true` flag or add it to your [systemd service config](#systemd). Restart your `nym-node` or [systemd](#2-following-steps-for-nym-nodes-running-as-systemd-service) service (recommended):
```sh
systemctl daemon-reload && service nym-node restart
```
- Optionally, you can check if the node is running correctly by monitoring the service logs:
```sh
journalctl -u nym-node.service -f -n 100
```
</Steps>
Make sure that you get the validation of all connectivity. If there are still any problems, please refer to [troubleshooting section](../../troubleshooting/vps-isp.mdx#incorrect-gateway-network-check).
## Wireguard Exit Policy Configuration
Nym Node running as Exit Gateway has contains multiple modules, one of them is Nym Network Requester(NR), routing TCP traffic to the internet. To make sure that the node is not just an open proxy, NR checks agains [Nym exit policy](https://nymtech.net/.wellknown/network-requester/exit-policy.txt) following these conditions (in this exact order):
1. Do we explicitly block those IP addresses regardless of ports?
2. Do we allow those specific ports regardless of IPs?
3. Do block EVERYTHING else!
The exit policy is same for all NRs, the content is shaped by an offchain governance of Nym Node operators on our [forum](https://forum.nym.com/t/poll-a-new-nym-exit-policy-for-exit-gateways-and-the-nym-mixnet-is-inbound/464).
There is a caveat though. NR is only routing TCP streams and therefore any other type of routing is *not* filtered thorugh the exit policy. To ensure that Nym Nodes follow the same exit policy when routing IP packets through wireguard and don't act as open proxies, the operators have to set up these rules via IP tables rules.
**Follow these steps, using a [setup script](https://raw.githubusercontent.com/nymtech/nym/refs/heads/develop/scripts/wireguard-exit-policy/wireguard-exit-policy-manager.sh) and [testing scripts](https://raw.githubusercontent.com/nymtech/nym/refs/heads/develop/scripts/wireguard-exit-policy/exit-policy-tests.sh) written by Nym quality assurance team, to setup exit policy for wireguard:**
<Steps>
###### 1. Download the scripts and make executable
- SSH to your node
- Create a folder `~/nym-binaries` and navigate there
```sh
mkdir $HOME/nym-binaries
cd $HOME/nym-binaries
```
- Download the scripts
```sh
wget https://raw.githubusercontent.com/nymtech/nym/refs/heads/develop/scripts/wireguard-exit-policy/wireguard-exit-policy-manager.sh
wget https://raw.githubusercontent.com/nymtech/nym/refs/heads/develop/scripts/wireguard-exit-policy/exit-policy-tests.sh
```
- Make executable
```sh
chmod +x wireguard-exit-policy-manager.sh exit-policy-tests.sh
```
###### 2. Install `wireguard-exit-policy-manager.sh`
```sh
./wireguard-exit-policy-manager.sh install
```
- The output should look like this:
<AccordionTemplate name="Cosole output">
<ExitPolicyInstallOutput />
</ AccordionTemplate>
###### 3. Run `wireguard-exit-policy-manager.sh`
```sh
./wireguard-exit-policy-manager.sh status
```
- The output should look like this:
<AccordionTemplate name="Cosole output">
<ExitPolicyStatusOutput />
</ AccordionTemplate>
###### 4. Test with `exit-policy-tests.sh`
```sh
./exit-policy-tests.sh
```
- The output should look like this:
<AccordionTemplate name="Cosole output">
<ExitPolicyTestOutput />
</ AccordionTemplate>
###### 5. In case of problems, you can clear the exit policy rule
```sh
./wireguard-exit-policy-manager.sh clear
./wireguard-exit-policy-manager.sh status
```
</ Steps>
Now your wireguart routing should have same rotuing permissions like [Nym exit policy](https://nymtech.net/.wellknown/network-requester/exit-policy.txt) used on 5-hop (Mixnet) mode of NymVPN.
<WGExitPolicyConf />
### Testing Wireguard Exit Policy
You can validate the application of the IP tables routes on your `nym-node` by checking it from the server side as well as from the outside.
<div>
<Tabs items={[
<strong>From the server</strong>,
<strong>From the outside - using NymVPN</strong>
]} defaultIndex={0}>
<Tabs.Tab><ExitPolicyTestServer /></Tabs.Tab>
<Tabs.Tab><ExitPolicyTestOutside /></Tabs.Tab>
</Tabs>
</div>
Your node has successfully implemented wireguard exit policy with the same routing permissions like [Nym exit policy](https://nymtech.net/.wellknown/network-requester/exit-policy.txt) used on 5-hop (Mixnet).
<WGExitPolicyTest />
## QUIC Transport Bridge Deployment
@@ -21,10 +21,10 @@ This documentation page provides a guide on how to set up and run a [NYM NODE](.
```sh
nym-node
Binary Name: nym-node
Build Timestamp: 2025-11-12T08:19:33.288341371Z
Build Version: 1.21.0
Commit SHA: babf113fe5d396fa8a84fa939ad4b1b5b4d38b83
Commit Date: 2025-11-12T08:39:48.000000000+01:00
Build Timestamp: 2025-10-30T12:43:37.933354749Z
Build Version: 1.20.0
Commit SHA: 75a6d3426bd18dca600ad1cfa39b0a3c4f319c69
Commit Date: 2025-10-30T11:59:32.000000000+01:00
Commit Branch: HEAD
rustc Version: 1.88.0
rustc Channel: stable
@@ -9,21 +9,23 @@ Nym Node operators running Gateway functionality are already familiar with the m
## Preparation
We recommend to have installed all [the prerequisites](../binaries/building-nym.md#prerequisites) needed to build `nym-node` from source including latest [Rust Toolchain](https://www.rust-lang.org/tools/install), **and** make sure to have [Go](https://go.dev/doc/install) installed. Go is necessary as the probe uses the `rust2go` FFI library to use `netstack` when making requests.
We recommend to have installed all [the prerequisites](../binaries/building-nym.md#prerequisites) needed to build `nym-node` from source including latest [Rust Toolchain](https://www.rust-lang.org/tools/install), **and** make sure to have [Go](https://go.dev/doc/install) installed. Go is necessary as the probe uses the `rust2go` FFI library to use `netstack` when making requests.
## Installation
`nym-gateway-probe` source code is in [`nym` monorepo](https://github.com/nymtech/nym). The probe needs to be built from source.
`nym-gateway-probe` source code is in [`nym-vpn-client`](https://github.com/nymtech/nym-vpn-client) repository. The client needs to be build from source.
1. Clone the repository:
```sh
git clone https://github.com/nymtech/nym.git
git clone https://github.com/nymtech/nym-vpn-client.git
```
2. Build `nym-gateway-probe`:
```sh
cd nym-vpn-client/nym-vpn-core
cargo build --release -p nym-gateway-probe
```
@@ -32,71 +34,65 @@ cargo build --release -p nym-gateway-probe
To list all commands and options run the binary with `--help` command:
```sh
./target/release/nym-gateway-probe -h
./target/release/nym-gateway-probe -h
```
- Output:
```sh
Usage: nym-gateway-probe [OPTIONS] [COMMAND]
Usage: nym-gateway-probe [OPTIONS] --mnemonic <MNEMONIC>
Commands:
run-local Run the probe locally
help Print this message or the help of the given subcommand(s)
Options:
-c, --config-env-file <CONFIG_ENV_FILE>
Path pointing to an env file describing the network
-g, --entry-gateway <ENTRY_GATEWAY>
The specific gateway specified by ID
-n, --node <NODE>
Identity of the node to test
--min-gateway-mixnet-performance <MIN_GATEWAY_MIXNET_PERFORMANCE>
--only-wireguard
--ignore-egress-epoch-role
Disable logging during probe
--no-log
-a, --amnezia-args <AMNEZIA_ARGS>
Arguments to be appended to the wireguard config enabling amnezia-wg configuration
--netstack-download-timeout-sec <NETSTACK_DOWNLOAD_TIMEOUT_SEC>
[default: 180]
--metadata-timeout-sec <METADATA_TIMEOUT_SEC>
[default: 30]
--netstack-v4-dns <NETSTACK_V4_DNS>
[default: 1.1.1.1]
--netstack-v6-dns <NETSTACK_V6_DNS>
[default: 2606:4700:4700::1111]
--netstack-num-ping <NETSTACK_NUM_PING>
[default: 5]
--netstack-send-timeout-sec <NETSTACK_SEND_TIMEOUT_SEC>
[default: 3]
--netstack-recv-timeout-sec <NETSTACK_RECV_TIMEOUT_SEC>
[default: 3]
--netstack-ping-hosts-v4 <NETSTACK_PING_HOSTS_V4>
[default: nym.com]
--netstack-ping-ips-v4 <NETSTACK_PING_IPS_V4>
[default: 1.1.1.1]
--netstack-ping-hosts-v6 <NETSTACK_PING_HOSTS_V6>
[default: cloudflare.com]
--netstack-ping-ips-v6 <NETSTACK_PING_IPS_V6>
[default: 2001:4860:4860::8888 2606:4700:4700::1111 2620:fe::fe]
--ticket-materials <TICKET_MATERIALS>
--ticket-materials-revision <TICKET_MATERIALS_REVISION>
[default: 1]
-h, --help
Print help
-V, --version
Print version
Options:
-c, --config-env-file <CONFIG_ENV_FILE>
Path pointing to an env file describing the network
-g, --entry-gateway <ENTRY_GATEWAY>
The specific gateway specified by ID
-n, --node <NODE>
Identity of the node to test
--min-gateway-mixnet-performance <MIN_GATEWAY_MIXNET_PERFORMANCE>
--min-gateway-vpn-performance <MIN_GATEWAY_VPN_PERFORMANCE>
--only-wireguard
-i, --ignore-egress-epoch-role
Disable logging during probe
--no-log
-a, --amnezia-args <AMNEZIA_ARGS>
Arguments to be appended to the wireguard config enabling amnezia-wg configuration
--netstack-download-timeout-sec <NETSTACK_DOWNLOAD_TIMEOUT_SEC>
[default: 180]
--netstack-v4-dns <NETSTACK_V4_DNS>
[default: 1.1.1.1]
--netstack-v6-dns <NETSTACK_V6_DNS>
[default: 2606:4700:4700::1111]
--netstack-num-ping <NETSTACK_NUM_PING>
[default: 5]
--netstack-send-timeout-sec <NETSTACK_SEND_TIMEOUT_SEC>
[default: 3]
--netstack-recv-timeout-sec <NETSTACK_RECV_TIMEOUT_SEC>
[default: 3]
--netstack-ping-hosts-v4 <NETSTACK_PING_HOSTS_V4>
[default: nymtech.net]
--netstack-ping-ips-v4 <NETSTACK_PING_IPS_V4>
[default: 1.1.1.1]
--netstack-ping-hosts-v6 <NETSTACK_PING_HOSTS_V6>
[default: ipv6.google.com]
--netstack-ping-ips-v6 <NETSTACK_PING_IPS_V6>
[default: 2001:4860:4860::8888 2606:4700:4700::1111 2620:fe::fe]
--mnemonic <MNEMONIC>
-h, --help
Print help
-V, --version
Print version
```
To run the client, simply add `-g` flag followed by the ID key of the node you wish to test, as well as the mnemonic of a funded Nyx account; this is required to test the ticketbook generation. **Note that this accout needs to have NYM tokens; you cannot use an account with a NymVPN subscription**. Make sure to have at least a few NYM tokens in there.
To run the client, simply add `-n` flag followed by the ID key of the node you wish to test, as well as the mnemonic of a funded Nyx account; this is required to test the ticketbook generation.
```sh
./target/release/nym-gateway-probe run-local -g <GATEWAY_IDENTITY_KEY> --mnemonic <MNEMONIC>
./target/release/nym-gateway-probe -n <GATEWAY_IDENTITY_KEY> --mnemonic <MNEMONIC>
```
For any `nym-node --mode exit-gateway` the aim is to have this outcome:
@@ -129,4 +125,4 @@ For any `nym-node --mode exit-gateway` the aim is to have this outcome:
**If your Gateway is blacklisted, the probe will not work.**
If you don't provide a `-g` flag it will pick a random node to test.
If you don't provide a `-n` flag it will pick a random node to test.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 79 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 117 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 108 KiB

+1 -1
View File
@@ -4,7 +4,7 @@
[package]
name = "nym-api"
license = "GPL-3.0"
version = "1.1.70"
version = "1.1.68"
authors.workspace = true
edition = "2021"
rust-version.workspace = true
@@ -156,8 +156,12 @@ pub struct Cli {
#[derive(Args, Debug, Clone)]
pub struct UpgradeModeConfig {
/// URL for polling for upgrade mode changes.
#[clap(long, env = "NYM_CREDENTIAL_PROXY_ATTESTATION_CHECK_URL")]
pub(crate) attestation_check_url: Option<Url>,
#[clap(
long,
env = "NYM_CREDENTIAL_PROXY_ATTESTATION_CHECK_URL",
default_value = "5m"
)]
pub(crate) attestation_check_url: Url,
/// Default polling interval of the upgrade mode endpoint.
#[clap(
@@ -8,8 +8,6 @@ use nym_bin_common::bin_info;
use nym_credential_proxy_lib::error::CredentialProxyError;
use nym_credential_proxy_lib::storage::CredentialProxyStorage;
use nym_credential_proxy_lib::ticketbook_manager::TicketbookManager;
use nym_network_defaults::var_names;
use nym_network_defaults::var_names::CONFIGURED;
use tracing::{error, info};
pub async fn wait_for_signal() {
@@ -57,28 +55,6 @@ pub(crate) async fn run_api(cli: Cli) -> Result<(), CredentialProxyError> {
let webhook_cfg = cli.webhook;
let jwt_signing_keys = cli.jwt_signing_keys.signing_keys()?;
let upgrade_mode_attestation_check_url = match cli.upgrade_mode.attestation_check_url {
Some(url) => url,
None => {
// argument hasn't been provided and env is not configured
if std::env::var(CONFIGURED).is_err() {
return Err(CredentialProxyError::AttestationCheckUrlNotSet);
}
// argument hasn't been provided and the relevant env value hasn't been set
// (technically this shouldn't be possible)
let Ok(env_url) = std::env::var(var_names::UPGRADE_MODE_ATTESTATION_URL) else {
return Err(CredentialProxyError::AttestationCheckUrlNotSet);
};
match env_url.parse() {
Ok(url) => url,
Err(err) => {
return Err(CredentialProxyError::MalformedAttestationCheckUrl { source: err });
}
}
}
};
let ticketbook_manager = TicketbookManager::new(
build_sha_short(),
cli.quorum_check_interval,
@@ -94,7 +70,7 @@ pub(crate) async fn run_api(cli: Cli) -> Result<(), CredentialProxyError> {
cli.upgrade_mode.attestation_check_regular_polling_interval,
cli.upgrade_mode
.attestation_check_expedited_polling_interval,
upgrade_mode_attestation_check_url,
cli.upgrade_mode.attestation_check_url,
jwt_signing_keys,
cli.upgrade_mode.upgrade_mode_jwt_validity,
);
+1 -1
View File
@@ -56,7 +56,7 @@ nym-ip-packet-requests = { path = "../common/ip-packet-requests" }
nym-sdk = { path = "../sdk/rust/nym-sdk" }
nym-validator-client = { path = "../common/client-libs/validator-client" }
nym-credentials = { path = "../common/credentials" }
nym-http-api-client-macro = { path = "../common/http-api-client-macro" }
nym-http-api-client-macro = { path = "../common/http-api-client-macro", features = ["debug-inventory"] }
nym-http-api-client = { path = "../common/http-api-client" }
nym-node-status-client = { path = "../nym-node-status-api/nym-node-status-client" }
+1 -1
View File
@@ -3,7 +3,7 @@
[package]
name = "nym-node"
version = "1.22.0"
version = "1.20.0"
authors.workspace = true
repository.workspace = true
homepage.workspace = true
+35 -68
View File
@@ -3,9 +3,7 @@
use tokio_util::sync::CancellationToken;
use nym_authenticator_client::{
AuthClientMixnetListener, AuthClientMixnetListenerHandle, AuthenticatorClient,
};
use nym_authenticator_client::{AuthClientMixnetListener, AuthenticatorClient};
use nym_bandwidth_controller::BandwidthTicketProvider;
use nym_credentials_interface::TicketType;
use nym_ip_packet_client::IprClientConnect;
@@ -37,22 +35,9 @@ pub struct RegistrationClient {
event_rx: EventReceiver,
}
enum MixnetClientHandle {
Authenticator(AuthClientMixnetListenerHandle),
Sdk(Box<MixnetClient>),
}
impl MixnetClientHandle {
async fn stop(self) {
match self {
Self::Authenticator(handle) => handle.stop().await,
Self::Sdk(handle) => handle.disconnect().await,
}
}
}
// Bundle of an actual error and the underlying mixnet client so it can be shutdown correctly if needed
struct RegistrationError {
mixnet_client_handle: MixnetClientHandle,
mixnet_client: Option<MixnetClient>,
source: crate::RegistrationClientError,
}
@@ -64,7 +49,7 @@ impl RegistrationClient {
let Some(ipr_address) = self.config.exit.node.ipr_address else {
return Err(RegistrationError {
mixnet_client_handle: MixnetClientHandle::Sdk(Box::new(self.mixnet_client)),
mixnet_client: Some(self.mixnet_client),
source: RegistrationClientError::NoIpPacketRouterAddress {
node_id: self.config.exit.node.identity.to_base58_string(),
},
@@ -82,17 +67,13 @@ impl RegistrationClient {
Some(Ok(addr)) => addr,
Some(Err(e)) => {
return Err(RegistrationError {
mixnet_client_handle: MixnetClientHandle::Sdk(Box::new(
ipr_client.into_mixnet_client(),
)),
mixnet_client: Some(ipr_client.into_mixnet_client()),
source: RegistrationClientError::ConnectToIpPacketRouter(e),
});
}
None => {
return Err(RegistrationError {
mixnet_client_handle: MixnetClientHandle::Sdk(Box::new(
ipr_client.into_mixnet_client(),
)),
mixnet_client: Some(ipr_client.into_mixnet_client()),
source: RegistrationClientError::Cancelled,
});
}
@@ -116,7 +97,7 @@ impl RegistrationClient {
async fn register_wg(self) -> Result<RegistrationResult, RegistrationError> {
let Some(entry_auth_address) = self.config.entry.node.authenticator_address else {
return Err(RegistrationError {
mixnet_client_handle: MixnetClientHandle::Sdk(Box::new(self.mixnet_client)),
mixnet_client: Some(self.mixnet_client),
source: RegistrationClientError::AuthenticationNotPossible {
node_id: self.config.entry.node.identity.to_base58_string(),
},
@@ -125,7 +106,7 @@ impl RegistrationClient {
let Some(exit_auth_address) = self.config.exit.node.authenticator_address else {
return Err(RegistrationError {
mixnet_client_handle: MixnetClientHandle::Sdk(Box::new(self.mixnet_client)),
mixnet_client: Some(self.mixnet_client),
source: RegistrationClientError::AuthenticationNotPossible {
node_id: self.config.exit.node.identity.to_base58_string(),
},
@@ -169,50 +150,35 @@ impl RegistrationClient {
let exit_fut = exit_auth_client
.register_wireguard(&*self.bandwidth_controller, TicketType::V1WireguardExit);
let (entry, exit) = match Box::pin(
let (entry, exit) = Box::pin(
self.cancel_token
.run_until_cancelled(async { tokio::join!(entry_fut, exit_fut) }),
)
.await
{
Some((entry, exit)) => (entry, exit),
None => {
return Err(RegistrationError {
mixnet_client_handle: MixnetClientHandle::Authenticator(mixnet_listener),
source: RegistrationClientError::Cancelled,
});
}
};
.ok_or(RegistrationError {
mixnet_client: None,
source: RegistrationClientError::Cancelled,
})?;
let entry = match entry {
Ok(entry) => entry,
Err(source) => {
return Err(RegistrationError {
mixnet_client_handle: MixnetClientHandle::Authenticator(mixnet_listener),
source: RegistrationClientError::from_authenticator_error(
source,
self.config.entry.node.identity.to_base58_string(),
entry_auth_address,
true,
),
});
}
};
let entry = entry.map_err(|source| RegistrationError {
mixnet_client: None,
source: RegistrationClientError::from_authenticator_error(
source,
self.config.entry.node.identity.to_base58_string(),
entry_auth_address,
true,
),
})?;
let exit = match exit {
Ok(exit) => exit,
Err(source) => {
return Err(RegistrationError {
mixnet_client_handle: MixnetClientHandle::Authenticator(mixnet_listener),
source: RegistrationClientError::from_authenticator_error(
source,
self.config.exit.node.identity.to_base58_string(),
exit_auth_address,
false,
),
});
}
};
let exit = exit.map_err(|source| RegistrationError {
mixnet_client: None,
source: RegistrationClientError::from_authenticator_error(
source,
self.config.exit.node.identity.to_base58_string(),
exit_auth_address,
false,
),
})?;
Ok(RegistrationResult::Wireguard(Box::new(
WireguardRegistrationResult {
@@ -233,14 +199,15 @@ impl RegistrationClient {
self.register_mix_exit().await
};
// If we failed to register, shut down the mixnet client and wait for it to exit
// If we failed to register, and we were the owner of the mixnet client, shut it down
match registration_result {
Ok(result) => Ok(result),
Err(error) => {
debug!("Registration failed");
debug!("Shutting down mixnet client");
error.mixnet_client_handle.stop().await;
debug!("Mixnet client stopped");
if let Some(mixnet_client) = error.mixnet_client {
debug!("Shutting down mixnet client");
mixnet_client.disconnect().await;
}
Err(error.source)
}
}
-1
View File
@@ -4219,7 +4219,6 @@ dependencies = [
"serde_plain",
"serde_yaml",
"thiserror 2.0.12",
"tokio",
"tracing",
"url",
"wasmtimer",
-290
View File
@@ -1,290 +0,0 @@
#!/bin/bash
network_device=$(ip route show default | awk '/default/ {print $5}')
tunnel_interface="nymtun0"
wg_tunnel_interface="nymwg"
if ! dpkg -s iptables-persistent >/dev/null 2>&1; then
sudo apt-get update
sudo apt-get install -y iptables-persistent
else
echo "iptables-persistent is already installed."
fi
fetch_ipv6_address() {
local interface=$1
ipv6_global_address=$(ip -6 addr show "$interface" scope global | grep inet6 | awk '{print $2}' | head -n 1)
if [[ -z "$ipv6_global_address" ]]; then
echo "no globally routable IPv6 address found on $interface. Please configure IPv6 or check your network settings."
exit 1
else
echo "using IPv6 address: $ipv6_global_address"
fi
}
fetch_and_display_ipv6() {
ipv6_address=$(ip -6 addr show "$network_device" scope global | grep inet6 | awk '{print $2}')
if [[ -z "$ipv6_address" ]]; then
echo "no global IPv6 address found on $network_device."
else
echo "IPv6 address on $network_device: $ipv6_address"
fi
}
remove_duplicate_rules() {
local interface=$1
local script_name=$(basename "$0")
if [[ -z "$interface" ]]; then
echo "error: no interface specified. please enter the interface (nymwg or nymtun0):"
read -r interface
fi
if [[ "$interface" != "nymwg" && "$interface" != "nymtun0" ]]; then
echo "error: invalid interface '$interface'. allowed values are 'nymwg' or 'nymtun0'." >&2
exit 1
fi
echo "removing duplicate rules for $interface..."
iptables-save | grep "$interface" | while read -r line; do
sudo iptables -D ${line#-A } || echo "Failed to delete rule: $line"
done
ip6tables-save | grep "$interface" | while read -r line; do
sudo ip6tables -D ${line#-A } || echo "Failed to delete rule: $line"
done
echo "duplicates removed for $interface."
echo "!!-important-!! you need to now reapply the iptables rules for $interface."
if [ "$interface" == "nymwg" ]; then
echo "run: ./$script_name apply_iptables_rules_wg"
else
echo "run: ./$script_name apply_iptables_rules"
fi
}
adjust_ip_forwarding() {
ipv6_forwarding_setting="net.ipv6.conf.all.forwarding=1"
ipv4_forwarding_setting="net.ipv4.ip_forward=1"
# remove duplicate entries for these settings from the file
sudo sed -i "/^net.ipv6.conf.all.forwarding=/d" /etc/sysctl.conf
sudo sed -i "/^net.ipv4.ip_forward=/d" /etc/sysctl.conf
echo "$ipv6_forwarding_setting" | sudo tee -a /etc/sysctl.conf
echo "$ipv4_forwarding_setting" | sudo tee -a /etc/sysctl.conf
sudo sysctl -p /etc/sysctl.conf
}
apply_iptables_rules() {
local interface=$1
echo "applying IPtables rules for $interface..."
sleep 2
sudo iptables -t nat -A POSTROUTING -o "$network_device" -j MASQUERADE
sudo iptables -A FORWARD -i "$interface" -o "$network_device" -j ACCEPT
sudo iptables -A FORWARD -i "$network_device" -o "$interface" -m state --state RELATED,ESTABLISHED -j ACCEPT
sudo ip6tables -t nat -A POSTROUTING -o "$network_device" -j MASQUERADE
sudo ip6tables -A FORWARD -i "$interface" -o "$network_device" -j ACCEPT
sudo ip6tables -A FORWARD -i "$network_device" -o "$interface" -m state --state RELATED,ESTABLISHED -j ACCEPT
sudo iptables-save | sudo tee /etc/iptables/rules.v4
sudo ip6tables-save | sudo tee /etc/iptables/rules.v6
}
check_tunnel_iptables() {
local interface=$1
echo "inspecting IPtables rules for $interface..."
echo "---------------------------------------"
echo "IPv4 rules:"
iptables -L FORWARD -v -n | awk -v dev="$interface" '/^Chain FORWARD/ || $0 ~ dev || $0 ~ "ufw-reject-forward"'
echo "---------------------------------------"
echo "IPv6 rules:"
ip6tables -L FORWARD -v -n | awk -v dev="$interface" '/^Chain FORWARD/ || $0 ~ dev || $0 ~ "ufw6-reject-forward"'
}
check_ipv6_ipv4_forwarding() {
result_ipv4=$(cat /proc/sys/net/ipv4/ip_forward)
result_ipv6=$(cat /proc/sys/net/ipv6/conf/all/forwarding)
echo "IPv4 forwarding is $([ "$result_ipv4" == "1" ] && echo "enabled" || echo "not enabled")."
echo "IPv6 forwarding is $([ "$result_ipv6" == "1" ] && echo "enabled" || echo "not enabled")."
}
check_ip_routing() {
echo "IPv4 routing table:"
ip route
echo "---------------------------------------"
echo "IPv6 routing table:"
ip -6 route
}
perform_pings() {
echo "performing IPv4 ping to google.com..."
ping -c 4 google.com
echo "---------------------------------------"
echo "performing IPv6 ping to google.com..."
ping6 -c 4 google.com
}
joke_through_tunnel() {
local interface=$1
local green="\033[0;32m"
local reset="\033[0m"
local red="\033[0;31m"
local yellow="\033[0;33m"
sleep 1
echo
echo -e "${yellow}checking tunnel connectivity and fetching a joke for $interface...${reset}"
echo -e "${yellow}if these test succeeds, it confirms your machine can reach the outside world via IPv4 and IPv6.${reset}"
echo -e "${yellow}however, probes and external clients may experience different connectivity to your nym-node.${reset}"
ipv4_address=$(ip addr show "$interface" | awk '/inet / {print $2}' | cut -d'/' -f1)
ipv6_address=$(ip addr show "$interface" | awk '/inet6 / && $2 !~ /^fe80/ {print $2}' | cut -d'/' -f1)
if [[ -z "$ipv4_address" && -z "$ipv6_address" ]]; then
echo -e "${red}no IP address found on $interface. unable to fetch a joke.${reset}"
echo -e "${red}please verify your tunnel configuration and ensure the interface is up.${reset}"
return 1
fi
if [[ -n "$ipv4_address" ]]; then
echo
echo -e "------------------------------------"
echo -e "detected IPv4 address: $ipv4_address"
echo -e "testing IPv4 connectivity..."
echo
if ping -c 1 -I "$ipv4_address" google.com >/dev/null 2>&1; then
echo -e "${green}IPv4 connectivity is working. fetching a joke...${reset}"
joke=$(curl -s -H "Accept: application/json" --interface "$ipv4_address" https://icanhazdadjoke.com/ | jq -r .joke)
[[ -n "$joke" && "$joke" != "null" ]] && echo -e "${green}IPv4 joke: $joke${reset}" || echo -e "failed to fetch a joke via IPv4."
else
echo -e "${red}IPv4 connectivity is not working for $interface. verify your routing and NAT settings.${reset}"
fi
else
echo -e "${red}no IPv4 address found on $interface. unable to fetch a joke via IPv4.${reset}"
fi
if [[ -n "$ipv6_address" ]]; then
echo
echo -e "------------------------------------"
echo -e "detected IPv6 address: $ipv6_address"
echo -e "testing IPv6 connectivity..."
echo
if ping6 -c 1 -I "$ipv6_address" google.com >/dev/null 2>&1; then
echo -e "${green}IPv6 connectivity is working. fetching a joke...${reset}"
joke=$(curl -s -H "Accept: application/json" --interface "$ipv6_address" https://icanhazdadjoke.com/ | jq -r .joke)
[[ -n "$joke" && "$joke" != "null" ]] && echo -e "${green}IPv6 joke: $joke${reset}" || echo -e "${red}failed to fetch a joke via IPv6.${reset}"
else
echo -e "${red}IPv6 connectivity is not working for $interface. verify your routing and NAT settings.${reset}"
fi
else
echo -e "${red}no IPv6 address found on $interface. unable to fetch a joke via IPv6.${reset}"
fi
echo -e "${green}joke fetching processes completed for $interface.${reset}"
echo -e "------------------------------------"
sleep 3
echo
echo
echo -e "${yellow}### connectivity testing recommendations ###${reset}"
echo -e "${yellow}- use the following command to test WebSocket connectivity from an external client:${reset}"
echo -e "${yellow} wscat -c wss://<your-ip-address/ hostname>:9001 ${reset}"
echo -e "${yellow}- test UDP connectivity on port 51822 (commonly used for nym wireguard) ${reset}"
echo -e "${yellow} from another machine, use tools like nc or socat to send UDP packets ${reset}"
echo -e "${yellow} echo 'test message' | nc -u <your-ip-address> 51822 ${reset}"
echo -e "${yellow}if connectivity issues persist, ensure port forwarding and firewall rules are correctly configured ${reset}"
echo
}
configure_dns_and_icmp_wg() {
echo "allowing icmp (ping)..."
sudo iptables -A INPUT -p icmp --icmp-type echo-request -j ACCEPT
sudo iptables -A OUTPUT -p icmp --icmp-type echo-reply -j ACCEPT
echo "allowing dns over udp (port 53)..."
sudo iptables -A INPUT -p udp --dport 53 -j ACCEPT
echo "allowing dns over tcp (port 53)..."
sudo iptables -A INPUT -p tcp --dport 53 -j ACCEPT
echo "saving iptables rules..."
sudo iptables-save >/etc/iptables/rules.v4
echo "dns and icmp configuration completed."
}
case "$1" in
fetch_ipv6_address_nym_tun)
fetch_ipv6_address "$tunnel_interface"
;;
fetch_and_display_ipv6)
fetch_and_display_ipv6
;;
apply_iptables_rules)
apply_iptables_rules "$tunnel_interface"
;;
apply_iptables_rules_wg)
apply_iptables_rules "$wg_tunnel_interface"
;;
check_nymtun_iptables)
check_tunnel_iptables "$tunnel_interface"
;;
check_nym_wg_tun)
check_tunnel_iptables "$wg_tunnel_interface"
;;
check_ipv6_ipv4_forwarding)
check_ipv6_ipv4_forwarding
;;
check_ip_routing)
check_ip_routing
;;
perform_pings)
perform_pings
;;
joke_through_the_mixnet)
joke_through_tunnel "$tunnel_interface"
;;
joke_through_wg_tunnel)
joke_through_tunnel "$wg_tunnel_interface"
;;
configure_dns_and_icmp_wg)
configure_dns_and_icmp_wg
;;
adjust_ip_forwarding)
adjust_ip_forwarding
;;
remove_duplicate_rules)
remove_duplicate_rules "$2"
;;
*)
echo "Usage: $0 [command]"
echo "Commands:"
echo " fetch_ipv6_address_nym_tun - Fetch IPv6 for nymtun0."
echo " fetch_and_display_ipv6 - Show IPv6 on default device."
echo " apply_iptables_rules - Apply IPtables rules for nymtun0."
echo " apply_iptables_rules_wg - Apply IPtables rules for nymwg."
echo " check_nymtun_iptables - Check IPtables for nymtun0."
echo " check_nym_wg_tun - Check IPtables for nymwg."
echo " check_ipv6_ipv4_forwarding - Check IPv4 and IPv6 forwarding."
echo " check_ip_routing - Display IP routing tables."
echo " perform_pings - Test IPv4 and IPv6 connectivity."
echo " joke_through_the_mixnet - Fetch a joke via nymtun0."
echo " joke_through_wg_tunnel - Fetch a joke via nymwg."
echo " configure_dns_and_icmp_wg - Allows icmp ping tests for probes alongside configuring dns"
echo " adjust_ip_forwarding - Enable IPV6 and IPV4 forwarding"
echo " remove_duplicate_rules <interface> - Remove duplicate iptables rules. Valid interfaces: nymwg, nymtun0"
exit 1
;;
esac
echo "operation $1 completed successfully."
File diff suppressed because it is too large Load Diff
+186 -82
View File
@@ -1,6 +1,6 @@
#!/usr/bin/python3
__version__ = "1.1.0"
__version__ = "1.2.0"
__default_branch__ = "develop"
import os
@@ -22,17 +22,25 @@ class NodeSetupCLI:
def __init__(self, args):
self.branch = args.dev
self.welcome_message = self.print_welcome_message()
self.mode = self.prompt_mode()
self.mode = self._get_or_prompt_mode(args)
self.prereqs_install_sh = self.fetch_script("nym-node-prereqs-install.sh")
self.env_vars_install_sh = self.fetch_script("setup-env-vars.sh")
self.node_install_sh = self.fetch_script("nym-node-install.sh")
self.service_config_sh = self.fetch_script("setup-systemd-service-file.sh")
self.start_node_systemd_service_sh = self.fetch_script("start-node-systemd-service.sh")
self.landing_page_html = self._check_gwx_mode() and self.fetch_script("landing-page.html")
self.nginx_proxy_wss_sh = self._check_gwx_mode() and self.fetch_script("nginx_proxy_wss_sh")
self.tunnel_manager_sh = self._check_gwx_mode() and self.fetch_script("network_tunnel_manager.sh")
self.wg_ip_tables_manager_sh = self._check_gwx_mode() and self.fetch_script("wireguard-exit-policy-manager.sh")
self.wg_ip_tables_test_sh = self._check_gwx_mode() and self.fetch_script("exit-policy-tests.sh")
self.is_gwx = self.mode == "exit-gateway"
if self.is_gwx:
self.landing_page_html = self.fetch_script("landing-page.html")
self.nginx_proxy_wss_sh = self.fetch_script("nginx_proxy_wss_sh")
self.tunnel_manager_sh = self.fetch_script("network_tunnel_manager.sh")
self.quic_bridge_deployment_sh = self.fetch_script("quic_bridge_deployment.sh")
else:
self.landing_page_html = None
self.nginx_proxy_wss_sh = None
self.tunnel_manager_sh = None
self.wg_ip_tables_manager_sh = None
self.wg_ip_tables_test_sh = None
self.quic_bridge_deployment_sh = None
def print_welcome_message(self):
"""Welcome user, warns for needed pre-reqs and asks for confimation"""
@@ -45,7 +53,7 @@ class NodeSetupCLI:
self.print_character("=", 41)
msg = \
"Before you begin, make sure that:\n"\
"1. You run this setup on Debian based Linux (ie Ubuntu)\n"\
"1. You run this setup on Debian based Linux (ie Ubuntu 22.04 LTS)\n"\
"2. You run this installation program from a root shell\n"\
"3. You meet minimal requirements: https://nym.com/docs/operators/nodes\n"\
"4. You accept Operators Terms & Conditions: https://nym.com/operators-validators-terms\n"\
@@ -59,43 +67,103 @@ class NodeSetupCLI:
else:
print("Without confirming the points above, we cannot continue.")
exit(1)
def ensure_env_values(self, args):
"""Collect env vars from args or prompt interactively, then save to env.sh."""
env_file = Path("env.sh")
fields = [
("hostname", "HOSTNAME", "Enter hostname (if you don't use a DNS, press enter): "),
("location", "LOCATION", "Enter node location (country code or name): "),
("email", "EMAIL", "Enter your email: "),
("moniker", "MONIKER", "Enter node public moniker (visible in explorer & NymVPN app): "),
("description", "DESCRIPTION", "Enter short node public description: "),
]
def prompt_mode(self):
"""Ask user to insert node functionality and save it in python and bash envs"""
existing = self._read_env_file(env_file)
updated = {}
for arg_name, key, prompt in fields:
cli_val = getattr(args, arg_name, None)
value = cli_val.strip() if cli_val else existing.get(key) or input(prompt).strip()
updated[key] = value
os.environ[key] = value
# autodetect PUBLIC_IP if not already set
if not os.environ.get("PUBLIC_IP"):
try:
ip = subprocess.run(["curl", "-fsS4", "https://ifconfig.me"],
capture_output=True, text=True, timeout=5)
if ip.returncode == 0 and ip.stdout.strip():
updated["PUBLIC_IP"] = ip.stdout.strip()
os.environ["PUBLIC_IP"] = ip.stdout.strip()
except subprocess.TimeoutExpired:
print("[WARN] Timeout expired while trying to fetch public IP with curl.")
except FileNotFoundError:
print("[WARN] 'curl' command not found. Please install curl or set PUBLIC_IP manually.")
except subprocess.CalledProcessError as e:
print(f"[WARN] Error while running curl to fetch public IP: {e}")
# write all collected variables to env.sh in one go
self._upsert_env_vars(updated, env_file)
print(f"[OK] Updated env.sh with {len(updated)} entries.")
def _upsert_env_vars(self, updates: dict, env_file: Path = Path("env.sh")):
existing = self._read_env_file(env_file)
existing.update(updates)
with env_file.open("w") as f:
for k, v in existing.items():
f.write(f'export {k}="{v}"\n')
os.environ.update(updates)
def _read_env_file(self, env_file: Path) -> dict:
env = {}
if env_file.exists():
for line in env_file.read_text().splitlines():
if line.startswith("export ") and "=" in line:
k, v = line.replace("export ", "", 1).split("=", 1)
env[k.strip()] = v.strip().strip('"')
return env
def _get_or_prompt_mode(self, args):
"""Resolve MODE from --mode, env.sh, os.environ, or prompt; persist to env.sh."""
env_file = Path("env.sh")
# CLI arg
mode = getattr(args, "mode", None)
if mode:
mode = mode.strip().lower()
self._upsert_env_vars({"MODE": mode})
print(f"Mode set to '{mode}' from CLI argument.")
return mode
# env.sh (replaces manual read)
existing = self._read_env_file(env_file)
mode = existing.get("MODE")
if mode:
os.environ["MODE"] = mode
return mode
# process env
if os.environ.get("MODE"):
return os.environ["MODE"]
# prompt
mode = input(
"\nEnter the mode you want to run nym-node in: "
"\n1. mixnode "
"\n2. entry-gateway "
"\n3. exit-gateway (works as entry-gateway as well) "
"\nPress 1, 2 or 3 and enter:\n"
).strip()
if mode in ("1", "mixnode"):
mode = "mixnode"
elif mode in ("2", "entry-gateway"):
mode = "entry-gateway"
elif mode in ("3", "exit-gateway"):
mode = "exit-gateway"
else:
print("Only numbers 1, 2 or 3 are accepted.")
"\nEnter node mode (mixnode / entry-gateway / exit-gateway): "
).strip().lower()
if mode not in ("mixnode", "entry-gateway", "exit-gateway"):
print("Invalid mode. Must be one of: mixnode, entry-gateway, exit-gateway.")
raise SystemExit(1)
# save mode for this Python instance
self.mode = mode
os.environ["MODE"] = mode
# persist to env.sh so other scripts can source it
env_file = Path("env.sh")
with env_file.open("a") as f:
f.write(f'export MODE="{mode}"\n')
# source env.sh so future bash subprocesses see it immediately
subprocess.run("source ./env.sh", shell=True, executable="/bin/bash")
self._upsert_env_vars({"MODE": mode})
print(f"Mode set to '{mode}' — stored in env.sh and sourced for immediate use.")
return mode
def fetch_script(self, script_name):
"""Fetches needed scripts according to a defined mode"""
# print header only the first time
@@ -119,16 +187,15 @@ class NodeSetupCLI:
github_raw_nymtech_nym_scripts_url = f"https://raw.githubusercontent.com/nymtech/nym/refs/heads/{self.branch}/scripts/"
scripts_urls = {
"nym-node-prereqs-install.sh": f"{github_raw_nymtech_nym_scripts_url}nym-node-setup/nym-node-prereqs-install.sh",
"setup-env-vars.sh": f"{github_raw_nymtech_nym_scripts_url}nym-node-setup/setup-env-vars.sh",
"nym-node-install.sh": f"{github_raw_nymtech_nym_scripts_url}nym-node-setup/nym-node-install.sh",
"setup-systemd-service-file.sh": f"{github_raw_nymtech_nym_scripts_url}nym-node-setup/setup-systemd-service-file.sh",
"start-node-systemd-service.sh": f"{github_raw_nymtech_nym_scripts_url}nym-node-setup/start-node-systemd-service.sh",
"nginx_proxy_wss_sh": f"{github_raw_nymtech_nym_scripts_url}nym-node-setup/setup-nginx-proxy-wss.sh",
"landing-page.html": f"{github_raw_nymtech_nym_scripts_url}nym-node-setup/landing-page.html",
"network_tunnel_manager.sh": f"https://raw.githubusercontent.com/nymtech/nym/refs/heads/develop/scripts/network_tunnel_manager.sh",
"wireguard-exit-policy-manager.sh": f"https://raw.githubusercontent.com/nymtech/nym/refs/heads/develop/scripts/wireguard-exit-policy/wireguard-exit-policy-manager.sh",
"exit-policy-tests.sh": f"https://raw.githubusercontent.com/nymtech/nym/refs/heads/develop/scripts/wireguard-exit-policy/exit-policy-tests.sh",
"network_tunnel_manager.sh": f"{github_raw_nymtech_nym_scripts_url}nym-node-setup/network-tunnel-manager.sh",
"quic_bridge_deployment.sh": f"{github_raw_nymtech_nym_scripts_url}nym-node-setup/quic_bridge_deployment.sh"
}
return scripts_urls[script_init_name]
def run_script(
@@ -200,62 +267,61 @@ class NodeSetupCLI:
def _check_gwx_mode(self):
"""Helper: Several fns run only for GWx - this fn checks this condition"""
if self.mode == "exit-gateway":
return True
else:
return False
return self.mode == "exit-gateway"
def check_wg_enabled(self):
"""Checks if Wireguard is enabled and if not, prompts user if they want to enable it, stores it to env.sh"""
def check_wg_enabled(self, args=None):
"""Determine if WireGuard is enabled; precedence: CLI > env > env.sh > prompt. Persist normalized value."""
env_file = os.path.join(os.getcwd(), "env.sh")
env_file = os.path.abspath(os.path.join(os.getcwd(), "env.sh"))
def norm(v):
return "true" if str(v).strip().lower() == "true" else "false"
def norm(v): # -> "true" or "false"
return "true" if str(v).strip().lower() in ("1", "true", "yes", "y") else "false"
val = None
# precedence: process env → env.sh → prompt
val = os.environ.get("WIREGUARD")
# CLI argument
if args and getattr(args, "wireguard", None) is not None:
val = norm(getattr(args, "wireguard"))
print(f"[INFO] WireGuard mode provided via CLI: {val}")
if val is None and os.path.isfile(env_file):
try:
with open(env_file, "r", encoding="utf-8") as f:
m = re.search(r'^\s*export\s+WIREGUARD\s*=\s*"?([^"\n]+)"?', f.read(), re.M)
if m:
val = m.group(1)
except Exception:
pass
# Environment variable
val = val or os.environ.get("WIREGUARD")
# env.sh file
if val is None:
envs = self._read_env_file(Path(env_file))
val = envs.get("WIREGUARD")
# Prompt
if val is None:
ans = input(
"\nWireGuard is not configured.\n"
"Nodes routing WireGuard can be listed as both entry and exit in the app.\n"
"Enable WireGuard support? (y/n): "
"Enable WireGuard support? (Y/n): "
).strip().lower()
val = "true" if ans in ("y", "yes") else "false"
val = "true" if ans in ("", "y", "yes") else "false"
val = norm(val)
os.environ["WIREGUARD"] = val
# persist to env.sh (replace or append)
# Persist to env.sh
try:
text = ""
if os.path.isfile(env_file):
with open(env_file, "r", encoding="utf-8") as f:
with open(env_file, encoding="utf-8") as f:
text = f.read()
if re.search(r'^\s*export\s+WIREGUARD\s*=.*$', text, re.M):
text = re.sub(r'^\s*export\s+WIREGUARD\s*=.*$', f'export WIREGUARD="{val}"', text, flags=re.M)
else:
if text and not text.endswith("\n"):
text += "\n"
text += f'export WIREGUARD="{val}"\n'
text = (text.rstrip("\n") + "\n" if text else "") + f'export WIREGUARD="{val}"\n'
with open(env_file, "w", encoding="utf-8") as f:
f.write(text)
print(f'WIREGUARD={val} saved to {env_file}')
except Exception as e:
except OSError as e:
print(f"Warning: could not write {env_file}: {e}")
return (val == "true")
return val == "true"
def run_bash_command(self, command, args=None, *, env=None, cwd=None, check=True):
"""
@@ -316,10 +382,17 @@ class NodeSetupCLI:
"Setting up Wireguard IP tables to match Nym exit policy for mixnet, stored at: https://nymtech.net/.wellknown/network-requester/exit-policy.txt"
"\nThis may take a while, follow the steps below and don't kill the process..."
)
self.run_script(self.wg_ip_tables_manager_sh, args=["install"])
self.run_script(self.wg_ip_tables_manager_sh, args=["status"])
self.run_script(self.wg_ip_tables_test_sh)
self.run_script(self.tunnel_manager_sh, args=["exit_policy_install"])
def quic_bridge_deploy(self):
"""Setup QUIC bridge and configuration using external script"""
print("\n* * * Installing and configuring QUIC bridges * * *")
answer = input("\nDo you want to install, setup and run QUIC bridge? (Y/n) ").strip().lower()
if answer in ("", "y", "yes"):
self.run_script(self.quic_bridge_deployment_sh, args=["full_bridge_setup"])
else:
print("Skipping QUIC bridge setup.")
def run_nym_node_as_service(self):
"""Starts /etc/systemd/system/nym-node.service based on prompt using external script"""
@@ -347,8 +420,8 @@ class NodeSetupCLI:
if is_active:
while True:
ans = input(f"{service} is already running. Restart it now? (y/n):\n").strip().lower()
if ans == "y":
ans = input(f"{service} is already running. Restart it now? (Y/n):\n").strip().lower()
if ans in ("", "Y", "y"):
self.run_script(self.start_node_systemd_service_sh, args=["restart-poll"], env=run_env)
return
elif ans == "n":
@@ -358,8 +431,8 @@ class NodeSetupCLI:
print("Invalid input. Please press 'y' or 'n' and press enter.")
else:
while True:
ans = input(f"{service} is not running. Start it now? (y/n):\n").strip().lower()
if ans == "y":
ans = input(f"{service} is not running. Start it now? (Y/n):\n").strip().lower()
if ans in ("", "Y", "y"):
self.run_script(self.start_node_systemd_service_sh, args=["start-poll"], env=run_env)
return
elif ans == "n":
@@ -510,8 +583,12 @@ class NodeSetupCLI:
def run_node_installation(self,args):
"""Main function called by argparser command install running full node install flow"""
self.ensure_env_values(args)
# Pass uplink override to all helper scripts if provided
if getattr(args, "uplink_dev", None):
os.environ["UPLINK_DEV"] = args.uplink_dev
os.environ["NETWORK_DEVICE"] = args.uplink_dev
self.run_script(self.prereqs_install_sh)
self.run_script(self.env_vars_install_sh)
self.run_script(self.node_install_sh)
self.run_script(self.service_config_sh)
self._check_gwx_mode() and self.run_script(self.nginx_proxy_wss_sh)
@@ -521,7 +598,7 @@ class NodeSetupCLI:
self.run_tunnel_manager_setup()
if self.check_wg_enabled():
self.setup_test_wg_ip_tables()
self.setup_test_wg_ip_tables()
self.quic_bridge_deploy()
@@ -537,7 +614,7 @@ class ArgParser:
version=f"nym-node-cli {__version__}"
)
parent.add_argument("-d", "--dev", metavar="BRANCH",
help="Define github branch",
help="Define github branch (default: develop)",
type=str,
default=argparse.SUPPRESS)
parent.add_argument("-v", "--verbose", action="store_true",
@@ -553,11 +630,38 @@ class ArgParser:
subparsers = parser.add_subparsers(dest="command", help="subcommands")
subparsers.required = True
p_install = subparsers.add_parser(
install_parser = subparsers.add_parser(
"install", parents=[parent],
help="Starts nym-node installation setup CLI",
aliases=["i", "I"], add_help=True
)
install_parser.add_argument(
"--mode",
choices=["mixnode", "entry-gateway", "exit-gateway"],
help="Node mode: 'mixnode', 'entry-gateway', or 'exit-gateway'",
)
install_parser.add_argument(
"--wireguard-enabled",
choices=["true", "false"],
help="WireGuard functionality switch: true / false"
)
install_parser.add_argument("--hostname", help="Node domain / hostname")
install_parser.add_argument("--location", help="Node location (country code or name)")
install_parser.add_argument("--email", help="Contact email for the node operator")
install_parser.add_argument("--moniker", help="Public moniker displayed in explorer & NymVPN app")
install_parser.add_argument("--description", help="Short public description of the node")
install_parser.add_argument("--public-ip", help="External IPv4 address (autodetected if omitted)")
install_parser.add_argument("--nym-node-binary", help="URL for nym-node binary (autodetected if omitted)")
install_parser.add_argument("--uplink-dev", help="Override uplink interface used for NAT/FORWARD (e.g., 'eth0'; autodetected if omitted)")
# generic fallback
install_parser.add_argument(
"--env",
action="append",
metavar="KEY=VALUE",
help="(Optional) Extra ENV VARS, e.g. --env CUSTOM_KEY=value",
)
args = parser.parse_args()
+26 -21
View File
@@ -34,8 +34,9 @@ check_existing_config() {
if [[ "${resp}" =~ ^([Rr][Ee][Ss][Ee][Tt])$ ]]; then
echo
read -r -p "We are going to remove the existing node with configuration $NODE_CONFIG_DIR and replace it with a fresh one, do you want to back up the old one first? (y/n) " backup_ans
if [[ "${backup_ans}" =~ ^[Yy]$ ]]; then
echo "We are going to remove the existing node with configuration $NODE_CONFIG_DIR and replace it with a fresh one."
read -r -p "back up the old one first? (Y/n) " backup_ans
if [[ -z "${backup_ans}" || "${backup_ans}" =~ ^[Yy]$ ]]; then
ts="$(date +%Y%m%d-%H%M%S)"
backup_dir="$HOME/.nym/backup/$(basename "$NODE_CONFIG_DIR")-$ts"
echo "Backing up to: $backup_dir"
@@ -181,24 +182,27 @@ fi
NYM_NODE="$HOME/nym-binaries/nym-node"
# if binary already exists, ask to overwrite; if yes, remove first
# if binary already exists, ask to overwrite; if yes, remove first; if no, skip download
if [[ -e "${NYM_NODE}" ]]; then
echo
echo -e "\n* * * A nym-node binary already exists at: ${NYM_NODE}"
read -r -p "Overwrite with the latest release? (y/n): " ow_ans
if [[ "${ow_ans}" =~ ^[Yy]$ ]]; then
echo "Removing existing binary to avoid 'text file busy'..."
rm -f "${NYM_NODE}"
else
echo "Keeping existing binary."
fi
fi
read -r -p "Overwrite with the latest release? (Y/n): " ow_ans
download_nym_node "$LATEST_TAG_URL" "$NYM_NODE"
if [[ -z "${ow_ans}" || "${ow_ans}" =~ ^[Yy]$ ]]; then
echo "Removing existing binary..."
rm -f "${NYM_NODE}"
download_nym_node "$LATEST_TAG_URL" "$NYM_NODE"
else
echo "Keeping existing binary. Skipping download."
fi
else
# binary does not exist → must download
download_nym_node "$LATEST_TAG_URL" "$NYM_NODE"
fi
echo -e "\n * * * Making binary executable * * *"
chmod +x "${NYM_NODE}"
echo "---------------------------------------------------"
echo "Nym node binary downloaded:"
"${NYM_NODE}" --version || true
@@ -225,17 +229,18 @@ WIREGUARD="${WIREGUARD:-}"
if [[ ( "$MODE" == "entry-gateway" || "$MODE" == "exit-gateway" ) && ( -n "${ASK_WG:-}" || -z "$WIREGUARD" ) ]]; then
echo
echo "Gateways can also route WireGuard in NymVPN."
echo "Enabling it means your node may be listed as both entry and exit in the app."
# show current default in the prompt if present
def_hint=""
[[ -n "${WIREGUARD}" ]] && def_hint=" [current: ${WIREGUARD}]"
read -r -p "Enable WireGuard support? (y/n)${def_hint}: " answer || true
case "${answer:-}" in
[Yy]* ) WIREGUARD="true" ;;
[Nn]* ) WIREGUARD="false" ;;
* ) : ;; # keep existing value if user just pressed enter
esac
read -r -p "Enable WireGuard support? (Y/n)${def_hint}: " answer || true
if [[ -z "${answer}" || "${answer}" =~ ^[Yy]$ ]]; then
WIREGUARD="true"
elif [[ "${answer}" =~ ^[Nn]$ ]]; then
WIREGUARD="false"
fi
fi
# final default only if still empty
WIREGUARD="${WIREGUARD:-false}"
@@ -1,29 +1,13 @@
#!/bin/bash
# update, upgrade & install dependencies
if [[ "$(id -u)" -ne 0 ]]; then
echo "This script must be run as root."
exit 1
fi
# update, upgrade and install dependencies
echo -e "\n* * * Installing needed prerequisities * * *"
apt update -y && apt --fix-broken install
apt upgrade
apt install apt ca-certificates jq curl wget ufw jq tmux pkg-config build-essential libssl-dev git ntp ntpdate neovim tree tmux tig nginx -y
apt install ufw --fix-missing
# enable & setup firewall
echo -e "\n* * * Setting up firewall using ufw * * * "
echo "Please enable the firewall in the next prompt for node proper routing!"
echo
ufw enable
ufw allow 22/tcp # SSH - you're in control of these ports
ufw allow 80/tcp # HTTP
ufw allow 443/tcp # HTTPS
ufw allow 1789/tcp # Nym specific
ufw allow 1790/tcp # Nym specific
ufw allow 8080/tcp # Nym specific - nym-node-api
ufw allow 9000/tcp # Nym Specific - clients port
ufw allow 9001/tcp # Nym specific - wss port
ufw allow 51822/udp # WireGuard
ufw allow 'Nginx Full' && \
ufw reload && \
ufw status
@@ -47,7 +47,17 @@ NYM_ETC_BRIDGES="$NYM_ETC_DIR/bridges.toml"
NYM_ETC_CLIENT_PARAMS_DEFAULT="$NYM_ETC_DIR/client_bridge_params.json"
SERVICE_FILE="/etc/systemd/system/nym-bridge.service"
NET_DEV="$(ip route show default 2>/dev/null | awk '/default/ {print $5}' || true)"
NET_DEV="${UPLINK_DEV:-}"
if [[ -z "$NET_DEV" ]]; then
NET_DEV="$(ip -o route show default 2>/dev/null | awk '{print $5}' | head -n1)"
[[ -z "$NET_DEV" ]] && NET_DEV="$(ip -o route show default table all 2>/dev/null | awk '{print $5}' | head -n1)"
fi
if [[ -z "$NET_DEV" ]]; then
echo -e "${RED}Cannot determine uplink interface. Set UPLINK_DEV.${RESET}" | tee -a "$LOG_FILE"
exit 1
fi
echo "Using uplink device: $NET_DEV"
WG_IFACE="nymwg"
# Root check
@@ -65,6 +75,17 @@ err() { echo -e "${RED}$1${RESET}"; }
info() { echo -e "${CYAN}$1${RESET}"; }
press_enter() { read -r -p "$1"; }
# Disable pauses and interactive prompts for noninteractive mode
if [[ "${NONINTERACTIVE:-0}" == "1" ]]; then
# all pauses become no-ops
press_enter() { :; }
# silence any "enter path:" prompts
echo_prompt() { :; }
else
echo_prompt() { echo -n "$1"; }
fi
# Helper: detect dpkg dependency failure for libc6>=2.34
deb_depends_libc_too_old() {
local v
@@ -176,13 +197,31 @@ verify_bridge_prerequisites() {
}
adjust_ip_forwarding() {
title "Adjusting IP Forwarding"
sed -i '/^net\.ipv4\.ip_forward=/d' /etc/sysctl.conf
sed -i '/^net\.ipv6\.conf\.all\.forwarding=/d' /etc/sysctl.conf
echo "net.ipv4.ip_forward=1" >> /etc/sysctl.conf
echo "net.ipv6.conf.all.forwarding=1" >> /etc/sysctl.conf
sysctl -p /etc/sysctl.conf
ok "IPv4/IPv6 forwarding enabled."
title "Checking IP forwarding"
local v4 v6
v4="$(cat /proc/sys/net/ipv4/ip_forward 2>/dev/null || echo 0)"
v6="$(cat /proc/sys/net/ipv6/conf/all/forwarding 2>/dev/null || echo 0)"
if [[ "$v4" == "1" ]]; then
ok "IPv4 forwarding is enabled."
else
warn "IPv4 forwarding is not enabled."
fi
if [[ "$v6" == "1" ]]; then
ok "IPv6 forwarding is enabled."
else
warn "IPv6 forwarding is not enabled."
fi
if [[ "$v4" != "1" || "$v6" != "1" ]]; then
echo
echo "To enable forwarding and routing consistently, run the network tunnel manager script as root."
echo "For example:"
echo " ./network-tunnel-manager.sh complete_networking_configuration"
echo "or:"
echo " ./network-tunnel-manager.sh adjust_ip_forwarding"
fi
}
# Install nym-bridge
@@ -377,6 +416,11 @@ User=root
ExecStart=$BRIDGE_BIN --config $NYM_ETC_BRIDGES
Restart=on-failure
RestartSec=5
LimitNOFILE=65535
ProtectSystem=full
ProtectHome=yes
PrivateTmp=yes
[Install]
WantedBy=multi-user.target
@@ -390,21 +434,40 @@ EOF
# IPTABLES & helpers
apply_bridge_iptables_rules() {
title "Applying iptables rules"
iptables -I INPUT -i "$WG_IFACE" -j ACCEPT || true
ip6tables -I INPUT -i "$WG_IFACE" -j ACCEPT || true
iptables -t nat -A POSTROUTING -o "$NET_DEV" -j MASQUERADE || true
ip6tables -t nat -A POSTROUTING -o "$NET_DEV" -j MASQUERADE || true
iptables-save > /etc/iptables/rules.v4
ip6tables-save > /etc/iptables/rules.v6
ok "iptables rules applied."
title "Checking iptables rules for bridge routing"
echo "Inspecting current iptables state for interface ${WG_IFACE} and uplink ${NET_DEV}."
echo
echo "IPv4 FORWARD:"
iptables -L FORWARD -n -v 2>/dev/null | sed -n '1,20p' || echo "iptables not available."
echo
echo "IPv4 NAT POSTROUTING:"
iptables -t nat -L POSTROUTING -n -v 2>/dev/null | sed -n '1,20p' || true
echo
echo "IPv6 FORWARD:"
ip6tables -L FORWARD -n -v 2>/dev/null | sed -n '1,20p' || true
echo
echo "IPv6 NAT POSTROUTING:"
ip6tables -t nat -L POSTROUTING -n -v 2>/dev/null | sed -n '1,20p' || true
echo
echo "This script no longer changes iptables. To configure routing and NAT for nym, use the network tunnel manager script."
echo "For example (run as root):"
echo " ./network-tunnel-manager.sh complete_networking_configuration"
}
configure_dns_and_icmp() {
title "Allow ICMP and DNS"
iptables -A INPUT -p icmp --icmp-type echo-request -j ACCEPT || true
ip6tables -A INPUT -p ipv6-icmp -j ACCEPT || true
ok "ICMP and DNS rules applied."
title "Checking ICMP and DNS firewall rules"
echo "IPv4 INPUT rules related to ICMP and DNS:"
iptables -L INPUT -n -v 2>/dev/null | grep -E 'icmp|dpt:53' || echo "no matching IPv4 rules shown."
echo
echo "IPv6 INPUT rules related to ICMP and DNS:"
ip6tables -L INPUT -n -v 2>/dev/null | grep -E 'icmp|dpt:53' || echo "no matching IPv6 rules shown."
echo
echo "If ping or DNS are blocked for bridge traffic, adjust your firewall using the network tunnel manager script or your chosen firewall tool."
}
# Full interactive setup
@@ -429,6 +492,8 @@ full_bridge_setup() {
echo ""
echo "Step 2/6: Installing bridge binary..."
install_bridge_binary
echo "[Bridge Install] $(date '+%F %T') $( $BRIDGE_BIN --version 2>/dev/null || echo 'nym-bridge (unknown)')" \
>> /var/log/nym-bridge-version.log
press_enter "Press Enter to continue..."
echo ""
@@ -447,7 +512,7 @@ full_bridge_setup() {
press_enter "Press Enter to continue..."
echo ""
echo "Step 6/6: Configuring network rules (optional but recommended)..."
echo "Step 6/6: Checking network rules and forwarding status..."
adjust_ip_forwarding
apply_bridge_iptables_rules
configure_dns_and_icmp
-10
View File
@@ -39,16 +39,6 @@ while true; do
esac
done
# try to get the latest binary URL (non-fatal if missing)
LATEST_BINARY=$(
curl -fsSL https://github.com/nymtech/nym/releases/latest \
| grep -Eo 'href="/nymtech/nym/releases/download/[^"]+/nym-node"' \
| head -n1 \
| cut -d'"' -f2
)
if [[ -z "${LATEST_BINARY:-}" ]]; then
echo "WARNING: Could not determine latest nym-node binary URL right now. The installer will resolve it later."
fi
PUBLIC_IP=$(curl -fsS -4 https://ifconfig.me || true)
PUBLIC_IP=${PUBLIC_IP:-""}
+111 -276
View File
@@ -1,315 +1,136 @@
#!/usr/bin/env bash
set -euo pipefail
# load env (prefer absolute ENV_FILE injected by Python CLI; fallback to ./env.sh)
if [[ "$(id -u)" -ne 0 ]]; then
echo "This script must be run as root."
exit 1
fi
# load env
if [[ -n "${ENV_FILE:-}" && -f "${ENV_FILE}" ]]; then
set -a; . "${ENV_FILE}"; set +a
elif [[ -f "./env.sh" ]]; then
set -a; . ./env.sh; set +a
fi
: "${HOSTNAME:?HOSTNAME not set in env.sh}"
: "${EMAIL:?EMAIL not set in env.sh}"
: "${HOSTNAME:?HOSTNAME not set}"
: "${EMAIL:?EMAIL not set}"
export SYSTEMD_PAGER=""
export SYSTEMD_COLORS="0"
DEBIAN_FRONTEND=noninteractive
export DEBIAN_FRONTEND=noninteractive
# sanity check
if [[ "${HOSTNAME}" == "localhost" || "${HOSTNAME}" == "127.0.0.1" || "${HOSTNAME}" == "ubuntu" ]]; then
echo "ERROR: HOSTNAME cannot be 'localhost'. Use a public FQDN." >&2
exit 1
fi
echo -e "\n* * * Starting nginx configuration for landing page, reverse proxy and WSS * * *"
# set paths & ports vars
WEBROOT="/var/www/${HOSTNAME}"
LE_ACME_DIR="/var/www/letsencrypt"
SITES_AVAIL="/etc/nginx/sites-available"
SITES_EN="/etc/nginx/sites-enabled"
BASE_HTTP="${SITES_AVAIL}/${HOSTNAME}" # :80 vhost
BASE_HTTPS="${SITES_AVAIL}/${HOSTNAME}-ssl" # :443 vhost (well write it ourselves)
WSS_AVAIL="${SITES_AVAIL}/wss-config-nym"
BACKUP_DIR="/etc/nginx/sites-backups"
NYM_PORT_HTTP="${NYM_PORT_HTTP:-8080}"
NYM_PORT_WSS="${NYM_PORT_WSS:-9000}"
WSS_LISTEN_PORT="${WSS_LISTEN_PORT:-9001}"
HTTP_CONF="${SITES_AVAIL}/${HOSTNAME}"
WSS_CONF="${SITES_AVAIL}/wss-config-nym"
mkdir -p "${WEBROOT}" "${LE_ACME_DIR}" "${BACKUP_DIR}" "${SITES_AVAIL}" "${SITES_EN}"
echo
echo "* * * Starting nginx configuration for landing page, reverse proxy and WSS * * *"
# helpers
neat_backup() {
local file="$1"; [[ -f "$file" ]] || return 0
local sha_now; sha_now="$(sha256sum "$file" | awk '{print $1}')" || return 0
local tag; tag="$(basename "$file")"
local latest="${BACKUP_DIR}/${tag}.latest"
if [[ -f "$latest" ]]; then
local sha_prev; sha_prev="$(awk '{print $1}' "$latest")"
[[ "$sha_now" == "$sha_prev" ]] && return 0
fi
cp -a "$file" "${BACKUP_DIR}/${tag}.bak.$(date +%s)"
echo "$sha_now ${tag}" > "$latest"
ls -1t "${BACKUP_DIR}/${tag}.bak."* 2>/dev/null | tail -n +6 | xargs -r rm -f
}
###############################################################################
# step 1: ensure landing page exists (local fetch -> github -> template)
###############################################################################
ensure_enabled() {
local src="$1"; local name; name="$(basename "$src")"
ln -sf "$src" "${SITES_EN}/${name}"
}
mkdir -p "${WEBROOT}"
cert_ok() {
[[ -s "/etc/letsencrypt/live/${HOSTNAME}/fullchain.pem" && -s "/etc/letsencrypt/live/${HOSTNAME}/privkey.pem" ]]
}
SCRIPT_DIR="$(dirname "${ENV_FILE:-./env.sh}")"
LOCAL_FETCHED_PAGE="${SCRIPT_DIR}/landing-page.html"
fetch_landing_html() {
local url="https://raw.githubusercontent.com/nymtech/nym/refs/heads/develop/scripts/nym-node-setup/landing-page.html"
mkdir -p "${WEBROOT}"
if command -v curl >/dev/null 2>&1; then
curl -fsSL "$url" -o "${WEBROOT}/index.html" || true
else
wget -qO "${WEBROOT}/index.html" "$url" || true
fi
if [[ ! -s "${WEBROOT}/index.html" ]]; then
cat > "${WEBROOT}/index.html" <<'HTML'
if [[ -s "${LOCAL_FETCHED_PAGE}" ]]; then
cp "${LOCAL_FETCHED_PAGE}" "${WEBROOT}/index.html"
elif curl -fsSL \
https://raw.githubusercontent.com/nymtech/nym/develop/scripts/nym-node-setup/landing-page.html \
-o "${WEBROOT}/index.html"; then
:
else
cat > "${WEBROOT}/index.html" <<EOF
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Nym Exit Gateway</title>
<style>
body {
font-family: sans-serif;
text-align: center;
padding: 2em;
background-color: #111;
color: #0ff;
}
h1 {
margin-bottom: 0.5em;
}
</style>
</head>
<body>
<h1>Nym Exit Gateway</h1>
<p>This is a Nym Exit Gateway. The operator of this router has no access to any of the data routing through that due to encryption design.</p>
<html>
<head><title>nym node</title></head>
<body style="font-family:sans-serif;text-align:center;padding:2em;">
<h1>nym exit gateway</h1>
<p>this is a nym exit gateway.</p>
<p>Operator contact: <a href="mailto:${EMAIL}">${EMAIL}</a></p>
</body>
</html>
HTML
fi
}
EOF
fi
inject_email() {
local file="${WEBROOT}/index.html"
[[ -n "${EMAIL:-}" && -s "$file" ]] || return 0
# Escape characters that would break sed replacement
local esc_email
esc_email="$(printf '%s' "$EMAIL" | sed -e 's/[&/\]/\\&/g')"
# try to update existing meta (case-insensitive on the name attr)
if grep -qiE '<meta[^>]+name=["'"'"']contact:email["'"'"']' "$file"; then
sed -i -E \
"s|(<meta[^>]+name=[\"']contact:email[\"'][^>]*content=\")[^\"]*(\"[^>]*>)|\1${esc_email}\2|I" \
"$file" || true
return 0
fi
# insert before </head> if present (case-insensitive)
if grep -qi '</head>' "$file"; then
awk -v email="$EMAIL" '
BEGIN{IGNORECASE=1}
/<\/head>/ && !done {
print " <meta name=\"contact:email\" content=\"" email "\">"
done=1
}
{ print }
' "$file" > "${file}.tmp" && mv "${file}.tmp" "$file"
return 0
fi
# fallback: append at end
printf '\n<meta name="contact:email" content="%s">\n' "$EMAIL" >> "$file" || true
}
fetch_logo() {
local logo_url="https://raw.githubusercontent.com/nymtech/websites/refs/heads/main/www/nym.com/public/images/Nym_meta_Image.png?token=GHSAT0AAAAAACEERII7URYRTFACZ4F2OWZ42GMCPBQ"
mkdir -p "${WEBROOT}/images"
if [[ ! -s "${WEBROOT}/images/nym_logo.png" ]]; then
if command -v curl >/dev/null 2>&1; then
curl -fsSL "$logo_url" -o "${WEBROOT}/images/nym_logo.png" || true
else
wget -qO "${WEBROOT}/images/nym_logo.png" "$logo_url" || true
fi
fi
}
reload_nginx() { nginx -t && systemctl reload nginx; }
# landing page (idempotent)
fetch_landing_html
inject_email
fetch_logo
echo "Landing page at ${WEBROOT}/index.html"
# disable default and stale SSL configs
###############################################################################
# step 2: remove default site and old configs, restart nginx
###############################################################################
echo "Cleaning existing nginx configuration"
# remove default nginx site
[[ -L "${SITES_EN}/default" ]] && unlink "${SITES_EN}/default" || true
for f in "${SITES_EN}"/*; do
[[ -L "$f" ]] || continue
if grep -q "/etc/letsencrypt/live/localhost" "$f"; then
echo "Disabling vhost referencing localhost cert: $f"; unlink "$f"
fi
done
for f in "${SITES_EN}"/*; do
[[ -L "$f" ]] || continue
if grep -qE 'listen\s+.*443' "$f"; then
cert=$(awk '/ssl_certificate[ \t]+/ {print $2}' "$f" | tr -d ';' | head -n1)
key=$(awk '/ssl_certificate_key[ \t]+/ {print $2}' "$f" | tr -d ';' | head -n1)
if [[ -n "${cert:-}" && ! -s "$cert" ]] || [[ -n "${key:-}" && ! -s "$key" ]]; then
echo "Disabling SSL vhost with missing cert/key: $f"; unlink "$f"
fi
fi
done
# HTTP :80 vhost (ACME-safe, proxy to :8080)
neat_backup "${BASE_HTTP}"
cat > "${BASE_HTTP}" <<EOF
# optional: remove default available config if present
rm -f /etc/nginx/sites-available/default || true
# remove old vhosts for this domain
rm -f "${SITES_EN}/${HOSTNAME}" || true
rm -f "${SITES_EN}/${HOSTNAME}-ssl" || true
rm -f "${SITES_EN}/wss-config-nym" || true
rm -f "${HTTP_CONF}" || true
rm -f "${WSS_CONF}" || true
systemctl restart nginx || systemctl start nginx
###############################################################################
# step 3: create basic HTTP config like manual flow (80 -> 8080)
###############################################################################
cat > "${HTTP_CONF}" <<EOF
server {
listen 80;
listen [::]:80;
server_name ${HOSTNAME};
# ACME challenge path (HTTP only)
location ^~ /.well-known/acme-challenge/ {
root ${LE_ACME_DIR};
default_type "text/plain";
}
root ${WEBROOT};
index index.html;
location = /favicon.ico { return 204; access_log off; log_not_found off; }
location / {
try_files \$uri \$uri/ @app;
}
location @app {
proxy_pass http://127.0.0.1:${NYM_PORT_HTTP};
proxy_pass http://127.0.0.1:8080;
proxy_set_header X-Real-IP \$remote_addr;
proxy_set_header Host \$host;
proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
}
}
EOF
ensure_enabled "${BASE_HTTP}"
reload_nginx
systemctl status nginx --no-pager | sed -n '1,6p' || true
# ACME preflight (informative)
echo -e "\n* * * ACME preflight checks * * *"
if ! curl -fsSL https://acme-v02.api.letsencrypt.org/directory >/dev/null; then
echo "WARNING: Can't reach Let's Encrypt directory. We'll still keep HTTP up." >&2
fi
THIS_IP="$(curl -fsS -4 https://ifconfig.me || true)"
DNS_IP="$(getent ahostsv4 "${HOSTNAME}" 2>/dev/null | awk '{print $1; exit}')"
echo "Public IPv4: ${THIS_IP:-unknown} DNS A(${HOSTNAME}): ${DNS_IP:-unresolved}"
if [[ -n "${THIS_IP:-}" && -n "${DNS_IP:-}" && "${THIS_IP}" != "${DNS_IP}" ]]; then
echo "WARNING: DNS for ${HOSTNAME} does not match this server's public IPv4."
fi
timedatectl show -p NTPSynchronized --value 2>/dev/null | grep -qi yes || timedatectl set-ntp true || true
ln -sf "${HTTP_CONF}" "${SITES_EN}/${HOSTNAME}"
# install certbot if missing
if ! command -v certbot >/dev/null 2>&1; then
if command -v snap >/dev/null 2>&1; then
snap install core || true; snap refresh core || true
snap install --classic certbot; ln -sf /snap/bin/certbot /usr/bin/certbot
else
apt-get update -y >/dev/null 2>&1 || true
apt-get install -y certbot >/dev/null 2>&1 || true
fi
fi
nginx -t
systemctl daemon-reload
systemctl restart nginx
# issue/renew via WEBROOT (no nginx auto-edit), non-fatal if it fails
STAGING_FLAG=""; [[ "${CERTBOT_STAGING:-0}" == "1" ]] && STAGING_FLAG="--staging" && echo "Using Let's Encrypt STAGING."
if ! cert_ok; then
certbot certonly --non-interactive --agree-tos -m "${EMAIL}" -d "${HOSTNAME}" \
--webroot -w "${LE_ACME_DIR}" ${STAGING_FLAG} || true
fi
###############################################################################
# step 4: install certbot and obtain certificate (letsencrypt)
###############################################################################
# create own 443 vhost (only if certs exist)
if cert_ok; then
neat_backup "${BASE_HTTPS}"
cat > "${BASE_HTTPS}" <<EOF
apt-get update -y >/dev/null 2>&1 || true
apt-get install -y certbot python3-certbot-nginx >/dev/null 2>&1 || true
echo "Requesting Let's Encrypt certificate for ${HOSTNAME}"
certbot --nginx --non-interactive --agree-tos --redirect --reuse-key \
-m "${EMAIL}" -d "${HOSTNAME}" || true
###############################################################################
# step 5: create WSS 9001 config using certbot-generated certs
###############################################################################
if [[ -s "/etc/letsencrypt/live/${HOSTNAME}/fullchain.pem" ]]; then
echo "Certificate detected, creating WSS config"
cat > "${WSS_CONF}" <<EOF
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name ${HOSTNAME};
listen 9001 ssl http2;
listen [::]:9001 ssl http2;
ssl_certificate /etc/letsencrypt/live/${HOSTNAME}/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/${HOSTNAME}/privkey.pem;
include /etc/letsencrypt/options-ssl-nginx.conf;
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
root ${WEBROOT};
index index.html;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
location = /favicon.ico { return 204; access_log off; log_not_found off; }
location / {
try_files \$uri \$uri/ @app;
}
location @app {
proxy_pass http://127.0.0.1:${NYM_PORT_HTTP};
proxy_http_version 1.1;
proxy_set_header X-Real-IP \$remote_addr;
proxy_set_header Host \$host;
proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
}
}
EOF
ensure_enabled "${BASE_HTTPS}"
# optional: redirect HTTP->HTTPS (keeps ACME path in HTTP too via separate small server)
neat_backup "${BASE_HTTP}"
cat > "${BASE_HTTP}" <<EOF
server {
listen 80;
listen [::]:80;
server_name ${HOSTNAME};
# Keep ACME reachable over HTTP:
location ^~ /.well-known/acme-challenge/ {
root ${LE_ACME_DIR};
default_type "text/plain";
}
# Redirect the rest to HTTPS
location / {
return 301 https://\$host\$request_uri;
}
}
EOF
ensure_enabled "${BASE_HTTP}"
reload_nginx
else
echo "NOTE: Cert not present yet; HTTPS (443) will not listen. Only HTTP (80) is active."
fi
# WSS TLS :9001 (only if certs exist)
if cert_ok; then
neat_backup "${WSS_AVAIL}"
cat > "${WSS_AVAIL}" <<EOF
server {
listen ${WSS_LISTEN_PORT} ssl http2;
listen [::]:${WSS_LISTEN_PORT} ssl http2;
server_name ${HOSTNAME};
ssl_certificate /etc/letsencrypt/live/${HOSTNAME}/fullchain.pem;
@@ -320,7 +141,11 @@ server {
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
location = /favicon.ico { return 204; access_log off; log_not_found off; }
location /favicon.ico {
return 204;
access_log off;
log_not_found off;
}
location / {
add_header 'Access-Control-Allow-Origin' '*' always;
@@ -333,20 +158,30 @@ server {
proxy_set_header Connection "Upgrade";
proxy_set_header X-Forwarded-For \$remote_addr;
proxy_pass http://127.0.0.1:${NYM_PORT_WSS};
proxy_pass http://localhost:9000;
proxy_intercept_errors on;
}
}
EOF
ensure_enabled "${WSS_AVAIL}"
reload_nginx
ln -sf "${WSS_CONF}" "${SITES_EN}/wss-config-nym"
nginx -t
systemctl daemon-reload
systemctl restart nginx
else
echo "Certificate missing, skipping WSS config"
fi
echo -e "\nDone."
if cert_ok; then
echo "HTTP : http://${HOSTNAME}/ (redirects to HTTPS)"
echo "TLS : https://${HOSTNAME}/ (served by nginx)"
echo "WSS : wss://${HOSTNAME}:${WSS_LISTEN_PORT}/ (served by nginx)"
###############################################################################
# step 6: summary
###############################################################################
echo "done."
echo "http : http://${HOSTNAME}"
if [[ -s "/etc/letsencrypt/live/${HOSTNAME}/fullchain.pem" ]]; then
echo "https : https://${HOSTNAME}"
echo "wss : wss://${HOSTNAME}:9001"
else
echo "Only HTTP is active (no cert yet). Re-run after DNS/ACME is ready to enable HTTPS + WSS."
echo "https not active yet (no cert)"
fi
@@ -83,8 +83,8 @@ fi
# interactive path (manual runs)
ensure_mode
read -rp "Service file not found. Create it now? (y/n): " create_ans
if [[ "${create_ans:-}" =~ ^[Yy]$ ]]; then
read -rp "Service file not found. Create it now? (Y/n): " create_ans
if [[ -z "${create_ans}" || "${create_ans}" =~ ^[Yy]$ ]]; then
create_service_file
else
echo "Not creating the service file."
@@ -1,240 +0,0 @@
#!/bin/bash
# Nym Exit Policy Verification Unit Tests
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[0;33m'
NC='\033[0m'
NYM_CHAIN="NYM-EXIT"
WG_INTERFACE="nymwg"
check_port_range_rules() {
local port_range="$1"
local protocol="${2:-tcp}"
local chain="${3:-$NYM_CHAIN}"
# Extract start and end ports
local start_port=$(echo "$port_range" | cut -d'-' -f1)
local end_port=$(echo "$port_range" | cut -d'-' -f2)
if iptables -t filter -C "$chain" -p "$protocol" --dport "$start_port:$end_port" -j ACCEPT 2>/dev/null; then
echo -e "${GREEN}✓ Rule exists: $chain $protocol port range $start_port:$end_port${NC}"
return 0
else
echo -e "${RED}✗ Rule missing: $chain $protocol port range $start_port:$end_port${NC}"
echo -e "${YELLOW}Dumping all rules in $chain:${NC}"
iptables -L "$chain" -n | grep "$protocol"
return 1
fi
}
# Test port range rules
test_port_range_rules() {
echo -e "${YELLOW}Testing Port Range Rules...${NC}"
# Select the essential port ranges for testing
local port_ranges=(
"20-21:tcp:FTP"
"80-81:tcp:HTTP"
"2082-2083:tcp:CPanel"
"5222-5223:tcp:XMPP"
"27000-27050:tcp:Steam (sampling)"
"989-990:tcp:FTP over TLS"
"5000-5005:tcp:RTP/VoIP"
"8087-8088:tcp:Simplify Media"
"8232-8233:tcp:Zcash"
"8332-8333:tcp:Bitcoin"
"18080-18081:tcp:Monero"
)
local total_failures=0
for range in "${port_ranges[@]}"; do
IFS=':' read -r port_range protocol service <<< "$range"
# Extract start and end ports
local start_port=$(echo "$port_range" | cut -d'-' -f1)
local end_port=$(echo "$port_range" | cut -d'-' -f2)
echo -e "${YELLOW}Testing $service $protocol port range $port_range${NC}"
if iptables -t filter -C "$NYM_CHAIN" -p "$protocol" --dport "$start_port:$end_port" -j ACCEPT 2>/dev/null; then
echo -e "${GREEN}✓ Rule exists: $NYM_CHAIN $protocol port range $start_port:$end_port${NC}"
else
echo -e "${RED}✗ Rule missing: $NYM_CHAIN $protocol port range $start_port:$end_port${NC}"
((total_failures++))
echo -e "${YELLOW}Existing rules for protocol $protocol:${NC}"
iptables -L "$NYM_CHAIN" -n | grep "$protocol"
fi
done
if [ $total_failures -eq 0 ]; then
return 0
else
return 1
fi
}
test_critical_services() {
echo -e "${YELLOW}Testing Critical Service Rules...${NC}"
local tcp_services=(
22 # SSH
53 # DNS
443 # HTTPS
853 # DNS over TLS
1194 # OpenVPN
)
local udp_services=(
53 # DNS
123 # NTP
1194 # OpenVPN
)
local failures=0
# Test TCP services
for port in "${tcp_services[@]}"; do
local rule_found=false
# First check for exact match
if iptables -t filter -C "$NYM_CHAIN" -p tcp --dport "$port" -j ACCEPT 2>/dev/null; then
echo -e "${GREEN}✓ Rule exists: NYM-EXIT tcp port $port${NC}"
rule_found=true
else
# If not found as exact port, search for it in port ranges
# This checks if the port is covered by any range rule
if iptables-save | grep -E "^-A $NYM_CHAIN.*tcp.*dpts:" | grep -qP "dpts:(\d+:)?$port(:|\d+)" || \
iptables-save | grep -E "^-A $NYM_CHAIN.*tcp.*dpts:" | grep -qP "dpts:$port:"; then
echo -e "${GREEN}✓ Rule exists: NYM-EXIT tcp port $port (covered by a range rule)${NC}"
rule_found=true
else
echo -e "${RED}✗ Rule missing: NYM-EXIT tcp port $port${NC}"
((failures++))
fi
fi
done
# Test UDP services - similar approach
for port in "${udp_services[@]}"; do
local rule_found=false
if iptables -t filter -C "$NYM_CHAIN" -p udp --dport "$port" -j ACCEPT 2>/dev/null; then
echo -e "${GREEN}✓ Rule exists: NYM-EXIT udp port $port${NC}"
rule_found=true
else
# If not found as exact port, search for it in port ranges
if iptables-save | grep -E "^-A $NYM_CHAIN.*udp.*dpts:" | grep -qP "dpts:(\d+:)?$port(:|\d+)" || \
iptables-save | grep -E "^-A $NYM_CHAIN.*udp.*dpts:" | grep -qP "dpts:$port:"; then
echo -e "${GREEN}✓ Rule exists: NYM-EXIT udp port $port (covered by a range rule)${NC}"
rule_found=true
else
echo -e "${RED}✗ Rule missing: NYM-EXIT udp port $port${NC}"
((failures++))
fi
fi
done
echo -e "${YELLOW}Relevant existing rules for HTTP (port 80):${NC}"
iptables-save | grep -E "$NYM_CHAIN.*tcp" | grep -E "(dpt|dpts):.*80"
return $failures
}
# Verify default reject rule exists
test_default_reject_rule() {
echo -e "${YELLOW}This test takes some time, do not quit the process${NC}"
echo
echo -e "${YELLOW}Testing Default Reject Rule...${NC}"
# Try different patterns to detect the reject rule
if iptables -L "$NYM_CHAIN" | grep -q "REJECT.*all.*anywhere.*anywhere.*reject-with"; then
echo -e "${GREEN}✓ Default REJECT rule exists${NC}"
return 0
elif iptables -L "$NYM_CHAIN" | grep -q "REJECT.*all -- .*everywhere.*everywhere"; then
echo -e "${GREEN}✓ Default REJECT rule exists${NC}"
return 0
elif iptables -L "$NYM_CHAIN" | grep -q "REJECT.*all.*0.0.0.0/0.*0.0.0.0/0"; then
echo -e "${GREEN}✓ Default REJECT rule exists${NC}"
return 0
elif iptables -n -L "$NYM_CHAIN" | grep -qE "REJECT.*all.*0.0.0.0/0.*0.0.0.0/0"; then
echo -e "${GREEN}✓ Default REJECT rule exists${NC}"
return 0
elif iptables -L "$NYM_CHAIN" | tail -1 | grep -q "REJECT"; then
echo -e "${GREEN}✓ Default REJECT rule exists at the end of chain${NC}"
return 0
else
echo -e "${RED}✗ Default REJECT rule missing${NC}"
# Display the last 3 rules in the chain for debugging
echo -e "${YELLOW}Last 3 rules in the chain:${NC}"
iptables -L "$NYM_CHAIN" | tail -3
return 1
fi
}
run_all_tests() {
local total_failures=0
local total_tests=0
local skip_default_reject=false
# Parse arguments
while [[ $# -gt 0 ]]; do
case "$1" in
--skip-default-reject)
skip_default_reject=true
shift
;;
*)
echo -e "${RED}Unknown argument: $1${NC}"
exit 1
;;
esac
done
local test_functions=(
"test_port_range_rules"
"test_critical_services"
)
if [ "$skip_default_reject" = false ]; then
test_functions+=("test_default_reject_rule")
fi
echo -e "${YELLOW}Running Nym Exit Policy Verification Tests...${NC}"
for test_func in "${test_functions[@]}"; do
((total_tests++))
$test_func
if [ $? -ne 0 ]; then
((total_failures++))
echo -e "${RED}Test $test_func FAILED${NC}"
else
echo -e "${GREEN}Test $test_func PASSED${NC}"
fi
done
echo -e "\n${YELLOW}Test Summary:${NC}"
echo -e "Total Tests: $total_tests"
echo -e "Failures: $total_failures"
if [ $total_failures -eq 0 ]; then
echo -e "${GREEN}All Tests Passed Successfully!${NC}"
exit 0
else
echo -e "${RED}Some Tests Failed. Please review the iptables configuration.${NC}"
exit 1
fi
}
if [[ $EUID -ne 0 ]]; then
echo -e "${RED}This script must be run as root${NC}"
exit 1
fi
# Run the tests
run_all_tests "$@"
@@ -1,40 +0,0 @@
#!/bin/bash
validate_exit_policy() {
echo "=== Nym Exit Policy Blocking Validation ==="
# Check iptables rules
echo "Checking iptables NYM-EXIT chain:"
sudo iptables -L NYM-EXIT -v -n
# Test IP ranges and individual IPs
test_ips=(
"5.188.10.0/24" # Blocked network range
"31.132.36.50" # Specific blocked IP
"37.9.42.100" # Another blocked IP
)
for target in "${test_ips[@]}"; do
echo -e "\n\e[33mTesting blocking for $target\e[0m"
# Multiple connection test methods
methods=(
"ping -c 4 -W 2"
"curl -m 5 http://$target"
"nc -z -w 5 $target 80"
"telnet $target 80"
)
for method in "${methods[@]}"; do
echo -n "Testing with $method: "
if sudo timeout 5 $method >/dev/null 2>&1; then
echo -e "\e[31mFAILED: Connection succeeded (Blocking ineffective)\e[0m"
else
echo -e "\e[32mBLOCKED\e[0m"
fi
done
done
}
# Run the test
validate_exit_policy

Some files were not shown because too many files have changed in this diff Show More