Compare commits

..

3 Commits

Author SHA1 Message Date
Zoltán Papp
ccb271b5bb [client] Make netbird up wait for the daemon to become ready
The CLI up path only tolerated a not-yet-ready daemon via a 10s blocking
dial, so "netbird service start" immediately followed by "netbird up"
(e.g. a container entrypoint) failed with a generic "daemon not running"
error. The container entrypoint worked around this with a shell poll loop
(status --check live) before running up.

Move the readiness wait into the CLI, mirroring how the GUI already dials:

- DialClientGRPCServer now uses grpc.NewClient with a tuned reconnect
  backoff and waits for the connection to reach READY (retrying on
  TRANSIENT_FAILURE) up to a 30s deadline, instead of grpc.DialContext +
  WithBlock with a hard 10s timeout.
- up now polls Status via waitForDaemonStatus, retrying while the RPC is
  Unavailable (socket up but service not yet registered).

Add an explicit daemon-ready signal so clients can wait deterministically
instead of heuristically:

- New optional StatusResponse.daemonReady field (field 5, wire-compatible
  with older GUIs/daemons which leave it unset). Regenerated with the
  pinned protoc v33.1 toolchain so no version churn leaks into the diff.
- The server sets ready once Start succeeds and the DaemonService is
  registered (SetReady, called from the service controller).
- waitForDaemonStatus waits for daemonReady=true (or an already-Connected
  status), with a bounded grace window so older daemons that never set the
  field are not blocked.

