Skip to content

feat(scripts): T-5.4 Bootstrap Script v2.0 with Smart Selection#5175

Closed
obtFusi wants to merge 28 commits intonetbirdio:mainfrom
silentspike:feature/t-5.4-bootstrap-script
Closed

feat(scripts): T-5.4 Bootstrap Script v2.0 with Smart Selection#5175
obtFusi wants to merge 28 commits intonetbirdio:mainfrom
silentspike:feature/t-5.4-bootstrap-script

Conversation

@obtFusi
Copy link
Copy Markdown

@obtFusi obtFusi commented Jan 25, 2026

Summary

  • Updates bootstrap-new-client.ps1 for v3.6 Smart Certificate Selection
  • Adds security improvements: Setup-Key redaction, REVOKE warning, verification docs

Changes

  • Smart Selection v3.6: Uses machine_cert_template_name + machine_cert_san_must_match instead of hardcoded thumbprint
  • REVOKE Warning: Prominent security box at script end reminding to revoke Setup-Key in Dashboard
  • Secret Redaction: Setup-Key shown as ****-****-****-****-XXXX (only last 4 chars visible)
  • Security Docs: Added in .NOTES section:
    • SHA256 checksum verification instructions
    • Authenticode signing instructions
    • Setup-Key handling best practices

Test Evidence

Windows VM WhatIf Mode Test:

Step 1: Pre-Tunnel NTP Sync (Public NTP)
What if: Performing the operation "Configure public NTP" on target "W32Time".

Step 2: Starting NetBird Machine Service (Phase 1: Setup-Key)
What if: Performing the operation "Install and start with Setup-Key" on target "NetBirdMachine".

Step 3: Verifying DC Connectivity via Tunnel
  Testing LDAP (port 389)... [OK] OK
  Testing Kerberos (port 88)... [OK] OK
  Testing DNS (port 53)... [OK] OK
[OK] All required DC ports reachable via tunnel

Step 4: NTP Sync with Domain Controller
What if: Performing the operation "Configure DC NTP" on target "W32Time".

Step 5: Domain Join
[OK] Computer is already joined to test.local

Step 6: Machine Certificate Enrollment
What if: Performing the operation "Request machine certificate" on target "AD CS".

Step 7: Updating NetBird Config for mTLS (Phase 2 - Smart Selection)
What if: Performing the operation "Enable mTLS with Smart Selection" on target "C:\ProgramData\NetBird\config.yaml".

Step 8: Completing Bootstrap
╔═══════════════════════════════════════════════════════════════════╗
║  ⚠️  SECURITY ACTION REQUIRED                                      ║
║  REVOKE the Setup-Key in NetBird Dashboard immediately!           ║
║  Setup-Key used: ****-****-****-****-7890                         ║
╚═══════════════════════════════════════════════════════════════════╝

DoD Checklist

  • Script mit allen 8 Schritten
  • DC-Connectivity Prüfung vor Join
  • NTP-Sync vor Join (Kerberos)
  • Smart Selection Config (kein Thumbprint)
  • Warnung: "REVOKE setup-key!"
  • Error-Handling für jeden Schritt
  • Integration Test: WhatIf Mode auf Windows VM
  • Keine Secrets in Logs (Setup-Key redacted)
  • Script-Signatur via Authenticode (dokumentiert)
  • Checksum-Verifikation dokumentieren

Closes #50

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Added Windows machine tunnel bootstrap with two-phase authentication (Setup-Key Phase 1, mTLS Phase 2)
    • Implemented mTLS-based machine peer registration and management on dedicated port 33074
    • Added automated machine certificate enrollment and renewal via Active Directory Certificate Services
    • Introduced Domain Controller connectivity validation before domain join
    • Added PowerShell automation for client bootstrap, lab setup, and service installation
  • Configuration & Infrastructure

    • Enhanced server configuration with mTLS settings (port, CA certificates, issuer validation, domain mappings)
    • Added git hooks for code formatting and secret detection
    • Configured Dependabot for dependency updates and GitHub Actions for automated labeling and PR linting

