2021-05-01 12:45:37 +02:00
package cmd
import (
2022-03-08 14:47:55 +01:00
"context"
2022-05-22 18:53:47 +02:00
"errors"
2021-05-01 12:45:37 +02:00
"fmt"
2022-05-22 18:53:47 +02:00
"io"
"io/fs"
2021-05-01 12:45:37 +02:00
"os"
"os/signal"
2022-05-22 18:53:47 +02:00
"path"
2021-06-20 23:01:44 +02:00
"runtime"
2021-11-15 09:11:50 +01:00
"strings"
2021-10-17 21:34:07 +02:00
"syscall"
2022-03-08 14:47:55 +01:00
"time"
"github.com/cenkalti/backoff/v4"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
2023-05-31 16:06:42 +02:00
"github.com/netbirdio/netbird/client/internal"
2021-05-01 12:45:37 +02:00
)
2023-01-17 19:16:50 +01:00
const (
2024-02-21 17:23:17 +01:00
externalIPMapFlag = "external-ip-map"
dnsResolverAddress = "dns-resolver-address"
enableRosenpassFlag = "enable-rosenpass"
rosenpassPermissiveFlag = "rosenpass-permissive"
preSharedKeyFlag = "preshared-key"
interfaceNameFlag = "interface-name"
wireguardPortFlag = "wireguard-port"
2024-05-07 18:50:34 +02:00
networkMonitorFlag = "network-monitor"
2024-02-21 17:23:17 +01:00
disableAutoConnectFlag = "disable-auto-connect"
serverSSHAllowedFlag = "allow-server-ssh"
2024-03-28 09:56:41 +01:00
extraIFaceBlackListFlag = "extra-iface-blacklist"
2024-06-13 13:24:24 +02:00
dnsRouteIntervalFlag = "dns-router-interval"
2023-01-17 19:16:50 +01:00
)
2021-05-01 12:45:37 +02:00
var (
2022-05-22 18:53:47 +02:00
configPath string
defaultConfigPathDir string
defaultConfigPath string
oldDefaultConfigPathDir string
oldDefaultConfigPath string
logLevel string
defaultLogFileDir string
defaultLogFile string
oldDefaultLogFileDir string
oldDefaultLogFile string
logFile string
daemonAddr string
managementURL string
adminURL string
setupKey string
2023-04-20 16:00:22 +02:00
hostName string
2022-05-22 18:53:47 +02:00
preSharedKey string
2023-01-17 19:16:50 +01:00
natExternalIPs [ ] string
customDNSAddress string
2024-01-08 12:25:35 +01:00
rosenpassEnabled bool
2024-02-21 17:23:17 +01:00
rosenpassPermissive bool
2024-02-20 11:13:27 +01:00
serverSSHAllowed bool
2024-01-15 15:53:23 +01:00
interfaceName string
wireguardPort uint16
2024-05-07 18:50:34 +02:00
networkMonitor bool
2024-03-12 18:29:19 +01:00
serviceName string
2024-02-20 10:10:05 +01:00
autoConnectDisabled bool
2024-03-28 09:56:41 +01:00
extraIFaceBlackList [ ] string
2024-04-26 17:20:10 +02:00
anonymizeFlag bool
2024-06-13 13:24:24 +02:00
dnsRouteInterval time . Duration
rootCmd = & cobra . Command {
2022-05-22 18:53:47 +02:00
Use : "netbird" ,
2022-05-12 11:17:24 +02:00
Short : "" ,
Long : "" ,
SilenceUsage : true ,
2021-05-01 12:45:37 +02:00
}
)
// Execute executes the root command.
func Execute ( ) error {
return rootCmd . Execute ( )
}
2021-07-17 14:38:59 +02:00
2022-03-08 14:47:55 +01:00
func init ( ) {
2022-05-22 18:53:47 +02:00
defaultConfigPathDir = "/etc/netbird/"
defaultLogFileDir = "/var/log/netbird/"
oldDefaultConfigPathDir = "/etc/wiretrustee/"
oldDefaultLogFileDir = "/var/log/wiretrustee/"
2021-06-20 23:01:44 +02:00
if runtime . GOOS == "windows" {
2022-05-22 18:53:47 +02:00
defaultConfigPathDir = os . Getenv ( "PROGRAMDATA" ) + "\\Netbird\\"
defaultLogFileDir = os . Getenv ( "PROGRAMDATA" ) + "\\Netbird\\"
oldDefaultConfigPathDir = os . Getenv ( "PROGRAMDATA" ) + "\\Wiretrustee\\"
oldDefaultLogFileDir = os . Getenv ( "PROGRAMDATA" ) + "\\Wiretrustee\\"
2021-06-20 23:01:44 +02:00
}
2021-08-18 13:35:42 +02:00
2022-05-22 18:53:47 +02:00
defaultConfigPath = defaultConfigPathDir + "config.json"
defaultLogFile = defaultLogFileDir + "client.log"
oldDefaultConfigPath = oldDefaultConfigPathDir + "config.json"
oldDefaultLogFile = oldDefaultLogFileDir + "client.log"
2023-05-31 16:06:42 +02:00
defaultDaemonAddr := "unix:///var/run/netbird.sock"
2022-03-08 14:47:55 +01:00
if runtime . GOOS == "windows" {
defaultDaemonAddr = "tcp://127.0.0.1:41731"
}
2024-03-12 18:29:19 +01:00
defaultServiceName := "netbird"
if runtime . GOOS == "windows" {
defaultServiceName = "Netbird"
}
2023-05-31 16:06:42 +02:00
rootCmd . PersistentFlags ( ) . StringVar ( & daemonAddr , "daemon-addr" , defaultDaemonAddr , "Daemon service address to serve CLI requests [unix|tcp]://[path|host:port]" )
rootCmd . PersistentFlags ( ) . StringVarP ( & managementURL , "management-url" , "m" , "" , fmt . Sprintf ( "Management Service URL [http|https]://[host]:[port] (default \"%s\")" , internal . DefaultManagementURL ) )
rootCmd . PersistentFlags ( ) . StringVar ( & adminURL , "admin-url" , "" , fmt . Sprintf ( "Admin Panel URL [http|https]://[host]:[port] (default \"%s\")" , internal . DefaultAdminURL ) )
2024-03-12 18:29:19 +01:00
rootCmd . PersistentFlags ( ) . StringVarP ( & serviceName , "service" , "s" , defaultServiceName , "Netbird system service name" )
2023-05-31 16:06:42 +02:00
rootCmd . PersistentFlags ( ) . StringVarP ( & configPath , "config" , "c" , defaultConfigPath , "Netbird config file location" )
rootCmd . PersistentFlags ( ) . StringVarP ( & logLevel , "log-level" , "l" , "info" , "sets Netbird log level" )
2023-11-10 16:33:13 +01:00
rootCmd . PersistentFlags ( ) . StringVar ( & logFile , "log-file" , defaultLogFile , "sets Netbird log path. If console is specified the log will be output to stdout" )
2023-05-31 16:06:42 +02:00
rootCmd . PersistentFlags ( ) . StringVarP ( & setupKey , "setup-key" , "k" , "" , "Setup key obtained from the Management Service Dashboard (used to register peer)" )
2023-12-14 11:48:12 +01:00
rootCmd . PersistentFlags ( ) . StringVar ( & preSharedKey , preSharedKeyFlag , "" , "Sets Wireguard PreSharedKey property. If set, then only peers that have the same key can communicate." )
2023-05-31 16:06:42 +02:00
rootCmd . PersistentFlags ( ) . StringVarP ( & hostName , "hostname" , "n" , "" , "Sets a custom hostname for the device" )
2024-04-26 17:20:10 +02:00
rootCmd . PersistentFlags ( ) . BoolVarP ( & anonymizeFlag , "anonymize" , "A" , false , "anonymize IP addresses and non-netbird.io domains in logs and status output" )
2024-04-23 14:42:53 +02:00
2021-06-19 14:55:45 +02:00
rootCmd . AddCommand ( serviceCmd )
2021-08-15 16:56:26 +02:00
rootCmd . AddCommand ( upCmd )
2022-03-08 14:47:55 +01:00
rootCmd . AddCommand ( downCmd )
rootCmd . AddCommand ( statusCmd )
2021-08-18 13:35:42 +02:00
rootCmd . AddCommand ( loginCmd )
2021-10-17 21:34:07 +02:00
rootCmd . AddCommand ( versionCmd )
2022-06-23 17:04:53 +02:00
rootCmd . AddCommand ( sshCmd )
2024-04-23 14:42:53 +02:00
rootCmd . AddCommand ( routesCmd )
2024-04-26 17:20:10 +02:00
rootCmd . AddCommand ( debugCmd )
2024-04-23 14:42:53 +02:00
2023-05-31 16:06:42 +02:00
serviceCmd . AddCommand ( runCmd , startCmd , stopCmd , restartCmd ) // service control commands are subcommands of service
serviceCmd . AddCommand ( installCmd , uninstallCmd ) // service installer commands are subcommands of service
2024-04-23 14:42:53 +02:00
routesCmd . AddCommand ( routesListCmd )
routesCmd . AddCommand ( routesSelectCmd , routesDeselectCmd )
2024-04-26 17:20:10 +02:00
debugCmd . AddCommand ( debugBundleCmd )
debugCmd . AddCommand ( logCmd )
logCmd . AddCommand ( logLevelCmd )
debugCmd . AddCommand ( forCmd )
2023-05-31 16:06:42 +02:00
upCmd . PersistentFlags ( ) . StringSliceVar ( & natExternalIPs , externalIPMapFlag , nil ,
` Sets external IPs maps between local addresses and interfaces. ` +
` You can specify a comma-separated list with a single IP and IP/IP or IP/Interface Name. ` +
` An empty string "" clears the previous configuration. ` +
` E.g. --external-ip-map 12.34.56.78/10.0.0.1 or --external-ip-map 12.34.56.200,12.34.56.78/10.0.0.1,12.34.56.80/eth1 ` +
` or --external-ip-map "" ` ,
)
upCmd . PersistentFlags ( ) . StringVar ( & customDNSAddress , dnsResolverAddress , "" ,
` Sets a custom address for NetBird's local DNS resolver. ` +
` If set, the agent won't attempt to discover the best ip and port to listen on. ` +
` An empty string "" clears the previous configuration. ` +
` E.g. --dns-resolver-address 127.0.0.1:5053 or --dns-resolver-address "" ` ,
)
2024-01-08 12:25:35 +01:00
upCmd . PersistentFlags ( ) . BoolVar ( & rosenpassEnabled , enableRosenpassFlag , false , "[Experimental] Enable Rosenpass feature. If enabled, the connection will be post-quantum secured via Rosenpass." )
2024-02-21 17:23:17 +01:00
upCmd . PersistentFlags ( ) . BoolVar ( & rosenpassPermissive , rosenpassPermissiveFlag , false , "[Experimental] Enable Rosenpass in permissive mode to allow this peer to accept WireGuard connections without requiring Rosenpass functionality from peers that do not have Rosenpass enabled." )
2024-02-20 11:13:27 +01:00
upCmd . PersistentFlags ( ) . BoolVar ( & serverSSHAllowed , serverSSHAllowedFlag , false , "Allow SSH server on peer. If enabled, the SSH server will be permitted" )
2024-02-20 10:10:05 +01:00
upCmd . PersistentFlags ( ) . BoolVar ( & autoConnectDisabled , disableAutoConnectFlag , false , "Disables auto-connect feature. If enabled, then the client won't connect automatically when the service starts." )
2021-05-01 12:45:37 +02:00
}
2021-05-15 12:33:07 +02:00
// SetupCloseHandler handles SIGTERM signal and exits with success
2022-03-25 13:21:04 +01:00
func SetupCloseHandler ( ctx context . Context , cancel context . CancelFunc ) {
termCh := make ( chan os . Signal , 1 )
signal . Notify ( termCh , os . Interrupt , syscall . SIGINT , syscall . SIGTERM )
2021-05-19 11:13:25 +02:00
go func ( ) {
2022-03-25 13:21:04 +01:00
done := ctx . Done ( )
select {
case <- done :
case <- termCh :
2021-05-19 11:13:25 +02:00
}
2022-03-25 13:21:04 +01:00
log . Info ( "shutdown signal received" )
cancel ( )
2021-05-19 11:13:25 +02:00
} ( )
2021-05-01 12:45:37 +02:00
}
2021-11-15 09:11:50 +01:00
// SetFlagsFromEnvVars reads and updates flag values from environment variables with prefix WT_
2023-01-17 19:16:50 +01:00
func SetFlagsFromEnvVars ( cmd * cobra . Command ) {
flags := cmd . PersistentFlags ( )
2021-11-15 09:11:50 +01:00
flags . VisitAll ( func ( f * pflag . Flag ) {
2022-05-22 18:53:47 +02:00
oldEnvVar := FlagNameToEnvVar ( f . Name , "WT_" )
if value , present := os . LookupEnv ( oldEnvVar ) ; present {
err := flags . Set ( f . Name , value )
if err != nil {
log . Infof ( "unable to configure flag %s using variable %s, err: %v" , f . Name , oldEnvVar , err )
}
}
newEnvVar := FlagNameToEnvVar ( f . Name , "NB_" )
2021-11-15 09:11:50 +01:00
2022-05-22 18:53:47 +02:00
if value , present := os . LookupEnv ( newEnvVar ) ; present {
2021-11-15 09:11:50 +01:00
err := flags . Set ( f . Name , value )
if err != nil {
2022-05-22 18:53:47 +02:00
log . Infof ( "unable to configure flag %s using variable %s, err: %v" , f . Name , newEnvVar , err )
2021-11-15 09:11:50 +01:00
}
}
} )
}
// FlagNameToEnvVar converts flag name to environment var name adding a prefix,
2022-05-22 18:53:47 +02:00
// replacing dashes and making all uppercase (e.g. setup-keys is converted to NB_SETUP_KEYS according to the input prefix)
func FlagNameToEnvVar ( cmdFlag string , prefix string ) string {
parsed := strings . ReplaceAll ( cmdFlag , "-" , "_" )
2021-11-15 09:11:50 +01:00
upper := strings . ToUpper ( parsed )
return prefix + upper
}
2022-03-08 14:47:55 +01:00
2024-02-20 11:13:27 +01:00
// DialClientGRPCServer returns client connection to the daemon server.
2022-03-08 14:47:55 +01:00
func DialClientGRPCServer ( ctx context . Context , addr string ) ( * grpc . ClientConn , error ) {
ctx , cancel := context . WithTimeout ( ctx , time . Second * 3 )
defer cancel ( )
return grpc . DialContext (
ctx ,
strings . TrimPrefix ( addr , "tcp://" ) ,
grpc . WithTransportCredentials ( insecure . NewCredentials ( ) ) ,
grpc . WithBlock ( ) ,
)
}
// WithBackOff execute function in backoff cycle.
func WithBackOff ( bf func ( ) error ) error {
return backoff . RetryNotify ( bf , CLIBackOffSettings , func ( err error , duration time . Duration ) {
log . Warnf ( "retrying Login to the Management service in %v due to error %v" , duration , err )
} )
}
// CLIBackOffSettings is default backoff settings for CLI commands.
var CLIBackOffSettings = & backoff . ExponentialBackOff {
InitialInterval : time . Second ,
RandomizationFactor : backoff . DefaultRandomizationFactor ,
Multiplier : backoff . DefaultMultiplier ,
MaxInterval : 10 * time . Second ,
MaxElapsedTime : 30 * time . Second ,
Stop : backoff . Stop ,
Clock : backoff . SystemClock ,
}
2022-05-22 18:53:47 +02:00
func handleRebrand ( cmd * cobra . Command ) error {
var err error
if logFile == defaultLogFile {
if migrateToNetbird ( oldDefaultLogFile , defaultLogFile ) {
cmd . Printf ( "will copy Log dir %s and its content to %s\n" , oldDefaultLogFileDir , defaultLogFileDir )
err = cpDir ( oldDefaultLogFileDir , defaultLogFileDir )
if err != nil {
return err
}
}
}
if configPath == defaultConfigPath {
if migrateToNetbird ( oldDefaultConfigPath , defaultConfigPath ) {
cmd . Printf ( "will copy Config dir %s and its content to %s\n" , oldDefaultConfigPathDir , defaultConfigPathDir )
err = cpDir ( oldDefaultConfigPathDir , defaultConfigPathDir )
if err != nil {
return err
}
}
}
return nil
}
func cpFile ( src , dst string ) error {
var err error
var srcfd * os . File
var dstfd * os . File
var srcinfo os . FileInfo
if srcfd , err = os . Open ( src ) ; err != nil {
return err
}
defer srcfd . Close ( )
if dstfd , err = os . Create ( dst ) ; err != nil {
return err
}
defer dstfd . Close ( )
if _ , err = io . Copy ( dstfd , srcfd ) ; err != nil {
return err
}
if srcinfo , err = os . Stat ( src ) ; err != nil {
return err
}
return os . Chmod ( dst , srcinfo . Mode ( ) )
}
func copySymLink ( source , dest string ) error {
link , err := os . Readlink ( source )
if err != nil {
return err
}
return os . Symlink ( link , dest )
}
func cpDir ( src string , dst string ) error {
var err error
2022-12-04 13:22:21 +01:00
var fds [ ] os . DirEntry
2022-05-22 18:53:47 +02:00
var srcinfo os . FileInfo
if srcinfo , err = os . Stat ( src ) ; err != nil {
return err
}
if err = os . MkdirAll ( dst , srcinfo . Mode ( ) ) ; err != nil {
return err
}
2022-12-04 13:22:21 +01:00
if fds , err = os . ReadDir ( src ) ; err != nil {
2022-05-22 18:53:47 +02:00
return err
}
for _ , fd := range fds {
srcfp := path . Join ( src , fd . Name ( ) )
dstfp := path . Join ( dst , fd . Name ( ) )
fileInfo , err := os . Stat ( srcfp )
if err != nil {
return fmt . Errorf ( "fouldn't get fileInfo; %v" , err )
}
switch fileInfo . Mode ( ) & os . ModeType {
case os . ModeSymlink :
if err = copySymLink ( srcfp , dstfp ) ; err != nil {
return fmt . Errorf ( "failed to copy from %s to %s; %v" , srcfp , dstfp , err )
}
case os . ModeDir :
if err = cpDir ( srcfp , dstfp ) ; err != nil {
return fmt . Errorf ( "failed to copy from %s to %s; %v" , srcfp , dstfp , err )
}
default :
if err = cpFile ( srcfp , dstfp ) ; err != nil {
return fmt . Errorf ( "failed to copy from %s to %s; %v" , srcfp , dstfp , err )
}
}
}
return nil
}
func migrateToNetbird ( oldPath , newPath string ) bool {
_ , errOld := os . Stat ( oldPath )
_ , errNew := os . Stat ( newPath )
if errors . Is ( errOld , fs . ErrNotExist ) || errNew == nil {
return false
}
return true
}
2024-04-26 17:20:10 +02:00
2024-06-06 10:59:10 +02:00
func getClient ( cmd * cobra . Command ) ( * grpc . ClientConn , error ) {
SetFlagsFromEnvVars ( rootCmd )
cmd . SetOut ( cmd . OutOrStdout ( ) )
conn , err := DialClientGRPCServer ( cmd . Context ( ) , daemonAddr )
2024-04-26 17:20:10 +02:00
if err != nil {
return nil , fmt . Errorf ( "failed to connect to daemon error: %v\n" +
"If the daemon is not running please run: " +
"\nnetbird service install \nnetbird service start\n" , err )
}
return conn , nil
}