Simplify the container entrypoint accordingly: drop the readiness poll
loop (up now waits) and the now-dead NB_ENTRYPOINT_SERVICE_TIMEOUT env,
keeping only the daemon+up process glue and SIGTERM forwarding for clean
shutdown.
2026-07-17 10:30:09 +02:00
Zoltan Papp
d15830a2d0 [client] Sync 0.74.6 fix/ios-relogin (#6795)
## sync 0.74.6 fix/ios-relogin

NewAuth built a fresh in-memory config on every call via
CreateInMemoryConfig, which generates a new WireGuard private key when
none is set. The iOS Swift layer calls this on interactive re-login and
writes the resulting config back to the profile's netbird.cfg, so each
re-auth replaced the peer's persisted private key with a new one. A new
key means a new public key, so the management server registered a
brand-new peer on every re-authentication — named after the fallback
hostname.

Load the existing config with DirectUpdateOrCreateConfig when a config
file is already present so re-login reuses the peer's persisted private
key (and its identity). Only fall back to a fresh in-memory config for
the first-time login when no config file exists yet (or after logout,
which deletes the file). DirectUpdateOrCreateConfig uses non-atomic
writes so it also works inside the tvOS App Group sandbox. This matches
what Run() and LoginForMobile() already do.

## Describe your changes

## Issue ticket number and link

## Stack

<!-- branch-stack -->

### Checklist
- [x] Is it a bug fix
- [ ] Is a typo/documentation fix
- [ ] Is a feature enhancement
- [ ] It is a refactor
- [ ] Created tests that fail without the change (if possible)
- [ ] This change does **not** modify the public API, gRPC protocols,
functionality behavior, CLI / service flags, or introduce a new feature
— **OR** I have discussed it with the NetBird team beforehand (link the
issue / Slack thread in the description). See

[CONTRIBUTING.md](https://github.com/netbirdio/netbird/blob/main/CONTRIBUTING.md#discuss-changes-with-the-netbird-team-first).

> By submitting this pull request, you confirm that you have read and
agree to the terms of the [Contributor License

Agreement](https://github.com/netbirdio/netbird/blob/main/CONTRIBUTOR_LICENSE_AGREEMENT.md).

## Documentation
Select exactly one:

- [ ] I added/updated documentation for this change
- [x] Documentation is **not needed** for this change (explain why)

### Docs PR URL (required if "docs added" is checked) Paste the PR link
from https://github.com/netbirdio/docs here:

https://github.com/netbirdio/docs/pull/__

<!-- codesmith:footer -->
---
<a
href="https://app.blacksmith.sh/netbirdio/codesmith/netbird/pr/6795"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://pr-comments-assets.blacksmith.sh/codesmith/view-with-codesmith-dark-v2.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://pr-comments-assets.blacksmith.sh/codesmith/view-with-codesmith-light-v2.svg"><img
alt="View with Codesmith"
src="https://pr-comments-assets.blacksmith.sh/codesmith/view-with-codesmith-dark-v2.svg"></picture></a>
<a
href="https://backend.blacksmith.sh/track/enable-autofix?expires=1786784867&installation_id=146802194&pr_number=6795&repository=netbirdio%2Fnetbird&return_to=https%3A%2F%2Fgithub.com%2Fnetbirdio%2Fnetbird%2Fpull%2F6795&signature=01bd94ea58128257c33f4d430ab3b71ce21eac02577ce90c009105b8c0027d9c"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://pr-comments-assets.blacksmith.sh/codesmith/autofix-with-codesmith-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://pr-comments-assets.blacksmith.sh/codesmith/autofix-with-codesmith-light.svg"><img
alt="Autofix with Codesmith"
src="https://pr-comments-assets.blacksmith.sh/codesmith/autofix-with-codesmith-dark.svg"></picture></a>
<sup>Need help on this PR? Tag <code>/codesmith</code> with what you
need. Autofix is disabled.</sup>

<!-- codesmith:autofix:disabled -->
<!-- /codesmith:footer -->

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

- **Bug Fixes**
- Improved iOS login handling when a configuration location is provided.
- Existing WireGuard keys can now be reused across subsequent logins,
helping avoid unnecessary key regeneration.
- Login continues to support temporary in-memory configuration when no
persistent location is available.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-07-16 14:38:01 +02:00
Zoltan Papp
141f3d0390 [client] Fix DNS probe listener impossible panic on unparseable local address (#6797)
generateFreePort used netip.MustParseAddrPort on the OS-produced
LocalAddr().String(), which panics on address strings that don't parse.
Eliminate the parsing entirely by reading the port from the concrete
*net.UDPAddr that net.ListenUDP returns, and construct the bind address
directly. The probe listener is bound with udp4 so only an IPv4 wildcard
address is ever used.

## Describe your changes

## Issue ticket number and link

## Stack

<!-- branch-stack -->

### Checklist
- [x] Is it a bug fix
- [ ] Is a typo/documentation fix
- [ ] Is a feature enhancement
- [ ] It is a refactor
- [ ] Created tests that fail without the change (if possible)
- [ ] This change does **not** modify the public API, gRPC protocols,
functionality behavior, CLI / service flags, or introduce a new feature
— **OR** I have discussed it with the NetBird team beforehand (link the
issue / Slack thread in the description). See
[CONTRIBUTING.md](https://github.com/netbirdio/netbird/blob/main/CONTRIBUTING.md#discuss-changes-with-the-netbird-team-first).

> By submitting this pull request, you confirm that you have read and
agree to the terms of the [Contributor License
Agreement](https://github.com/netbirdio/netbird/blob/main/CONTRIBUTOR_LICENSE_AGREEMENT.md).

## Documentation
Select exactly one:

- [ ] I added/updated documentation for this change
- [x] Documentation is **not needed** for this change (explain why)

### Docs PR URL (required if "docs added" is checked)
Paste the PR link from https://github.com/netbirdio/docs here:

https://github.com/netbirdio/docs/pull/__


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

## Summary by CodeRabbit

* **Bug Fixes**
  * Improved reliability when selecting an ephemeral UDP port.
  * Avoided potential failures when determining the assigned port.
* Preserved existing error handling and diagnostic logging for listener
operations.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-07-16 14:37:27 +02:00
26 changed files with 439 additions and 640 deletions

View File

@@ -17,8 +17,7 @@ ENV \
NETBIRD_BIN="/usr/local/bin/netbird" \
NB_LOG_FILE="console,/var/log/netbird/client.log" \
NB_DAEMON_ADDR="unix:///var/run/netbird.sock" \
NB_ENABLE_CAPTURE="false" \
NB_ENTRYPOINT_SERVICE_TIMEOUT="30"
NB_ENABLE_CAPTURE="false"
ENTRYPOINT [ "/usr/local/bin/netbird-entrypoint.sh" ]
ARG TARGETPLATFORM

View File

@@ -23,8 +23,7 @@ ENV \
NB_DAEMON_ADDR="unix:///var/lib/netbird/netbird.sock" \
NB_LOG_FILE="console,/var/lib/netbird/client.log" \
NB_DISABLE_DNS="true" \
NB_ENABLE_CAPTURE="false" \
NB_ENTRYPOINT_SERVICE_TIMEOUT="30"
NB_ENABLE_CAPTURE="false"
ENTRYPOINT [ "/usr/local/bin/netbird-entrypoint.sh" ]
ARG TARGETPLATFORM

176
client/cmd/dial_test.go Normal file
View File

@@ -0,0 +1,176 @@
package cmd
import (
"context"
"net"
"path/filepath"
"sync/atomic"
"testing"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/connectivity"
"github.com/netbirdio/netbird/client/internal"
"github.com/netbirdio/netbird/client/proto"
)
// startUnixGRPCServer starts a bare gRPC server listening on a unix socket at path
// and returns a stop function. No services are registered; the connectivity-state
// wait only cares about the transport becoming READY.
func startUnixGRPCServer(t *testing.T, path string) func() {
t.Helper()
lis, err := net.Listen("unix", path)
if err != nil {
t.Fatalf("listen unix %s: %v", path, err)
}
srv := grpc.NewServer()
go func() { _ = srv.Serve(lis) }()
return srv.Stop
}
func TestDialClientGRPCServer_ConnectsWhenServing(t *testing.T) {
sock := filepath.Join(t.TempDir(), "nb.sock")
stop := startUnixGRPCServer(t, sock)
defer stop()
conn, err := dialClientGRPCServer(context.Background(), "unix://"+sock, 5*time.Second)
if err != nil {
t.Fatalf("expected connection, got error: %v", err)
}
defer conn.Close()
if state := conn.GetState(); state != connectivity.Ready {
t.Fatalf("expected READY, got %s", state)
}
}
// TestDialClientGRPCServer_WaitsForLateServer is the core regression test: the
// daemon socket appears only after the dial has already started, mirroring
// "netbird service start" immediately followed by "netbird up".
func TestDialClientGRPCServer_WaitsForLateServer(t *testing.T) {
sock := filepath.Join(t.TempDir(), "nb.sock")
var stop func()
timer := time.AfterFunc(1*time.Second, func() {
stop = startUnixGRPCServer(t, sock)
})
defer timer.Stop()
defer func() {
if stop != nil {
stop()
}
}()
start := time.Now()
conn, err := dialClientGRPCServer(context.Background(), "unix://"+sock, 10*time.Second)
if err != nil {
t.Fatalf("expected connection after late server start, got error: %v", err)
}
defer conn.Close()
if elapsed := time.Since(start); elapsed < 500*time.Millisecond {
t.Fatalf("connected too fast (%s); server should not have been up yet", elapsed)
}
if state := conn.GetState(); state != connectivity.Ready {
t.Fatalf("expected READY, got %s", state)
}
}
// fakeStatusServer serves the Status RPC with a programmable response so we can
// exercise waitForDaemonStatus without spinning up a real engine.
type fakeStatusServer struct {
proto.UnimplementedDaemonServiceServer
resp func() *proto.StatusResponse
}
func (f *fakeStatusServer) Status(context.Context, *proto.StatusRequest) (*proto.StatusResponse, error) {
return f.resp(), nil
}
func startFakeStatusServer(t *testing.T, sock string, resp func() *proto.StatusResponse) func() {
t.Helper()
lis, err := net.Listen("unix", sock)
if err != nil {
t.Fatalf("listen unix %s: %v", sock, err)
}
srv := grpc.NewServer()
proto.RegisterDaemonServiceServer(srv, &fakeStatusServer{resp: resp})
go func() { _ = srv.Serve(lis) }()
return srv.Stop
}
func dialFake(t *testing.T, sock string) proto.DaemonServiceClient {
t.Helper()
conn, err := dialClientGRPCServer(context.Background(), "unix://"+sock, 5*time.Second)
if err != nil {
t.Fatalf("dial fake daemon: %v", err)
}
t.Cleanup(func() { conn.Close() })
return proto.NewDaemonServiceClient(conn)
}
// New daemon that flips DaemonReady=true after a couple of polls: waitForDaemonStatus
// must block until the flag is set, then return.
func TestWaitForDaemonStatus_WaitsForDaemonReady(t *testing.T) {
sock := filepath.Join(t.TempDir(), "nb.sock")
var polls int32
stop := startFakeStatusServer(t, sock, func() *proto.StatusResponse {
n := atomic.AddInt32(&polls, 1)
return &proto.StatusResponse{
Status: string(internal.StatusConnecting),
DaemonReady: n >= 3, // ready only from the 3rd poll on
}
})
defer stop()
client := dialFake(t, sock)
status, err := waitForDaemonStatus(context.Background(), client)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if !status.GetDaemonReady() {
t.Fatalf("expected DaemonReady=true, got false")
}
if got := atomic.LoadInt32(&polls); got < 3 {
t.Fatalf("expected at least 3 polls before ready, got %d", got)
}
}
// Older daemon that never sets DaemonReady but reports a healthy (Connected)
// status: waitForDaemonStatus must return promptly via the readiness fallback,
// not block for the whole grace window.
func TestWaitForDaemonStatus_OlderDaemonHealthyStatus(t *testing.T) {
sock := filepath.Join(t.TempDir(), "nb.sock")
stop := startFakeStatusServer(t, sock, func() *proto.StatusResponse {
return &proto.StatusResponse{Status: string(internal.StatusConnected)} // DaemonReady unset
})
defer stop()
client := dialFake(t, sock)
start := time.Now()
status, err := waitForDaemonStatus(context.Background(), client)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if status.GetDaemonReady() {
t.Fatalf("expected DaemonReady=false from older daemon")
}
if elapsed := time.Since(start); elapsed > 2*time.Second {
t.Fatalf("returned too slowly (%s); healthy status should short-circuit the grace", elapsed)
}
}
func TestDialClientGRPCServer_TimesOutWhenAbsent(t *testing.T) {
sock := filepath.Join(t.TempDir(), "never.sock")
start := time.Now()
conn, err := dialClientGRPCServer(context.Background(), "unix://"+sock, 1*time.Second)
if err == nil {
conn.Close()
t.Fatal("expected timeout error, got nil")
}
if elapsed := time.Since(start); elapsed < 900*time.Millisecond {
t.Fatalf("returned too early (%s); should have waited ~timeout", elapsed)
}
}

View File

@@ -20,6 +20,8 @@ import (
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"google.golang.org/grpc"
gbackoff "google.golang.org/grpc/backoff"
"google.golang.org/grpc/connectivity"
"google.golang.org/grpc/credentials/insecure"
daddr "github.com/netbirdio/netbird/client/internal/daemonaddr"
@@ -264,17 +266,70 @@ func FlagNameToEnvVar(cmdFlag string, prefix string) string {
return prefix + upper
}
// DialClientGRPCServer returns client connection to the daemon server.
func DialClientGRPCServer(ctx context.Context, addr string) (*grpc.ClientConn, error) {
ctx, cancel := context.WithTimeout(ctx, time.Second*10)
defer cancel()
// defaultDaemonDialTimeout is how long DialClientGRPCServer waits for the daemon
// to become reachable. It is intentionally generous so that invoking the CLI
// right after "netbird service start" (e.g. from a container entrypoint) tolerates
// the window where the daemon has created its socket but is not yet serving.
const defaultDaemonDialTimeout = 30 * time.Second
return grpc.DialContext(
ctx,
// DialClientGRPCServer returns a client connection to the daemon server. It waits
// for the daemon to become reachable, retrying with backoff until the connection
// reports READY or defaultDaemonDialTimeout elapses. This handles the startup race
// where the daemon socket exists (or is about to) before the gRPC server is serving.
func DialClientGRPCServer(ctx context.Context, addr string) (*grpc.ClientConn, error) {
return dialClientGRPCServer(ctx, addr, defaultDaemonDialTimeout)
}
func dialClientGRPCServer(ctx context.Context, addr string, timeout time.Duration) (*grpc.ClientConn, error) {
conn, err := grpc.NewClient(
strings.TrimPrefix(addr, "tcp://"),
grpc.WithTransportCredentials(insecure.NewCredentials()),
grpc.WithBlock(),
// Cap reconnect backoff at 5s; gRPC's default 120s MaxDelay would leave the
// CLI waiting far too long to notice a freshly-started daemon. Mirrors the GUI.
grpc.WithConnectParams(grpc.ConnectParams{
Backoff: gbackoff.Config{
BaseDelay: 1 * time.Second,
Multiplier: 1.6,
Jitter: 0.2,
MaxDelay: 5 * time.Second,
},
}),
)
if err != nil {
return nil, fmt.Errorf("create daemon gRPC client: %w", err)
}
// grpc.NewClient is lazy: it does not connect until the first RPC or until we
// nudge it. Trigger connection attempts and wait until the channel reaches READY.
if err := waitForConnReady(ctx, conn, timeout); err != nil {
_ = conn.Close()
return nil, err
}
return conn, nil
}
// waitForConnReady drives the gRPC channel out of IDLE and blocks until it becomes
// READY, or until timeout/ctx expires. TRANSIENT_FAILURE (daemon not yet serving)
// is treated as retryable so the caller keeps waiting within the deadline.
func waitForConnReady(ctx context.Context, conn *grpc.ClientConn, timeout time.Duration) error {
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
for {
state := conn.GetState()
switch state {
case connectivity.Ready:
return nil
case connectivity.Idle:
// Kick the lazy channel into connecting.
conn.Connect()
}
if !conn.WaitForStateChange(ctx, state) {
// ctx expired while in `state`.
return fmt.Errorf("timed out after %s waiting for daemon to become ready (last state: %s)", timeout, state)
}
}
}
// WithBackOff execute function in backoff cycle.

View File

@@ -78,6 +78,10 @@ func (p *program) Start(svc service.Service) error {
log.Fatalf("failed to start daemon: %v", err)
}
proto.RegisterDaemonServiceServer(p.serv, serverInstance)
// The engine is started and the service is registered: from here on the
// daemon serves RPCs backed by a running engine. Report readiness so
// clients (e.g. netbird up) can wait deterministically.
serverInstance.SetReady()
p.serverInstanceMu.Lock()
p.serverInstance = serverInstance

View File

@@ -295,9 +295,7 @@ func runInDaemonMode(ctx context.Context, cmd *cobra.Command, pm *profilemanager
client := proto.NewDaemonServiceClient(conn)
status, err := client.Status(ctx, &proto.StatusRequest{
WaitForReady: func() *bool { b := true; return &b }(),
})
status, err := waitForDaemonStatus(ctx, client)
if err != nil {
return fmt.Errorf("unable to get daemon status: %v", err)
}
@@ -336,6 +334,79 @@ func runInDaemonMode(ctx context.Context, cmd *cobra.Command, pm *profilemanager
return nil
}
// daemonStatusPollTimeout bounds how long we poll the Status RPC waiting for the
// daemon to answer coherently. The transport is already READY at this point (see
// DialClientGRPCServer), so this only covers the brief window where the gRPC server
// is serving but the daemon engine is still starting up and the Status RPC races
// against server.Start().
const daemonStatusPollTimeout = 15 * time.Second
// daemonReadyGrace bounds how long we keep polling once the daemon answers but
// still reports DaemonReady=false. A freshly-started daemon flips it to true
// within this window; an older daemon that never sets the field simply falls
// through after the grace elapses, preserving backward compatibility.
const daemonReadyGrace = 10 * time.Second
// waitForDaemonStatus fetches the daemon status, waiting for the daemon to become
// ready. It handles two startup races:
//
// 1. The gRPC server is not yet serving: Status fails with Unavailable — retry.
// 2. The server serves but the engine is still starting: a DaemonReady-aware
// daemon reports DaemonReady=false until Start finishes; poll until it flips
// true (bounded by daemonReadyGrace). Older daemons never set DaemonReady, so
// we stop waiting on it after the grace and use the status as-is.
//
// It gives up after daemonStatusPollTimeout.
func waitForDaemonStatus(ctx context.Context, client proto.DaemonServiceClient) (*proto.StatusResponse, error) {
ctx, cancel := context.WithTimeout(ctx, daemonStatusPollTimeout)
defer cancel()
waitForReady := true
req := &proto.StatusRequest{WaitForReady: &waitForReady}
var lastErr error
var firstAnswer time.Time
for {
status, err := client.Status(ctx, req)
if err != nil {
lastErr = err
// Only retry while the daemon is not yet answering; surface real errors.
if s, ok := gstatus.FromError(err); !ok || s.Code() != codes.Unavailable {
return nil, err
}
} else {
// Daemon answered. Explicitly ready (DaemonReady-aware daemon), or
// already fully connected — either way, done. Connected is the only
// status unambiguous enough to short-circuit on: a DaemonReady-aware
// daemon sets the flag at startup, so trusting Connected here can only
// help an older daemon that never sets the flag, without overriding a
// new daemon that legitimately reports DaemonReady=false while starting.
if status.GetDaemonReady() || internal.StatusType(status.GetStatus()) == internal.StatusConnected {
return status, nil
}
// Answered but neither ready-flagged nor connected yet: give a
// DaemonReady-aware daemon a bounded window to finish starting, then
// fall through so an older daemon that never sets the flag isn't
// blocked here.
if firstAnswer.IsZero() {
firstAnswer = time.Now()
} else if time.Since(firstAnswer) >= daemonReadyGrace {
return status, nil
}
lastErr = nil
}
select {
case <-ctx.Done():
if lastErr != nil {
return nil, fmt.Errorf("daemon did not become ready: %w", lastErr)
}
return nil, fmt.Errorf("daemon did not become ready within %s", daemonStatusPollTimeout)
case <-time.After(500 * time.Millisecond):
}
}
}
func doDaemonUp(ctx context.Context, cmd *cobra.Command, client proto.DaemonServiceClient, pm *profilemanager.ProfileManager, activeProf *profilemanager.Profile, customDNSAddressConverted []byte, username string) error {
providedSetupKey, err := getSetupKey()

View File

@@ -292,18 +292,16 @@ func (s *serviceViaListener) generateFreePort() (uint16, error) {
return customPort, nil
}
udpAddr := net.UDPAddrFromAddrPort(netip.MustParseAddrPort("0.0.0.0:0"))
probeListener, err := net.ListenUDP("udp", udpAddr)
probeListener, err := net.ListenUDP("udp4", &net.UDPAddr{})
if err != nil {
log.Debugf("failed to bind random port for DNS: %s", err)
return 0, err
}
addrPort := netip.MustParseAddrPort(probeListener.LocalAddr().String()) // might panic if address is incorrect
err = probeListener.Close()
if err != nil {
port := uint16(probeListener.LocalAddr().(*net.UDPAddr).Port)
if err = probeListener.Close(); err != nil {
log.Debugf("failed to free up DNS port: %s", err)
return 0, err
}
return addrPort.Port(), nil
return port, nil
}

View File

@@ -551,7 +551,7 @@ func (e *Engine) Start(netbirdConfig *mgmProto.NetbirdConfig, mgmtURL *url.URL)
} else {
log.Infof("running rosenpass in strict mode")
}
e.rpManager, err = rosenpass.NewManager(e.config.PreSharedKey, e.config.WgIfaceName, publicKey, e.config.StateDir)
e.rpManager, err = rosenpass.NewManager(e.config.PreSharedKey, e.config.WgIfaceName, publicKey)
if err != nil {
return fmt.Errorf("create rosenpass manager: %w", err)
}
@@ -1809,7 +1809,6 @@ func (e *Engine) createPeerConn(pubKey string, allowedIPs []netip.Prefix, agentV
PubKey: e.getRosenpassPubKey(),
Addr: e.getRosenpassAddr(),
PermissiveMode: e.config.RosenpassPermissive,
KeyResolver: e.rosenpassKeyResolver(),
},
ICEConfig: e.createICEConfig(),
}
@@ -1880,8 +1879,6 @@ func (e *Engine) receiveSignalEvents() error {
log.Debugf("receiveMSG: took %s to get lock for peer %s with session id %s", gotLock, msg.Key, offerAnswer.SessionID)
e.applyRosenpassKeyExchange(msg, offerAnswer)
if msg.Body.Type == sProto.Body_OFFER {
conn.OnRemoteOffer(*offerAnswer)
} else {
@@ -2225,34 +2222,6 @@ func (e *Engine) getRosenpassAddr() string {
return ""
}
// rosenpassKeyResolver returns the Rosenpass manager as the offer/answer key
// resolver, or a true nil interface when Rosenpass is disabled (returning the
// typed-nil *Manager would make the interface non-nil and panic on use).
func (e *Engine) rosenpassKeyResolver() peer.RosenpassKeyResolver {
if e.rpManager == nil {
return nil
}
return e.rpManager
}
// applyRosenpassKeyExchange reconciles the fingerprint/cache fields of an incoming
// offer/answer against the Rosenpass manager's cache: it resolves the remote peer's
// full public key (from the message or the cache) into the OfferAnswer, and records
// whether the peer acknowledged holding our key. No-op when Rosenpass is disabled.
func (e *Engine) applyRosenpassKeyExchange(msg *sProto.Message, oa *peer.OfferAnswer) {
if e.rpManager == nil {
return
}
cfg := msg.GetBody().GetRosenpassConfig()
if cfg == nil {
return
}
remoteWgKey := msg.GetKey()
oa.RosenpassPubKey = e.rpManager.ResolveRemotePubKey(remoteWgKey, cfg.GetRosenpassPubKey(), cfg.GetRosenpassPubKeyHash())
e.rpManager.SetRemoteAck(remoteWgKey, cfg.GetAcknowledgedRosenpassPubKeyHash())
}
// RunHealthProbes executes health checks for Signal, Management, Relay, and WireGuard services
// and updates the status recorder with the latest states.
//

View File

@@ -65,20 +65,6 @@ type WgConfig struct {
PreSharedKey *wgtypes.Key
}
// RosenpassKeyResolver lets the handshaker fill the fingerprint/cache fields of an
// offer/answer without depending on the Rosenpass manager directly. Implemented by
// rosenpass.Manager and wired in by the engine.
type RosenpassKeyResolver interface {
// LocalPubKeyHash is the SHA256 of our own Rosenpass public key.
LocalPubKeyHash() []byte
// RemotePubKeyAck is the SHA256 of the remote peer's cached key (nil if we do
// not hold it), sent back as an acknowledgement.
RemotePubKeyAck(remoteWgKey string) []byte
// RemoteHasLocalKey reports whether the peer already holds our key, so the full
// key may be omitted.
RemoteHasLocalKey(remoteWgKey string) bool
}
type RosenpassConfig struct {
// RosenpassPubKey is this peer's Rosenpass public key
PubKey []byte
@@ -86,10 +72,6 @@ type RosenpassConfig struct {
Addr string
PermissiveMode bool
// KeyResolver drives fingerprint-based key caching over signalling. Nil when
// Rosenpass is disabled, which makes the handshaker always send the full key.
KeyResolver RosenpassKeyResolver
}
// ConnConfig is a peer Connection configuration

View File

@@ -33,13 +33,8 @@ type OfferAnswer struct {
// Version of NetBird Agent
Version string
// RosenpassPubKey is the Rosenpass public key of the remote peer when receiving this message
// This value is the local Rosenpass server public key when sending the message.
// May be empty on send when the remote peer has acknowledged already holding it (see RosenpassPubKeyAck).
// This value is the local Rosenpass server public key when sending the message
RosenpassPubKey []byte
// RosenpassPubKeyHash is the SHA256 of the sender's own RosenpassPubKey. Always set when Rosenpass is enabled.
RosenpassPubKeyHash []byte
// RosenpassPubKeyAck is the SHA256 of the remote peer's key the sender holds cached; empty means "send it in full".
RosenpassPubKeyAck []byte
// RosenpassAddr is the Rosenpass server address (IP:port) of the remote peer when receiving this message
// This value is the local Rosenpass server address when sending the message
RosenpassAddr string
@@ -214,11 +209,11 @@ func (h *Handshaker) sendAnswer() error {
func (h *Handshaker) buildOfferAnswer() OfferAnswer {
answer := OfferAnswer{
WgListenPort: h.config.LocalWgPort,
Version: version.NetbirdVersion(),
RosenpassAddr: h.config.RosenpassConfig.Addr,
WgListenPort: h.config.LocalWgPort,
Version: version.NetbirdVersion(),
RosenpassPubKey: h.config.RosenpassConfig.PubKey,
RosenpassAddr: h.config.RosenpassConfig.Addr,
}
h.setRosenpassPubKey(&answer)
if h.ice != nil && h.RemoteICESupported() {
uFrag, pwd := h.ice.GetLocalUserCredentials()
@@ -235,30 +230,6 @@ func (h *Handshaker) buildOfferAnswer() OfferAnswer {
return answer
}
// setRosenpassPubKey fills the Rosenpass key fields of an outgoing offer/answer.
// With a resolver wired it advertises our key hash and the ack for the remote key
// we hold, and includes the full public key only when the peer has not yet
// acknowledged holding it. Without a resolver (Rosenpass disabled, or an older
// code path) it always sends the full key, preserving the previous behaviour.
func (h *Handshaker) setRosenpassPubKey(answer *OfferAnswer) {
localKey := h.config.RosenpassConfig.PubKey
if len(localKey) == 0 {
return
}
resolver := h.config.RosenpassConfig.KeyResolver
if resolver == nil {
answer.RosenpassPubKey = localKey
return
}
answer.RosenpassPubKeyHash = resolver.LocalPubKeyHash()
answer.RosenpassPubKeyAck = resolver.RemotePubKeyAck(h.config.Key)
if !resolver.RemoteHasLocalKey(h.config.Key) {
answer.RosenpassPubKey = localKey
}
}
func (h *Handshaker) updateRemoteICEState(offer *OfferAnswer) {
hasICE := offer.hasICECredentials()
prev := h.remoteICESupported.Swap(hasICE)

View File

@@ -1,65 +0,0 @@
package peer
import (
"testing"
"github.com/stretchr/testify/require"
)
type fakeRPResolver struct {
localHash []byte
ack []byte
hasLocal bool
}
func (f fakeRPResolver) LocalPubKeyHash() []byte { return f.localHash }
func (f fakeRPResolver) RemotePubKeyAck(string) []byte { return f.ack }
func (f fakeRPResolver) RemoteHasLocalKey(remote string) bool { return f.hasLocal }
func TestSetRosenpassPubKey_NoResolverAlwaysSendsFullKey(t *testing.T) {
localKey := []byte{1, 2, 3}
h := &Handshaker{config: ConnConfig{RosenpassConfig: RosenpassConfig{PubKey: localKey}}}
var a OfferAnswer
h.setRosenpassPubKey(&a)
require.Equal(t, localKey, a.RosenpassPubKey)
require.Nil(t, a.RosenpassPubKeyHash)
require.Nil(t, a.RosenpassPubKeyAck)
}
func TestSetRosenpassPubKey_ResolverIncludesFullKeyUntilAcked(t *testing.T) {
localKey := []byte{1, 2, 3}
res := fakeRPResolver{localHash: []byte{9}, ack: []byte{8}, hasLocal: false}
h := &Handshaker{config: ConnConfig{Key: "peerA", RosenpassConfig: RosenpassConfig{PubKey: localKey, KeyResolver: res}}}
var a OfferAnswer
h.setRosenpassPubKey(&a)
require.Equal(t, localKey, a.RosenpassPubKey, "full key must be sent until the peer acks it")
require.Equal(t, []byte{9}, a.RosenpassPubKeyHash)
require.Equal(t, []byte{8}, a.RosenpassPubKeyAck)
}
func TestSetRosenpassPubKey_ResolverOmitsFullKeyOnceAcked(t *testing.T) {
localKey := []byte{1, 2, 3}
res := fakeRPResolver{localHash: []byte{9}, ack: []byte{8}, hasLocal: true}
h := &Handshaker{config: ConnConfig{Key: "peerA", RosenpassConfig: RosenpassConfig{PubKey: localKey, KeyResolver: res}}}
var a OfferAnswer
h.setRosenpassPubKey(&a)
require.Nil(t, a.RosenpassPubKey, "full key must be omitted once the peer holds it")
require.Equal(t, []byte{9}, a.RosenpassPubKeyHash)
require.Equal(t, []byte{8}, a.RosenpassPubKeyAck)
}
func TestSetRosenpassPubKey_DisabledSetsNothing(t *testing.T) {
h := &Handshaker{config: ConnConfig{RosenpassConfig: RosenpassConfig{}}}
var a OfferAnswer
h.setRosenpassPubKey(&a)
require.Nil(t, a.RosenpassPubKey)
require.Nil(t, a.RosenpassPubKeyHash)
}

View File

@@ -61,13 +61,11 @@ func (s *Signaler) signalOfferAnswer(offerAnswer OfferAnswer, remoteKey string,
UFrag: offerAnswer.IceCredentials.UFrag,
Pwd: offerAnswer.IceCredentials.Pwd,
},
RosenpassPubKey: offerAnswer.RosenpassPubKey,
RosenpassPubKeyHash: offerAnswer.RosenpassPubKeyHash,
RosenpassPubKeyAck: offerAnswer.RosenpassPubKeyAck,
RosenpassAddr: offerAnswer.RosenpassAddr,
RelaySrvAddress: offerAnswer.RelaySrvAddress,
RelaySrvIP: offerAnswer.RelaySrvIP,
SessionID: sessionIDBytes,
RosenpassPubKey: offerAnswer.RosenpassPubKey,
RosenpassAddr: offerAnswer.RosenpassAddr,
RelaySrvAddress: offerAnswer.RelaySrvAddress,
RelaySrvIP: offerAnswer.RelaySrvIP,
SessionID: sessionIDBytes,
})
if err != nil {
return err

View File

@@ -1,62 +0,0 @@
package rosenpass
import (
"bytes"
"testing"
"github.com/stretchr/testify/require"
)
func newCacheTestManager(spk []byte) *Manager {
return &Manager{
spk: spk,
remotePubKeys: make(map[string][]byte),
remoteHasLocalKey: make(map[string]bool),
}
}
func TestResolveRemotePubKey(t *testing.T) {
m := newCacheTestManager([]byte{0x01, 0x02})
full := bytes.Repeat([]byte{0xAB}, 64)
// a received full key is cached and returned
require.Equal(t, full, m.ResolveRemotePubKey("peerA", full, nil))
// a later hash-only message resolves from the cache
require.Equal(t, full, m.ResolveRemotePubKey("peerA", nil, rawRosenpassKeyHash(full)))
// hash mismatch is a cache miss
require.Nil(t, m.ResolveRemotePubKey("peerA", nil, bytes.Repeat([]byte{0x01}, 32)))
// no key and no hash (remote without Rosenpass) resolves to nil
require.Nil(t, m.ResolveRemotePubKey("peerB", nil, nil))
}
func TestRemotePubKeyAck(t *testing.T) {
m := newCacheTestManager([]byte{0x01})
// unknown peer -> no ack (signals "send me the full key")
require.Nil(t, m.RemotePubKeyAck("peerA"))
full := bytes.Repeat([]byte{0x09}, 48)
m.ResolveRemotePubKey("peerA", full, nil)
require.Equal(t, rawRosenpassKeyHash(full), m.RemotePubKeyAck("peerA"))
}
func TestSetRemoteAckAndRemoteHasLocalKey(t *testing.T) {
m := newCacheTestManager(bytes.Repeat([]byte{0x07}, 100))
require.False(t, m.RemoteHasLocalKey("peerA"))
// an ack matching our own key hash marks the peer as holding our key
m.SetRemoteAck("peerA", m.LocalPubKeyHash())
require.True(t, m.RemoteHasLocalKey("peerA"))
// empty ack clears it
m.SetRemoteAck("peerA", nil)
require.False(t, m.RemoteHasLocalKey("peerA"))
// a non-matching ack does not count
m.SetRemoteAck("peerA", bytes.Repeat([]byte{0x01}, 32))
require.False(t, m.RemoteHasLocalKey("peerA"))
}

View File

@@ -8,7 +8,6 @@ import (
"log/slog"
"net"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
@@ -29,11 +28,6 @@ func hashRosenpassKey(key []byte) string {
return hex.EncodeToString(hasher.Sum(nil))
}
func rawRosenpassKeyHash(key []byte) []byte {
sum := sha256.Sum256(key)
return sum[:]
}
// rpServer is the subset of rp.Server used by Manager. Defined as an interface
// so tests can substitute a mock without spinning up a real UDP server.
type rpServer interface {
@@ -56,29 +50,12 @@ type Manager struct {
lock sync.Mutex
port int
wgIface PresharedKeySetter
// remotePubKeys caches remote peers' full Rosenpass public keys keyed by their
// WireGuard public key, so a peer that already sent us its (large) key over
// signalling need only send its hash on subsequent offers/answers. RAM only —
// never persisted (1000 peers x ~512KB would be ~512MB on disk).
remotePubKeys map[string][]byte
// remoteHasLocalKey tracks, per remote WireGuard key, whether that peer has
// acknowledged holding our current Rosenpass public key, letting us omit it.
remoteHasLocalKey map[string]bool
}
// NewManager creates a new Rosenpass manager. localWgKey is the local
// WireGuard public key, used to derive the per-peer rendezvous key. When stateDir
// is non-empty the static keypair is persisted under it and reused across
// restarts, keeping the public key (and the fingerprint peers cache) stable;
// an empty stateDir keeps the previous behaviour of an ephemeral per-run keypair.
func NewManager(preSharedKey *wgtypes.Key, wgIfaceName string, localWgKey wgtypes.Key, stateDir string) (*Manager, error) {
var keyPath string
if stateDir != "" {
keyPath = filepath.Join(stateDir, keypairFileName)
}
public, secret, err := loadOrGenerateKeypair(keyPath)
// WireGuard public key, used to derive the per-peer rendezvous key.
func NewManager(preSharedKey *wgtypes.Key, wgIfaceName string, localWgKey wgtypes.Key) (*Manager, error) {
public, secret, err := rp.GenerateKeyPair()
if err != nil {
return nil, err
}
@@ -99,10 +76,8 @@ func NewManager(preSharedKey *wgtypes.Key, wgIfaceName string, localWgKey wgtype
// nil receiver in addPeer -> m.rpWgHandler.AddPeer. generateConfig will
// replace it with a fresh handler on each Run() to clear stale peer
// state from previous engine sessions.
rpWgHandler: NewNetbirdHandler((*[32]byte)(preSharedKey), localWgKey),
lock: sync.Mutex{},
remotePubKeys: make(map[string][]byte),
remoteHasLocalKey: make(map[string]bool),
rpWgHandler: NewNetbirdHandler((*[32]byte)(preSharedKey), localWgKey),
lock: sync.Mutex{},
}, nil
}
@@ -115,68 +90,6 @@ func (m *Manager) GetAddress() *net.UDPAddr {
return &net.UDPAddr{Port: m.port}
}
// LocalPubKeyHash returns the raw SHA256 of the local Rosenpass public key. It is
// advertised on every offer/answer so the remote peer can tell (via its cache)
// whether it already holds our full key.
func (m *Manager) LocalPubKeyHash() []byte {
return rawRosenpassKeyHash(m.spk)
}
// RemotePubKeyAck returns the SHA256 of the remote peer's cached public key, used
// as the acknowledgement we send back. Nil means we do not hold the peer's key,
// which signals the peer to include its full key next time.
func (m *Manager) RemotePubKeyAck(remoteWgKey string) []byte {
m.lock.Lock()
defer m.lock.Unlock()
key, ok := m.remotePubKeys[remoteWgKey]
if !ok {
return nil
}
return rawRosenpassKeyHash(key)
}
// RemoteHasLocalKey reports whether the remote peer acknowledged holding our
// current public key, so we may omit the full key from the next offer/answer.
func (m *Manager) RemoteHasLocalKey(remoteWgKey string) bool {
m.lock.Lock()
defer m.lock.Unlock()
return m.remoteHasLocalKey[remoteWgKey]
}
// ResolveRemotePubKey reconciles the Rosenpass key material from a received
// offer/answer: it caches a received full key, or — when only a hash was sent —
// returns the cached key matching that hash. It returns nil when the remote peer
// does not use Rosenpass (no key, no hash) or on a cache miss (hash sent but not
// held); a miss self-heals because our resulting empty ack makes the peer resend
// its full key.
func (m *Manager) ResolveRemotePubKey(remoteWgKey string, full, hash []byte) []byte {
m.lock.Lock()
defer m.lock.Unlock()
if len(full) > 0 {
m.remotePubKeys[remoteWgKey] = full
return full
}
if len(hash) == 0 {
return nil
}
if cached, ok := m.remotePubKeys[remoteWgKey]; ok && bytes.Equal(rawRosenpassKeyHash(cached), hash) {
return cached
}
return nil
}
// SetRemoteAck records whether the remote peer's acknowledgement matches our
// current public key hash, i.e. whether it already holds our key.
func (m *Manager) SetRemoteAck(remoteWgKey string, ack []byte) {
m.lock.Lock()
defer m.lock.Unlock()
m.remoteHasLocalKey[remoteWgKey] = len(ack) > 0 && bytes.Equal(ack, rawRosenpassKeyHash(m.spk))
}
// addPeer adds a new peer to the Rosenpass server
func (m *Manager) addPeer(rosenpassPubKey []byte, rosenpassAddr string, wireGuardIP string, wireGuardPubKey string) error {
// Defense in depth against issue #4341 (Android crash): if Run() has not

View File

@@ -255,7 +255,7 @@ func TestAddPeer_NilServer_ReturnsErrorNoCrash(t *testing.T) {
// issue #4341 cannot occur in the window between NewManager and Run().
func TestNewManager_PreInitializesHandler(t *testing.T) {
psk := wgtypes.Key{}
m, err := NewManager(&psk, "wt0", wgtypes.Key{0x01}, "")
m, err := NewManager(&psk, "wt0", wgtypes.Key{0x01})
require.NoError(t, err)
require.NotNil(t, m.rpWgHandler, "rpWgHandler must be initialized in NewManager")
}

View File

@@ -1,92 +0,0 @@
package rosenpass
import (
"context"
"fmt"
"os"
rp "cunicu.li/go-rosenpass"
log "github.com/sirupsen/logrus"
"github.com/netbirdio/netbird/util"
)
const (
// keypairFileName is the file, relative to the state directory, that holds
// the persisted local Rosenpass static keypair.
keypairFileName = "rosenpass_key.json"
// rpStaticPublicKeySize is the byte length of a Rosenpass (Classic McEliece)
// static public key as produced by the pinned go-rosenpass version. Used as a
// version-compatibility guard: a persisted key of any other size is treated as
// stale and regenerated instead of being fed to go-rosenpass (which would fail).
rpStaticPublicKeySize = 524160
// keypairFormatVersion is bumped whenever the on-disk representation changes so
// old files are discarded and regenerated rather than misparsed.
keypairFormatVersion = 1
)
// persistedKeypair is the on-disk representation of the local Rosenpass static
// keypair. Keys are stored raw (base64 via JSON) with the same restricted 0600
// permission as the WireGuard private key and other client secrets.
type persistedKeypair struct {
Version int `json:"version"`
PublicKey []byte `json:"public_key"`
SecretKey []byte `json:"secret_key"`
}
// loadOrGenerateKeypair returns a Rosenpass static keypair. When keyPath is set
// and holds a valid persisted keypair it is reused, so the local public key —
// and therefore the fingerprint advertised to remote peers over signalling —
// stays stable across restarts. Otherwise a fresh keypair is generated and, when
// keyPath is set, persisted for subsequent runs. A missing or corrupt file is not
// fatal: it degrades to generating an ephemeral keypair, matching the pre-persistence
// behaviour.
func loadOrGenerateKeypair(keyPath string) (public []byte, secret []byte, err error) {
if keyPath != "" {
public, secret, err = loadKeypair(keyPath)
switch {
case err == nil:
return public, secret, nil
case os.IsNotExist(err):
// first run for this state dir; fall through to generate
default:
log.Warnf("failed to load persisted rosenpass keypair, generating a new one: %v", err)
}
}
pub, sec, err := rp.GenerateKeyPair()
if err != nil {
return nil, nil, fmt.Errorf("generate rosenpass key pair: %w", err)
}
if keyPath != "" {
if err := saveKeypair(keyPath, pub, sec); err != nil {
log.Warnf("failed to persist rosenpass keypair, key will be regenerated on next restart: %v", err)
}
}
return pub, sec, nil
}
func loadKeypair(keyPath string) ([]byte, []byte, error) {
var kp persistedKeypair
if _, err := util.ReadJson(keyPath, &kp); err != nil {
return nil, nil, err
}
if kp.Version != keypairFormatVersion || len(kp.PublicKey) != rpStaticPublicKeySize || len(kp.SecretKey) == 0 {
return nil, nil, fmt.Errorf("persisted rosenpass keypair is incompatible (version %d, public %d bytes, secret %d bytes)", kp.Version, len(kp.PublicKey), len(kp.SecretKey))
}
return kp.PublicKey, kp.SecretKey, nil
}
func saveKeypair(keyPath string, public, secret []byte) error {
return util.WriteJsonWithRestrictedPermission(context.Background(), keyPath, persistedKeypair{
Version: keypairFormatVersion,
PublicKey: public,
SecretKey: secret,
})
}

View File

@@ -1,66 +0,0 @@
package rosenpass
import (
"bytes"
"encoding/json"
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/require"
)
func TestLoadOrGenerateKeypair_EphemeralWhenNoPath(t *testing.T) {
pub, sec, err := loadOrGenerateKeypair("")
require.NoError(t, err)
require.Len(t, pub, rpStaticPublicKeySize)
require.NotEmpty(t, sec)
}
func TestLoadOrGenerateKeypair_PersistsAndReloads(t *testing.T) {
keyPath := filepath.Join(t.TempDir(), keypairFileName)
pub1, sec1, err := loadOrGenerateKeypair(keyPath)
require.NoError(t, err)
info, err := os.Stat(keyPath)
require.NoError(t, err, "keypair file must be written")
require.Equal(t, os.FileMode(0600), info.Mode().Perm(), "keypair file must be 0600")
pub2, sec2, err := loadOrGenerateKeypair(keyPath)
require.NoError(t, err)
require.True(t, bytes.Equal(pub1, pub2), "public key must be stable across reloads")
require.True(t, bytes.Equal(sec1, sec2), "secret key must be stable across reloads")
}
func TestLoadOrGenerateKeypair_RegeneratesOnCorruptFile(t *testing.T) {
keyPath := filepath.Join(t.TempDir(), keypairFileName)
require.NoError(t, os.WriteFile(keyPath, []byte("not json"), 0600))
pub, sec, err := loadOrGenerateKeypair(keyPath)
require.NoError(t, err)
require.Len(t, pub, rpStaticPublicKeySize)
require.NotEmpty(t, sec)
// the corrupt file must have been overwritten with a valid, reloadable keypair
pub2, _, err := loadOrGenerateKeypair(keyPath)
require.NoError(t, err)
require.True(t, bytes.Equal(pub, pub2))
}
func TestLoadOrGenerateKeypair_RegeneratesOnVersionMismatch(t *testing.T) {
keyPath := filepath.Join(t.TempDir(), keypairFileName)
pub1, _, err := loadOrGenerateKeypair(keyPath)
require.NoError(t, err)
// rewrite with a bumped/unknown format version -> must be discarded
bs, err := json.Marshal(persistedKeypair{Version: keypairFormatVersion + 1, PublicKey: pub1, SecretKey: []byte{0x01}})
require.NoError(t, err)
require.NoError(t, os.WriteFile(keyPath, bs, 0600))
pub2, sec2, err := loadOrGenerateKeypair(keyPath)
require.NoError(t, err)
require.Len(t, pub2, rpStaticPublicKeySize)
require.NotEmpty(t, sec2)
}

View File

@@ -44,10 +44,25 @@ type Auth struct {
// NewAuth instantiate Auth struct and validate the management URL
func NewAuth(cfgPath string, mgmURL string) (*Auth, error) {
inputCfg := profilemanager.ConfigInput{
ConfigPath: cfgPath,
ManagementURL: mgmURL,
}
cfg, err := profilemanager.CreateInMemoryConfig(inputCfg)
// Load the existing config when a config file is already present so an
// interactive re-login reuses the peer's persisted WireGuard private key
// (and thus its identity) instead of generating a fresh one. Generating a
// new key registers a brand-new peer on the management server on every
// re-auth (named after the fallback hostname). Only fall back to a fresh
// in-memory config for the first-time login when no config file exists yet.
// DirectUpdateOrCreateConfig uses non-atomic writes so it also works inside
// the tvOS App Group sandbox where atomic temp-file+rename is blocked.
var cfg *profilemanager.Config
var err error
if cfgPath != "" {
cfg, err = profilemanager.DirectUpdateOrCreateConfig(inputCfg)
} else {
cfg, err = profilemanager.CreateInMemoryConfig(inputCfg)
}
if err != nil {
return nil, err
}

View File

@@ -1,71 +1,27 @@
#!/usr/bin/env bash
# Runs the NetBird daemon and brings the connection up in one container process.
#
# A thin wrapper is needed (rather than a one-line ENTRYPOINT) for two reasons:
# 1. Two processes must run: the daemon (`service run`, long-lived) and a
# one-shot `up` that brings the connection up.
# 2. Signal handling: as PID 1 the wrapper must forward SIGTERM/SIGINT to the
# daemon so it tears down WireGuard and deregisters ephemeral peers on
# `docker stop`. Without this the daemon would be killed uncleanly.
#
# `netbird up` waits for the daemon to become ready on its own, so no readiness
# poll is needed here.
set -eEuo pipefail
: ${NB_ENTRYPOINT_SERVICE_TIMEOUT:="30"}
NETBIRD_BIN="${NETBIRD_BIN:-"netbird"}"
export NB_LOG_FILE="${NB_LOG_FILE:-"console,/var/log/netbird/client.log"}"
service_pids=()
_log() {
# mimic Go logger's output for easier parsing
# 2025-04-15T21:32:00+08:00 INFO client/internal/config.go:495: setting notifications to disabled by default
printf "$(date -Isec) ${1} ${BASH_SOURCE[1]}:${BASH_LINENO[1]}: ${2}\n" "${@:3}" >&2
}
daemon=""
cleanup() { [[ -n "${daemon}" ]] && kill -TERM "${daemon}" 2>/dev/null || true; }
trap cleanup SIGTERM SIGINT EXIT
info() {
_log INFO "$@"
}
"${NETBIRD_BIN}" service run &
daemon=$!
warn() {
_log WARN "$@"
}
"${NETBIRD_BIN}" up
on_exit() {
info "Shutting down NetBird daemon..."
if test "${#service_pids[@]}" -gt 0; then
info "terminating service process IDs: ${service_pids[@]@Q}"
kill -TERM "${service_pids[@]}" 2>/dev/null || true
wait "${service_pids[@]}" 2>/dev/null || true
else
info "there are no service processes to terminate"
fi
}
wait_for_daemon_startup() {
local timeout="${1}"
if [[ "${timeout}" -eq 0 ]]; then
info "not waiting for daemon startup due to zero timeout."
return
fi
local deadline=$((SECONDS + timeout))
while [[ "${SECONDS}" -lt "${deadline}" ]]; do
if "${NETBIRD_BIN}" status --check live 2>/dev/null; then
return
fi
sleep 1
done
warn "daemon did not become responsive after ${timeout} seconds, exiting..."
exit 1
}
connect() {
info "running 'netbird up'..."
"${NETBIRD_BIN}" up
return $?
}
main() {
trap 'on_exit' SIGTERM SIGINT EXIT
"${NETBIRD_BIN}" service run &
service_pids+=("$!")
info "registered new service process 'netbird service run', currently running: ${service_pids[@]@Q}"
wait_for_daemon_startup "${NB_ENTRYPOINT_SERVICE_TIMEOUT}"
connect
wait "${service_pids[@]}"
}
main "$@"
wait "${daemon}"

View File

@@ -995,8 +995,13 @@ type StatusResponse struct {
// Unset when the peer is not SSO-registered or login expiration is disabled.
// The UI derives "warning active" from this value and its own clock.
SessionExpiresAt *timestamppb.Timestamp `protobuf:"bytes,4,opt,name=sessionExpiresAt,proto3" json:"sessionExpiresAt,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
// daemonReady reports whether the daemon has finished starting up and is
// serving RPCs backed by a running engine. Older daemons never set this
// (it defaults to false); clients must treat an unset value as "unknown"
// and fall back to their previous readiness heuristics for compatibility.
DaemonReady bool `protobuf:"varint,5,opt,name=daemonReady,proto3" json:"daemonReady,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *StatusResponse) Reset() {
@@ -1057,6 +1062,13 @@ func (x *StatusResponse) GetSessionExpiresAt() *timestamppb.Timestamp {
return nil
}
func (x *StatusResponse) GetDaemonReady() bool {
if x != nil {
return x.DaemonReady
}
return false
}
type DownRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
unknownFields protoimpl.UnknownFields
@@ -7083,14 +7095,15 @@ const file_daemon_proto_rawDesc = "" +
"\x11getFullPeerStatus\x18\x01 \x01(\bR\x11getFullPeerStatus\x12(\n" +
"\x0fshouldRunProbes\x18\x02 \x01(\bR\x0fshouldRunProbes\x12'\n" +
"\fwaitForReady\x18\x03 \x01(\bH\x00R\fwaitForReady\x88\x01\x01B\x0f\n" +
"\r_waitForReady\"\xca\x01\n" +
"\r_waitForReady\"\xec\x01\n" +
"\x0eStatusResponse\x12\x16\n" +
"\x06status\x18\x01 \x01(\tR\x06status\x122\n" +
"\n" +
"fullStatus\x18\x02 \x01(\v2\x12.daemon.FullStatusR\n" +
"fullStatus\x12$\n" +
"\rdaemonVersion\x18\x03 \x01(\tR\rdaemonVersion\x12F\n" +
"\x10sessionExpiresAt\x18\x04 \x01(\v2\x1a.google.protobuf.TimestampR\x10sessionExpiresAt\"\r\n" +
"\x10sessionExpiresAt\x18\x04 \x01(\v2\x1a.google.protobuf.TimestampR\x10sessionExpiresAt\x12 \n" +
"\vdaemonReady\x18\x05 \x01(\bR\vdaemonReady\"\r\n" +
"\vDownRequest\"\x0e\n" +
"\fDownResponse\"P\n" +
"\x10GetConfigRequest\x12 \n" +

View File

@@ -291,6 +291,11 @@ message StatusResponse{
// Unset when the peer is not SSO-registered or login expiration is disabled.
// The UI derives "warning active" from this value and its own clock.
google.protobuf.Timestamp sessionExpiresAt = 4;
// daemonReady reports whether the daemon has finished starting up and is
// serving RPCs backed by a running engine. Older daemons never set this
// (it defaults to false); clients must treat an unset value as "unknown"
// and fall back to their previous readiness heuristics for compatibility.
bool daemonReady = 5;
}
message DownRequest {}

View File

@@ -104,6 +104,12 @@ type Server struct {
persistSyncResponse bool
isSessionActive atomic.Bool
// ready is set once the daemon has finished startup and is serving RPCs
// backed by a running engine (see SetReady, called after Start succeeds and
// the service is registered). Reported via StatusResponse.DaemonReady so
// clients can wait deterministically instead of polling heuristically.
ready atomic.Bool
cpuProfileBuf *bytes.Buffer
cpuProfiling bool
@@ -158,6 +164,14 @@ func New(ctx context.Context, logFile string, configFile string, profilesDisable
return s
}
// SetReady marks the daemon as fully started and serving RPCs. It is called by
// the service controller once Start has succeeded and the DaemonService is
// registered, so a subsequent Status RPC reports DaemonReady=true. Safe for
// concurrent use.
func (s *Server) SetReady() {
s.ready.Store(true)
}
func (s *Server) Start() error {
s.mutex.Lock()
defer s.mutex.Unlock()
@@ -1422,7 +1436,7 @@ func (s *Server) buildStatusResponse(ctx context.Context, msg *proto.StatusReque
s.isSessionActive.Store(false)
}
statusResponse := proto.StatusResponse{Status: string(status), DaemonVersion: version.NetbirdVersion()}
statusResponse := proto.StatusResponse{Status: string(status), DaemonVersion: version.NetbirdVersion(), DaemonReady: s.ready.Load()}
if deadline := s.statusRecorder.GetSessionExpiresAt(); !deadline.IsZero() {
statusResponse.SessionExpiresAt = timestamppb.New(deadline)

View File

@@ -17,8 +17,7 @@ RUN apk add --no-cache bash ca-certificates ip6tables iproute2 iptables
ENV NETBIRD_BIN="/usr/local/bin/netbird" \
NB_LOG_FILE="console,/var/log/netbird/client.log" \
NB_DAEMON_ADDR="unix:///var/run/netbird.sock" \
NB_ENABLE_CAPTURE="false" \
NB_ENTRYPOINT_SERVICE_TIMEOUT="30"
NB_ENABLE_CAPTURE="false"
ENTRYPOINT [ "/usr/local/bin/netbird-entrypoint.sh" ]
COPY client/netbird-entrypoint.sh /usr/local/bin/netbird-entrypoint.sh
COPY --from=builder /out/netbird /usr/local/bin/netbird

View File

@@ -51,17 +51,10 @@ type CredentialPayload struct {
WgListenPort int
Credential *Credential
RosenpassPubKey []byte
// RosenpassPubKeyHash is the SHA256 of the sender's own RosenpassPubKey (empty
// when Rosenpass is disabled). RosenpassPubKey may be omitted when the peer has
// already acknowledged this hash. See RosenpassConfig in the proto.
RosenpassPubKeyHash []byte
// RosenpassPubKeyAck is the SHA256 of the remote peer's key the sender holds
// cached; empty means "send me the full key".
RosenpassPubKeyAck []byte
RosenpassAddr string
RelaySrvAddress string
RelaySrvIP netip.Addr
SessionID []byte
RosenpassAddr string
RelaySrvAddress string
RelaySrvIP netip.Addr
SessionID []byte
}
// UnMarshalCredential parses the credentials from the message and returns a Credential instance
@@ -85,10 +78,8 @@ func MarshalCredential(myKey wgtypes.Key, remoteKey string, p CredentialPayload)
WgListenPort: uint32(p.WgListenPort),
NetBirdVersion: version.NetbirdVersion(),
RosenpassConfig: &proto.RosenpassConfig{
RosenpassPubKey: p.RosenpassPubKey,
RosenpassServerAddr: p.RosenpassAddr,
RosenpassPubKeyHash: p.RosenpassPubKeyHash,
AcknowledgedRosenpassPubKeyHash: p.RosenpassPubKeyAck,
RosenpassPubKey: p.RosenpassPubKey,
RosenpassServerAddr: p.RosenpassAddr,
},
SessionId: p.SessionID,
}

View File

@@ -1,7 +1,7 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.26.0
// protoc v6.33.1
// protoc v3.21.12
// source: signalexchange.proto
package proto
@@ -399,17 +399,6 @@ type RosenpassConfig struct {
RosenpassPubKey []byte `protobuf:"bytes,1,opt,name=rosenpassPubKey,proto3" json:"rosenpassPubKey,omitempty"`
// rosenpassServerAddr is an IP:port of the rosenpass service
RosenpassServerAddr string `protobuf:"bytes,2,opt,name=rosenpassServerAddr,proto3" json:"rosenpassServerAddr,omitempty"`
// rosenpassPubKeyHash is the SHA256 of the sender's own rosenpassPubKey. It is
// always set when Rosenpass is enabled and lets the receiver detect (via a
// per-peer cache) whether it already holds the sender's full public key,
// avoiding re-sending the large key on every offer/answer.
RosenpassPubKeyHash []byte `protobuf:"bytes,3,opt,name=rosenpassPubKeyHash,proto3" json:"rosenpassPubKeyHash,omitempty"`
// acknowledgedRosenpassPubKeyHash is the SHA256 of the remote peer's rosenpassPubKey
// that the sender currently holds cached. When it matches the receiver's own key hash
// the receiver may omit its full rosenpassPubKey from the message. Empty means the
// sender does not have the remote key and needs it sent in full. Absent from peers
// that predate this field, which keeps them receiving the full key as before.
AcknowledgedRosenpassPubKeyHash []byte `protobuf:"bytes,4,opt,name=acknowledgedRosenpassPubKeyHash,proto3" json:"acknowledgedRosenpassPubKeyHash,omitempty"`
}
func (x *RosenpassConfig) Reset() {
@@ -458,20 +447,6 @@ func (x *RosenpassConfig) GetRosenpassServerAddr() string {
return ""
}
func (x *RosenpassConfig) GetRosenpassPubKeyHash() []byte {
if x != nil {
return x.RosenpassPubKeyHash
}
return nil
}
func (x *RosenpassConfig) GetAcknowledgedRosenpassPubKeyHash() []byte {
if x != nil {
return x.AcknowledgedRosenpassPubKeyHash
}
return nil
}
var File_signalexchange_proto protoreflect.FileDescriptor
var file_signalexchange_proto_rawDesc = []byte{
@@ -531,35 +506,27 @@ var file_signalexchange_proto_rawDesc = []byte{
0x65, 0x72, 0x49, 0x50, 0x4a, 0x04, 0x08, 0x09, 0x10, 0x0a, 0x22, 0x2e, 0x0a, 0x04, 0x4d, 0x6f,
0x64, 0x65, 0x12, 0x1b, 0x0a, 0x06, 0x64, 0x69, 0x72, 0x65, 0x63, 0x74, 0x18, 0x01, 0x20, 0x01,
0x28, 0x08, 0x48, 0x00, 0x52, 0x06, 0x64, 0x69, 0x72, 0x65, 0x63, 0x74, 0x88, 0x01, 0x01, 0x42,
0x09, 0x0a, 0x07, 0x5f, 0x64, 0x69, 0x72, 0x65, 0x63, 0x74, 0x22, 0xe9, 0x01, 0x0a, 0x0f, 0x52,
0x6f, 0x73, 0x65, 0x6e, 0x70, 0x61, 0x73, 0x73, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x28,
0x0a, 0x0f, 0x72, 0x6f, 0x73, 0x65, 0x6e, 0x70, 0x61, 0x73, 0x73, 0x50, 0x75, 0x62, 0x4b, 0x65,
0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0f, 0x72, 0x6f, 0x73, 0x65, 0x6e, 0x70, 0x61,
0x73, 0x73, 0x50, 0x75, 0x62, 0x4b, 0x65, 0x79, 0x12, 0x30, 0x0a, 0x13, 0x72, 0x6f, 0x73, 0x65,
0x6e, 0x70, 0x61, 0x73, 0x73, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x41, 0x64, 0x64, 0x72, 0x18,
0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x13, 0x72, 0x6f, 0x73, 0x65, 0x6e, 0x70, 0x61, 0x73, 0x73,
0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x41, 0x64, 0x64, 0x72, 0x12, 0x30, 0x0a, 0x13, 0x72, 0x6f,
0x73, 0x65, 0x6e, 0x70, 0x61, 0x73, 0x73, 0x50, 0x75, 0x62, 0x4b, 0x65, 0x79, 0x48, 0x61, 0x73,
0x68, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x13, 0x72, 0x6f, 0x73, 0x65, 0x6e, 0x70, 0x61,
0x73, 0x73, 0x50, 0x75, 0x62, 0x4b, 0x65, 0x79, 0x48, 0x61, 0x73, 0x68, 0x12, 0x48, 0x0a, 0x1f,
0x61, 0x63, 0x6b, 0x6e, 0x6f, 0x77, 0x6c, 0x65, 0x64, 0x67, 0x65, 0x64, 0x52, 0x6f, 0x73, 0x65,
0x6e, 0x70, 0x61, 0x73, 0x73, 0x50, 0x75, 0x62, 0x4b, 0x65, 0x79, 0x48, 0x61, 0x73, 0x68, 0x18,
0x04, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x1f, 0x61, 0x63, 0x6b, 0x6e, 0x6f, 0x77, 0x6c, 0x65, 0x64,
0x67, 0x65, 0x64, 0x52, 0x6f, 0x73, 0x65, 0x6e, 0x70, 0x61, 0x73, 0x73, 0x50, 0x75, 0x62, 0x4b,
0x65, 0x79, 0x48, 0x61, 0x73, 0x68, 0x32, 0xb9, 0x01, 0x0a, 0x0e, 0x53, 0x69, 0x67, 0x6e, 0x61,
0x6c, 0x45, 0x78, 0x63, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x12, 0x4c, 0x0a, 0x04, 0x53, 0x65, 0x6e,
0x64, 0x12, 0x20, 0x2e, 0x73, 0x69, 0x67, 0x6e, 0x61, 0x6c, 0x65, 0x78, 0x63, 0x68, 0x61, 0x6e,
0x67, 0x65, 0x2e, 0x45, 0x6e, 0x63, 0x72, 0x79, 0x70, 0x74, 0x65, 0x64, 0x4d, 0x65, 0x73, 0x73,
0x61, 0x67, 0x65, 0x1a, 0x20, 0x2e, 0x73, 0x69, 0x67, 0x6e, 0x61, 0x6c, 0x65, 0x78, 0x63, 0x68,
0x61, 0x6e, 0x67, 0x65, 0x2e, 0x45, 0x6e, 0x63, 0x72, 0x79, 0x70, 0x74, 0x65, 0x64, 0x4d, 0x65,
0x73, 0x73, 0x61, 0x67, 0x65, 0x22, 0x00, 0x12, 0x59, 0x0a, 0x0d, 0x43, 0x6f, 0x6e, 0x6e, 0x65,
0x63, 0x74, 0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x12, 0x20, 0x2e, 0x73, 0x69, 0x67, 0x6e, 0x61,
0x6c, 0x65, 0x78, 0x63, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x2e, 0x45, 0x6e, 0x63, 0x72, 0x79, 0x70,
0x74, 0x65, 0x64, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x1a, 0x20, 0x2e, 0x73, 0x69, 0x67,
0x6e, 0x61, 0x6c, 0x65, 0x78, 0x63, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x2e, 0x45, 0x6e, 0x63, 0x72,
0x79, 0x70, 0x74, 0x65, 0x64, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x22, 0x00, 0x28, 0x01,
0x30, 0x01, 0x42, 0x08, 0x5a, 0x06, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x06, 0x70, 0x72,
0x6f, 0x74, 0x6f, 0x33,
0x09, 0x0a, 0x07, 0x5f, 0x64, 0x69, 0x72, 0x65, 0x63, 0x74, 0x22, 0x6d, 0x0a, 0x0f, 0x52, 0x6f,
0x73, 0x65, 0x6e, 0x70, 0x61, 0x73, 0x73, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x28, 0x0a,
0x0f, 0x72, 0x6f, 0x73, 0x65, 0x6e, 0x70, 0x61, 0x73, 0x73, 0x50, 0x75, 0x62, 0x4b, 0x65, 0x79,
0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0f, 0x72, 0x6f, 0x73, 0x65, 0x6e, 0x70, 0x61, 0x73,
0x73, 0x50, 0x75, 0x62, 0x4b, 0x65, 0x79, 0x12, 0x30, 0x0a, 0x13, 0x72, 0x6f, 0x73, 0x65, 0x6e,
0x70, 0x61, 0x73, 0x73, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x41, 0x64, 0x64, 0x72, 0x18, 0x02,
0x20, 0x01, 0x28, 0x09, 0x52, 0x13, 0x72, 0x6f, 0x73, 0x65, 0x6e, 0x70, 0x61, 0x73, 0x73, 0x53,
0x65, 0x72, 0x76, 0x65, 0x72, 0x41, 0x64, 0x64, 0x72, 0x32, 0xb9, 0x01, 0x0a, 0x0e, 0x53, 0x69,
0x67, 0x6e, 0x61, 0x6c, 0x45, 0x78, 0x63, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x12, 0x4c, 0x0a, 0x04,
0x53, 0x65, 0x6e, 0x64, 0x12, 0x20, 0x2e, 0x73, 0x69, 0x67, 0x6e, 0x61, 0x6c, 0x65, 0x78, 0x63,
0x68, 0x61, 0x6e, 0x67, 0x65, 0x2e, 0x45, 0x6e, 0x63, 0x72, 0x79, 0x70, 0x74, 0x65, 0x64, 0x4d,
0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x1a, 0x20, 0x2e, 0x73, 0x69, 0x67, 0x6e, 0x61, 0x6c, 0x65,
0x78, 0x63, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x2e, 0x45, 0x6e, 0x63, 0x72, 0x79, 0x70, 0x74, 0x65,
0x64, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x22, 0x00, 0x12, 0x59, 0x0a, 0x0d, 0x43, 0x6f,
0x6e, 0x6e, 0x65, 0x63, 0x74, 0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x12, 0x20, 0x2e, 0x73, 0x69,
0x67, 0x6e, 0x61, 0x6c, 0x65, 0x78, 0x63, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x2e, 0x45, 0x6e, 0x63,
0x72, 0x79, 0x70, 0x74, 0x65, 0x64, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x1a, 0x20, 0x2e,
0x73, 0x69, 0x67, 0x6e, 0x61, 0x6c, 0x65, 0x78, 0x63, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x2e, 0x45,
0x6e, 0x63, 0x72, 0x79, 0x70, 0x74, 0x65, 0x64, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x22,
0x00, 0x28, 0x01, 0x30, 0x01, 0x42, 0x08, 0x5a, 0x06, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62,
0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
}
var (

View File

@@ -86,15 +86,4 @@ message RosenpassConfig {
bytes rosenpassPubKey = 1;
// rosenpassServerAddr is an IP:port of the rosenpass service
string rosenpassServerAddr = 2;
// rosenpassPubKeyHash is the SHA256 of the sender's own rosenpassPubKey. It is
// always set when Rosenpass is enabled and lets the receiver detect (via a
// per-peer cache) whether it already holds the sender's full public key,
// avoiding re-sending the large key on every offer/answer.
bytes rosenpassPubKeyHash = 3;
// acknowledgedRosenpassPubKeyHash is the SHA256 of the remote peer's rosenpassPubKey
// that the sender currently holds cached. When it matches the receiver's own key hash
// the receiver may omit its full rosenpassPubKey from the message. Empty means the
// sender does not have the remote key and needs it sent in full. Absent from peers
// that predate this field, which keeps them receiving the full key as before.
bytes acknowledgedRosenpassPubKeyHash = 4;
}