✏️ Tip: You can customize this high-level summary in your review settings.

obtFusi and others added 28 commits January 18, 2026 02:54
- PR lint workflow (Conventional Commits validation)
- Auto-label workflow (Epic/Story/Task + type detection)
- Dependabot config (Go, Docker, GitHub Actions)
- Issue templates (Bug, Feature, Epic, Story, Task)
- PR template with checklist

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
ci: add GitHub configuration from network-agent pattern
Implements server-side mTLS authentication infrastructure:

- MTLSIdentity extraction from client certificates
- SAN DNSName as primary identity (not CN!)
- Template OID (v2) and Template Name (v1) parsing
- BMPString (UTF-16BE) decoding for AD CS templates
- PeerType determination (machine/user/unknown)
- Issuer fingerprint via VerifiedChains (strong binding)
- gRPC interceptors (unary + stream) with method-based routing

Includes:
- ADR-001: mTLS Port Strategy
- ADR-002: CNG Signer Interface (for T-1.1)
- Test certificates for unit tests
- Comprehensive test coverage

Closes #14 (T-1.2)
Closes #15 (T-1.3)
Refs #13 (T-1.1 blocked - needs Windows)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Security audit documents should not be committed to public repository.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
T-1.1: CNG crypto.Signer spike (spike/cng-signer/)
- Pure Go Windows CNG integration via golang.org/x/sys/windows
- Non-exportable private key signing with crypto.Signer interface
- Tested on DC01: 1.6ms signing latency, no CGO required
- Fixed CertDuplicateCertificateContext bug for context retention

T-1.3: SAN/Template parser spike (spike/san-parser/)
- Extracts SAN DNSName (primary identity, NOT CN)
- Parses AD CS Template OID/Name from extensions
- Determines PeerType (machine/user) from template analysis
- Tested on DC01: All checks passed

Also includes:
- scripts/lab/autounattend.xml for Windows VM provisioning

Closes #13, #15

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- setup-lab-ca.ps1: Automates AD CS setup, template creation, GPO
- verify-lab-ca.ps1: Validates CA configuration (7 checks)
- test-client-enrollment.ps1: Tests machine cert enrollment via SYSTEM context

Key improvements based on T-2.7 learnings:
- Machine cert enrollment requires SYSTEM context (Scheduled Task)
- Template created via ADSI with proper flags
- RPC port range restriction (5000-5100) for firewall

Closes #24

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Fix regex for CA name parsing (pipe to Out-String)
- Cast PropertyValueCollection to int for bitwise ops
- Fix GPO link check using Get-ADObject
- Fix RPC port range regex

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- RegisterMachinePeer, SyncMachinePeer, GetMachineRoutes, ReportMachineStatus
- MachineIdentity, MachineRegisterRequest/Response, MachineSyncRequest/Response
- MachineRoutesRequest/Response, MachineStatusRequest/Response
- MachineUpdateType enum

Refs #27

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Implements T-3.4: AllowedDomains pro-Account Scoping

- Add AccountID and MatchedDomain fields to MTLSIdentity struct
- Add MTLSDomainAccountMapping and MTLSAccountAllowedDomains config
- Implement getAccountIDFromDomain() for domain-to-account mapping
- Implement getAllowedDomainsForAccount() for per-account domain lists
- Implement validateDomainForAccount() for cross-tenant prevention
- Add checkMultiAccountSpan() for security logging
- Update extractMTLSIdentity() to validate against account domains
- Add comprehensive unit tests for account mapping

Security: Prevents cross-tenant certificate acceptance by validating
that certificate SANs match only the mapped account's allowed domains.
Fail-safe: No configured domains = reject all.

Closes #30

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Implement gRPC handlers for machine peer registration using mTLS:
- RegisterMachinePeer: Register machine peers via certificate auth
- SyncMachinePeer: Streaming sync for machine peers (stub)
- GetMachineRoutes: Retrieve DC routes for machine peers (stub)
- ReportMachineStatus: Machine status reporting

Architectural changes:
- Create shared/mtls package for Identity type to avoid import cycles
- Update mtls_auth.go to use shared Identity via type alias
- Remove duplicate GetMTLSIdentity function

The handlers extract mTLS identity from context (set by interceptor)
and use AccountID from domain-account mapping for multi-tenant isolation.

Closes #32

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
…ll mTLS support

Implements all features from Issue #32:

1. validateIssuerCA - CA-Fingerprint validation per account
   - Added MTLSAccountAllowedIssuers config field
   - ValidateIssuerCA function in shared/mtls package
   - Per Security Review: Empty allowlist = DENY (explicit config required)

2. Meta fields for audit trail
   - Extended PeerSystemMeta with mTLS-specific fields:
     - PeerType, AuthMethod, CertDNSName, CertDomain
     - CertIssuerFP, CertSerial, CertTemplate
     - FirstAuthTime, LastCertAuthTime
   - extractMachinePeerMeta enriches metadata with mTLS identity

3. Re-registration logic
   - LoginPeer handles both new and existing peers
   - Cross-account registration blocked (security check)
   - mTLS metadata updated on re-registration

4. Security validations
   - Issuer CA validation in all Machine Tunnel RPCs
   - Account isolation via MTLSIdentity.AccountID
   - Fingerprint-based comparison (not DN string matching)

5. Rate-limit/Replay protection: Stubbed for MVP (TODO)

Files changed:
- config/config.go: Added MTLSAccountAllowedIssuers
- mtls_auth.go: Added ValidateIssuerCA, MTLSConfig updated
- shared/mtls/identity.go: ValidatorConfig, ValidateIssuerCA
- shared/grpc/machine_tunnel.go: Full implementation
- server/peer/peer.go: Extended PeerSystemMeta with mTLS fields

Closes #32

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Implements unique DNS label generation for mTLS-authenticated peers
to prevent hostname collisions across different domains.

Features:
- GenerateUniqueDNSLabel: Creates FQDN-hash based labels
  Example: "win10-pc.customer-a.local" -> "win10-pc-a1b2c3d4"
- ValidateDNSLabel: RFC 1123 compliance check
- sanitizeForDNS: Hostname sanitization (underscores, spaces -> hyphens)
- CheckDNSLabelCollision: Helper for collision detection

Technical details:
- 32-bit SHA256 hash suffix (8 hex chars) for ~0.001% collision rate
- Automatic hostname truncation for labels > 63 chars
- Case-insensitive FQDN hashing
- Fallback to IP-based label on validation failure

Integration:
- AddPeer in peer.go now uses hash-based labels for mTLS peers
- Detection via peer.Meta.CertDNSName and peer.Meta.CertDomain fields

Unit tests:
- Uniqueness across domains/hostnames
- Truncation for long hostnames
- RFC 1123 validation (all edge cases)
- Sanitization (underscores, spaces, special chars)

Closes #33

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Add MTLSServer type with RequireAndVerifyClientCert on port 33074
- Add MTLSPort config option for dedicated mTLS-only server
- Integrate mTLS server lifecycle into BaseServer (Start/Stop)
- Add GetMTLSServer() for external service registration
- Load CA pool from directory (.crt/.pem/.cer) and/or single file
- Initialize mTLS validator config with account-issuer mappings
- TLS 1.2+ minimum required for mTLS connections

Port 33073 (standard): NoClientCert - user auth, setup keys
Port 33074 (mTLS): RequireAndVerifyClientCert - machine tunnel only

Closes #34

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Fix duplicate word 'LoginPeer' in comment (machine_tunnel.go)
- Convert if-else chains to switch statements (mtls_auth.go, peer.go)
- Add nolint directive for deprecated Audience field test (conversion_test.go)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
We had both .github/PULL_REQUEST_TEMPLATE.md (our custom) and
.github/pull_request_template.md (upstream). On macOS with its
case-insensitive filesystem, this causes git diff failures in CI.

Keep the upstream template (lowercase) for compatibility.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
We had both .github/PULL_REQUEST_TEMPLATE.md (our custom) and
.github/pull_request_template.md (upstream). On macOS with its
case-insensitive filesystem, this causes git diff failures in CI.

Keep the upstream template (lowercase) for compatibility.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
feat(server): Complete S-3 Server mTLS Implementation
Adds Dockerfile.multistage that builds the management server binary
inside a golang:1.25 container, solving the ar archive issue.

Problem: Building with `go build ./management/cmd/` produced an ar
archive instead of an ELF executable because cmd/ has `package cmd`
(library), not `package main`.

Solution: Use `go build ./management/` which contains main.go with
`package main` and `func main()`.

Benefits:
- No cross-compilation issues (builds inside Linux container)
- Produces correct ELF binary (~52MB)
- Smaller final image (ubuntu:24.04 base)
- Build flags: -ldflags="-s -w" for smaller binary

Usage:
  docker build -f management/Dockerfile.multistage -t netbird-fork/management:latest .

Relates to: #93 (T-3.9: Deploy Fork to Lab)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
…-5.1)

Implement Bootstrap() method that supports two-phase authentication:
- Phase 1: Setup-Key authentication for initial enrollment (before cert)
- Phase 2: mTLS authentication with machine certificate (after AD CS enrollment)

Components:
- bootstrap.go: Main bootstrap logic with hasMachineCert() check
- bootstrap_test.go: Unit tests for all edge cases (15 tests passing)

The bootstrap automatically selects the appropriate auth method:
- If MachineCertEnabled and valid cert exists: use mTLS via RegisterMachinePeer RPC
- Otherwise: fall back to Setup-Key via standard Login/Register RPC

Closes #47

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Implement DC connectivity checks and domain join helpers:
- CheckDCConnectivity: Validates LDAP, Kerberos, DNS, SMB, NTP ports
- ValidatePreJoinRequirements: Pre-join checklist with all requirements
- GenerateDomainJoinScript: Generates PowerShell script for domain join

PowerShell bootstrap script (scripts/bootstrap-new-client.ps1):
- Full Phase 1 → Domain Join → Cert → Phase 2 workflow
- NTP sync with public NTP (pre-tunnel) and DC (pre-join)
- DC connectivity verification via tunnel
- Certificate enrollment via AD CS (certreq)
- Config update for mTLS transition

Tests: 18 new tests for DC connectivity and domain join (all passing)

Closes #48

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Use net.JoinHostPort() for TCP and UDP port checks (IPv6 compatible)
- Extract credential prompt to constant with nolint directive
- The prompt message is NOT a credential, just UI text

Part of T-5.2

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
feat(build): Add multi-stage Dockerfile for management server
…-fallback

feat(client): Add machine tunnel bootstrap and domain join (T-5.1, T-5.2)
- Add ValidateMachineCertificate() for machine cert validation
- Add GenerateCertEnrollmentScript() for AD CS enrollment via certreq
- Add ParseCertificateFile() for cert info extraction
- Add NeedsRenewal() for certificate renewal detection
- Add WatchCertificateExpiry() for proactive renewal monitoring
- Add ExtractIssuerFingerprint() for mTLS issuer verification
- 32 tests covering all cert validation scenarios

Validates:
- SAN DNSNames (not CN!) matching hostname.domain format
- Certificate expiry and minimum validity
- Renewal threshold (30 days before expiry)
- Case-insensitive hostname matching
- Certificate chain for issuer fingerprint

Closes T-5.3

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Add comprehensive PowerShell scripts for test environment management:

- reset-netbird-machine.ps1: Safely reset NetBird Machine Tunnel
  - Stops and removes service
  - Removes WireGuard interface
  - SCOPED NRPT cleanup (only NetBird-Machine-* prefix, not all rules!)
  - SCOPED firewall rule cleanup
  - Optional config backup

- verify-nrpt-cleanup.ps1: Verify NRPT cleanup
  - Checks both registry paths (Policy and Dnscache)
  - Checks PowerShell Get-DnsClientNrptRule
  - Reports any remaining NetBird rules

- reinstall-and-test.ps1: Automated reinstall and test cycle
  - Full reset -> install -> start -> verify workflow
  - Waits for tunnel establishment
  - Basic connectivity tests

CRITICAL: Uses Registry-based scoped cleanup to avoid removing
other NRPT rules (GPO, VPN, etc.)

Closes T-5.5

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
feat(scripts): Add reset and test scripts for Windows VM testing (T-5.5)
feat(tunnel): Add certificate enrollment after domain join (T-5.3)
- Update to v2.0.0 with Smart Cert Selection (no thumbprint needed)
- Add REVOKE Setup-Key warning at script end (Step 8)
- Redact Setup-Key in logs (show only last 4 chars: ****-****-****-****-XXXX)
- Add security documentation in .NOTES:
  - SHA256 checksum verification instructions
  - Authenticode signing instructions
  - Setup-Key handling best practices
- Step 7 now uses machine_cert_template_name + machine_cert_san_must_match
- Remove hardcoded thumbprint requirement

Tested on Windows VM in WhatIf mode - all 8 steps execute correctly.

Closes #50

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
@CLAassistant
Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

@obtFusi
Copy link
Copy Markdown
Author

obtFusi commented Jan 25, 2026

Created in wrong repo, recreating in fork

@obtFusi obtFusi closed this Jan 25, 2026
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Jan 25, 2026

Caution

Review failed

The pull request is closed.

📝 Walkthrough

Walkthrough

Implements Windows pre-login machine tunnel support via two-phase mTLS authentication. Adds client-side bootstrap logic (Setup-Key Phase 1, mTLS Phase 2), server-side mTLS gRPC infrastructure, certificate enrollment utilities, domain controller connectivity checks, and PowerShell automation scripts for lab setup and deployment.

Changes

Cohort / File(s) Summary
Git Hooks & Pre-commit Enforcement
.githooks/pre-commit, Makefile
Adds gofmt formatting check and secrets pattern detection for staged Go files; updates Makefile to apply executable permission to pre-commit hook alongside existing pre-push hook.
GitHub Issue Templates & Workflows
.github/ISSUE_TEMPLATE/{bug_report,epic,feature_request,story,task}.md, .github/ISSUE_TEMPLATE/config.yml, .github/workflows/{auto-label,pr-lint}.yml
Adds German-language issue templates for bugs, epics, features, stories, and tasks; defines template config with contact links; introduces auto-labeling workflow for issues/PRs and conventional-commits linter for PR titles.
Repository Configuration
.gitignore, .github/dependabot.yml
Narrows VSCode folder ignore while broadening coverage for secrets (.key, .pem, cert files), build artifacts, OS ephemeral files; adds Dependabot config for Go modules, GitHub Actions, and Docker.
Client Bootstrap Implementation
client/internal/tunnel/bootstrap.go, client/internal/tunnel/bootstrap_test.go
Implements two-phase authentication: Setup-Key (Phase 1) fallback and mTLS (Phase 2) primary path with machine certificate validation; includes cert loading, MTLS URL construction, and server config retrieval. Comprehensive unit tests cover cert validation, URL parsing, and bootstrap pathways.
Certificate Enrollment & Management
client/internal/tunnel/certenroll.go, client/internal/tunnel/certenroll_test.go
Adds machine certificate validation (PEM parsing, SAN DNSNames, expiry checks, thumbprint computation), renewal decision logic, PowerShell enrollment script generation, certificate info parsing, expiry watching, and issuer fingerprint extraction. Extensive tests validate cert lifecycle and parsing.
Domain Join & DC Connectivity
client/internal/tunnel/domainjoin.go, client/internal/tunnel/domainjoin_test.go
Implements DC reachability validation (LDAP, LDAPS, Kerberos, DNS, SMB, NTP), pre-join requirement checks, and domain join PowerShell script generation. Tests cover port connectivity, timeout handling, and join readiness states.
Management Server mTLS Configuration
management/internals/server/config/config.go, management/internals/server/boot.go
Extends HttpServerConfig with mTLS fields (enabled flag, port, CA cert/dir, strict mode, domain-to-account mappings); refactors gRPC server initialization to conditionally load mTLS config and integrate interceptors.
mTLS Authentication & Validation
management/internals/server/mtls_auth.go, management/internals/server/mtls_auth_test.go
Implements comprehensive mTLS authentication layer: interceptors for unary/stream calls, identity extraction from TLS certificates (SAN DNSNames, domain parsing, issuer validation), peer type determination (machine/user), and template OID/name parsing. Extensive tests validate identity extraction, domain mapping, and OID decoding.
Dedicated mTLS Server
management/internals/server/mtls_server.go, management/internals/server/server.go
Introduces standalone mTLS-only gRPC server on separate port (default 33074) with CA pool loading, TLS configuration, and lifecycle management; integrates into main server startup/shutdown.
Machine Tunnel RPC Handlers
management/internals/shared/grpc/machine_tunnel.go
Implements mTLS-secured gRPC methods: RegisterMachinePeer (peer registration with issuer validation), SyncMachinePeer (placeholder), GetMachineRoutes (DC routes), ReportMachineStatus (status acknowledgment). Includes peer metadata extraction and audit field enrichment.
Shared mTLS Utilities
management/internals/shared/mtls/{identity,dnslabel}.go, management/internals/shared/mtls/*_test.go
Provides mTLS identity struct with multi-tenant fields, context helpers, issuer CA validation logic; implements RFC 1123-compliant DNS label generation with SHA-256 hash suffix, validation, sanitization, and collision detection.
Protocol Definitions
shared/management/proto/management.proto
Adds new machine tunnel RPC methods (RegisterMachinePeer, SyncMachinePeer, GetMachineRoutes, ReportMachineStatus) and supporting message types (MachineIdentity, MachineRegisterRequest/Response, etc.); updates EncryptedMessage with wgPubKey field.
Peer Metadata Extensions
management/server/peer.go, management/server/peer/peer.go
Integrates mTLS DNS label generation from cert domain/hostname; adds mTLS audit metadata fields to PeerSystemMeta (PeerType, AuthMethod, CertDNSName, CertDomain, CertIssuerFP, CertSerial, CertTemplate, auth timestamps).
Windows PowerShell Bootstrap Scripts
scripts/bootstrap-new-client.ps1, scripts/reset-netbird-machine.ps1, scripts/reinstall-and-test.ps1, scripts/verify-nrpt-cleanup.ps1
Comprehensive automation suite: bootstrap orchestrates Phase 1→2 workflow (NTP sync, tunnel setup, DC connectivity, domain join, cert enrollment); reset cleans service/interface/NRPT/firewall; reinstall validates service/interface startup; verify-nrpt ensures cleanup.
Lab Setup & Testing Scripts
scripts/lab/{setup-lab-ca,test-client-enrollment,verify-lab-ca}.ps1, scripts/lab/autounattend.xml
Provides lab infrastructure automation: setup-lab-ca installs AD CS and creates NetBirdMachine template with auto-enrollment GPO; test-client-enrollment validates machine cert enrollment via scheduled task; verify-lab-ca checks CA readiness; autounattend.xml automates Windows Server 2025 Datacenter deployment and OpenSSH setup.
Architecture & Design Documentation
docs/ADR-001-mTLS-Port-Strategy.md, docs/ADR-002-CNG-Signer-Interface.md
ADR-001 documents mTLS port strategy (single port with per-method routing vs dual ports decision); ADR-002 specifies Windows CNG-based crypto.Signer for non-exportable machine certificates (API surface, Windows API calls, test requirements).
Spike Implementations
spike/cng-signer/{main,go.mod}, spike/san-parser/{main,go.mod}
Proof-of-concept implementations: CNG signer demonstrates crypto.Signer integration with Windows certificate store and NCryptSignHash for RSA signing; SAN parser extracts certificate metadata (DNSNames, template OID/name, peer type) from AD CS certificates.
Test Certificates & Keys
test/certs/{ca,client,server}.{crt,key,csr,cnf,srl}
Adds test certificate infrastructure: CA, client, and server certificates with SAN extensions, private keys, CSR configs, and CA serial tracking for mTLS testing.
Minor Test Updates
management/internals/shared/grpc/conversion_test.go
Adds nolint directive to suppress deprecation warning for existing assertion.
Dockerfile
management/Dockerfile.multistage
Introduces multi-stage Dockerfile for management component: builder stage compiles netbird-mgmt binary; runtime stage packages binary into minimal Ubuntu 24.04 image.

Sequence Diagram(s)

sequenceDiagram
    actor Client as Windows Client
    participant Phase1 as Bootstrap Phase 1<br/>(Setup-Key)
    participant Mgmt as Management Server<br/>(Port 443)
    participant CA as Certificate Authority<br/>(AD CS)
    participant Phase2 as Bootstrap Phase 2<br/>(mTLS)
    participant Tunnel as MTLS Server<br/>(Port 33074)

    Client->>Phase1: Bootstrap(cfg) with Setup-Key
    Phase1->>Mgmt: Connect via standard mgmt client
    Mgmt->>Phase1: Validate Setup-Key & login/register
    Phase1->>Client: Return peer config & netbird config
    Client->>Client: Store peer config
    
    rect rgba(200, 150, 100, 0.5)
    Note over Client,CA: Phase 1 Complete - Tunnel established
    Client->>Client: Initiate domain join workflow
    Client->>CA: Request machine certificate via certreq
    CA->>CA: Validate request (template, auto-enrollment)
    CA->>Client: Issue machine certificate
    Client->>Client: Store cert in Windows cert store
    end
    
    Client->>Phase2: Bootstrap(cfg) with machine cert
    Phase2->>Phase2: Validate cert (SAN, expiry, thumbprint)
    Phase2->>Tunnel: mTLS connect with client cert
    Tunnel->>Tunnel: Verify client certificate
    Tunnel->>Tunnel: Extract identity from SAN/Extensions<br/>(hostname, domain, issuer, template)
    Phase2->>Tunnel: RegisterMachinePeer(identity + pubkey)
    Tunnel->>Mgmt: Validate issuer CA & account mapping
    Mgmt->>Tunnel: Account/domain validation result
    Tunnel->>Tunnel: Register machine peer with audit metadata
    Tunnel->>Phase2: Return bootstrap result<br/>(peer config, DC routes, DNS)
    Phase2->>Client: Complete Phase 2 setup
    Client->>Client: Update config with mTLS settings
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • [management] pass config to controller #4807 — Extends controller/gRPC configuration with additional HTTP/device-flow config parameters and ToSyncResponse plumbing, overlapping with management server config and protocol updates in this PR.
  • [client,management] Rewrite the SSH feature #4015 — Involves substantial client/server SSH subsystem refactoring (SSH config, BuildManager API, proto definitions) that parallels the architectural changes to authentication and peer registration infrastructure in this PR.

Poem

🐰 A rabbit hops through tunnels secure,
With certs and keys, a lock so pure,
Two phases dance—first Setup, then mTLS grace,
Domain joins spinning at a faster pace,
Windows machines now trust the way,
Pre-login magic saves the day!

✨ Finishing touches
  • 📝 Generate docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@sonarqubecloud
Copy link
Copy Markdown

Quality Gate Failed Quality Gate failed

Failed conditions
12 New issues
3 Security Hotspots
C Security Rating on New Code (required ≥ A)
10 New Code Smells (required ≤ 0)

See analysis details on SonarQube Cloud

Catch issues before they fail your Quality Gate with our IDE extension SonarQube for IDE

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Panic when unable to add-peer due to permissions

2 participants