2020-11-30 09:37:17 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
2021-02-02 13:15:13 +00:00
|
|
|
saferand "crypto/rand"
|
2021-12-29 13:08:47 +00:00
|
|
|
"encoding/csv"
|
2020-11-30 09:37:17 +00:00
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
|
|
|
"io/ioutil"
|
2021-02-02 13:15:13 +00:00
|
|
|
"math/big"
|
2020-11-30 09:37:17 +00:00
|
|
|
"os"
|
|
|
|
"strings"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/AlecAivazis/survey/v2"
|
|
|
|
"github.com/crowdsecurity/crowdsec/pkg/csconfig"
|
|
|
|
"github.com/crowdsecurity/crowdsec/pkg/database"
|
|
|
|
"github.com/denisbrodbeck/machineid"
|
|
|
|
"github.com/enescakir/emoji"
|
|
|
|
"github.com/go-openapi/strfmt"
|
|
|
|
"github.com/olekukonko/tablewriter"
|
|
|
|
"github.com/pkg/errors"
|
|
|
|
log "github.com/sirupsen/logrus"
|
|
|
|
"github.com/spf13/cobra"
|
|
|
|
"gopkg.in/yaml.v2"
|
|
|
|
)
|
|
|
|
|
|
|
|
var machineID string
|
|
|
|
var machinePassword string
|
|
|
|
var interactive bool
|
|
|
|
var apiURL string
|
|
|
|
var outputFile string
|
|
|
|
var forceAdd bool
|
|
|
|
var autoAdd bool
|
|
|
|
|
|
|
|
var (
|
|
|
|
passwordLength = 64
|
|
|
|
upper = "ABCDEFGHIJKLMNOPQRSTUVWXY"
|
|
|
|
lower = "abcdefghijklmnopqrstuvwxyz"
|
|
|
|
digits = "0123456789"
|
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
uuid = "/proc/sys/kernel/random/uuid"
|
|
|
|
)
|
|
|
|
|
|
|
|
func generatePassword(length int) string {
|
2021-02-02 13:15:13 +00:00
|
|
|
|
2020-11-30 09:37:17 +00:00
|
|
|
charset := upper + lower + digits
|
2021-02-02 13:15:13 +00:00
|
|
|
charsetLength := len(charset)
|
2020-11-30 09:37:17 +00:00
|
|
|
|
|
|
|
buf := make([]byte, length)
|
2021-02-02 13:15:13 +00:00
|
|
|
for i := 0; i < length; i++ {
|
|
|
|
rInt, err := saferand.Int(saferand.Reader, big.NewInt(int64(charsetLength)))
|
|
|
|
if err != nil {
|
|
|
|
log.Fatalf("failed getting data from prng for password generation : %s", err)
|
|
|
|
}
|
|
|
|
buf[i] = charset[rInt.Int64()]
|
2020-11-30 09:37:17 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return string(buf)
|
|
|
|
}
|
|
|
|
|
2022-03-24 10:07:54 +00:00
|
|
|
// Returns a unique identifier for each crowdsec installation, using an
|
|
|
|
// identifier of the OS installation where available, otherwise a random
|
|
|
|
// string.
|
|
|
|
func generateIDPrefix() (string, error) {
|
|
|
|
prefix, err := machineid.ID()
|
|
|
|
if err == nil {
|
|
|
|
return prefix, nil
|
2020-11-30 09:37:17 +00:00
|
|
|
}
|
2022-03-24 10:07:54 +00:00
|
|
|
log.Debugf("failed to get machine-id with usual files: %s", err)
|
|
|
|
|
|
|
|
bID, err := ioutil.ReadFile(uuid)
|
|
|
|
if err == nil {
|
|
|
|
return string(bID), nil
|
|
|
|
}
|
|
|
|
return "", errors.Wrap(err, "generating machine id")
|
|
|
|
}
|
|
|
|
|
|
|
|
// Generate a unique identifier, composed by a prefix and a random suffix.
|
|
|
|
// The prefix can be provided by a parameter to use in test environments.
|
|
|
|
func generateID(prefix string) (string, error) {
|
|
|
|
var err error
|
|
|
|
if prefix == "" {
|
|
|
|
prefix, err = generateIDPrefix()
|
|
|
|
}
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
2020-11-30 09:37:17 +00:00
|
|
|
}
|
2022-03-24 10:07:54 +00:00
|
|
|
prefix = strings.ReplaceAll(prefix, "-", "")[:32]
|
|
|
|
suffix := generatePassword(16)
|
|
|
|
return prefix + suffix, nil
|
2020-11-30 09:37:17 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func NewMachinesCmd() *cobra.Command {
|
|
|
|
/* ---- DECISIONS COMMAND */
|
|
|
|
var cmdMachines = &cobra.Command{
|
|
|
|
Use: "machines [action]",
|
2021-04-16 08:50:08 +00:00
|
|
|
Short: "Manage local API machines [requires local API]",
|
|
|
|
Long: `To list/add/delete/validate machines.
|
|
|
|
Note: This command requires database direct access, so is intended to be run on the local API machine.
|
2020-11-30 09:37:17 +00:00
|
|
|
`,
|
2021-08-31 13:03:47 +00:00
|
|
|
Example: `cscli machines [action]`,
|
|
|
|
DisableAutoGenTag: true,
|
2021-04-16 08:50:08 +00:00
|
|
|
PersistentPreRun: func(cmd *cobra.Command, args []string) {
|
|
|
|
if err := csConfig.LoadAPIServer(); err != nil || csConfig.DisableAPI {
|
2021-10-04 15:14:52 +00:00
|
|
|
if err != nil {
|
|
|
|
log.Errorf("local api : %s", err)
|
|
|
|
}
|
2021-04-16 08:50:08 +00:00
|
|
|
log.Fatal("Local API is disabled, please run this command on the local API machine")
|
|
|
|
}
|
2021-03-24 17:16:17 +00:00
|
|
|
if err := csConfig.LoadDBConfig(); err != nil {
|
2021-04-16 08:50:08 +00:00
|
|
|
log.Errorf("This command requires direct database access (must be run on the local API machine)")
|
2021-03-24 17:16:17 +00:00
|
|
|
log.Fatalf(err.Error())
|
|
|
|
}
|
|
|
|
},
|
2020-11-30 09:37:17 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
var cmdMachinesList = &cobra.Command{
|
2021-08-31 13:03:47 +00:00
|
|
|
Use: "list",
|
|
|
|
Short: "List machines",
|
|
|
|
Long: `List `,
|
|
|
|
Example: `cscli machines list`,
|
|
|
|
Args: cobra.MaximumNArgs(1),
|
|
|
|
DisableAutoGenTag: true,
|
2021-04-16 08:50:08 +00:00
|
|
|
PreRun: func(cmd *cobra.Command, args []string) {
|
2020-11-30 09:37:17 +00:00
|
|
|
var err error
|
|
|
|
dbClient, err = database.NewClient(csConfig.DbConfig)
|
|
|
|
if err != nil {
|
|
|
|
log.Fatalf("unable to create new database client: %s", err)
|
|
|
|
}
|
|
|
|
},
|
|
|
|
Run: func(cmd *cobra.Command, args []string) {
|
|
|
|
machines, err := dbClient.ListMachines()
|
|
|
|
if err != nil {
|
|
|
|
log.Errorf("unable to list blockers: %s", err)
|
|
|
|
}
|
|
|
|
if csConfig.Cscli.Output == "human" {
|
|
|
|
table := tablewriter.NewWriter(os.Stdout)
|
|
|
|
table.SetCenterSeparator("")
|
|
|
|
table.SetColumnSeparator("")
|
|
|
|
|
|
|
|
table.SetHeaderAlignment(tablewriter.ALIGN_LEFT)
|
|
|
|
table.SetAlignment(tablewriter.ALIGN_LEFT)
|
|
|
|
table.SetHeader([]string{"Name", "IP Address", "Last Update", "Status", "Version"})
|
|
|
|
for _, w := range machines {
|
|
|
|
var validated string
|
|
|
|
if w.IsValidated {
|
2022-03-09 15:15:18 +00:00
|
|
|
validated = emoji.CheckMark.String()
|
2020-11-30 09:37:17 +00:00
|
|
|
} else {
|
2022-03-09 15:15:18 +00:00
|
|
|
validated = emoji.Prohibited.String()
|
2020-11-30 09:37:17 +00:00
|
|
|
}
|
|
|
|
table.Append([]string{w.MachineId, w.IpAddress, w.UpdatedAt.Format(time.RFC3339), validated, w.Version})
|
|
|
|
}
|
|
|
|
table.Render()
|
|
|
|
} else if csConfig.Cscli.Output == "json" {
|
|
|
|
x, err := json.MarshalIndent(machines, "", " ")
|
|
|
|
if err != nil {
|
|
|
|
log.Fatalf("failed to unmarshal")
|
|
|
|
}
|
|
|
|
fmt.Printf("%s", string(x))
|
|
|
|
} else if csConfig.Cscli.Output == "raw" {
|
2021-12-29 13:08:47 +00:00
|
|
|
csvwriter := csv.NewWriter(os.Stdout)
|
|
|
|
err := csvwriter.Write([]string{"machine_id", "ip_address", "updated_at", "validated", "version"})
|
|
|
|
if err != nil {
|
|
|
|
log.Fatalf("failed to write header: %s", err)
|
|
|
|
}
|
2020-11-30 09:37:17 +00:00
|
|
|
for _, w := range machines {
|
|
|
|
var validated string
|
|
|
|
if w.IsValidated {
|
|
|
|
validated = "true"
|
|
|
|
} else {
|
|
|
|
validated = "false"
|
|
|
|
}
|
2021-12-29 13:08:47 +00:00
|
|
|
err := csvwriter.Write([]string{w.MachineId, w.IpAddress, w.UpdatedAt.Format(time.RFC3339), validated, w.Version})
|
|
|
|
if err != nil {
|
|
|
|
log.Fatalf("failed to write raw output : %s", err)
|
|
|
|
}
|
2020-11-30 09:37:17 +00:00
|
|
|
}
|
2021-12-29 13:08:47 +00:00
|
|
|
csvwriter.Flush()
|
2020-11-30 09:37:17 +00:00
|
|
|
} else {
|
|
|
|
log.Errorf("unknown output '%s'", csConfig.Cscli.Output)
|
|
|
|
}
|
|
|
|
},
|
|
|
|
}
|
|
|
|
cmdMachines.AddCommand(cmdMachinesList)
|
|
|
|
|
|
|
|
var cmdMachinesAdd = &cobra.Command{
|
2021-08-31 13:03:47 +00:00
|
|
|
Use: "add",
|
|
|
|
Short: "add machine to the database.",
|
|
|
|
DisableAutoGenTag: true,
|
|
|
|
Long: `Register a new machine in the database. cscli should be on the same machine as LAPI.`,
|
2020-11-30 09:37:17 +00:00
|
|
|
Example: `
|
|
|
|
cscli machines add --auto
|
|
|
|
cscli machines add MyTestMachine --auto
|
|
|
|
cscli machines add MyTestMachine --password MyPassword
|
|
|
|
`,
|
2021-04-16 08:50:08 +00:00
|
|
|
PreRun: func(cmd *cobra.Command, args []string) {
|
2020-11-30 09:37:17 +00:00
|
|
|
var err error
|
|
|
|
dbClient, err = database.NewClient(csConfig.DbConfig)
|
|
|
|
if err != nil {
|
|
|
|
log.Fatalf("unable to create new database client: %s", err)
|
|
|
|
}
|
|
|
|
},
|
|
|
|
Run: func(cmd *cobra.Command, args []string) {
|
|
|
|
var dumpFile string
|
|
|
|
var err error
|
|
|
|
|
2021-12-06 16:29:23 +00:00
|
|
|
// create machineID if not specified by user
|
2020-11-30 09:37:17 +00:00
|
|
|
if len(args) == 0 {
|
|
|
|
if !autoAdd {
|
2022-03-10 12:55:25 +00:00
|
|
|
printHelp(cmd)
|
2020-11-30 09:37:17 +00:00
|
|
|
return
|
|
|
|
}
|
2022-03-24 10:07:54 +00:00
|
|
|
machineID, err = generateID("")
|
2020-11-30 09:37:17 +00:00
|
|
|
if err != nil {
|
|
|
|
log.Fatalf("unable to generate machine id : %s", err)
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
machineID = args[0]
|
|
|
|
}
|
|
|
|
|
|
|
|
/*check if file already exists*/
|
|
|
|
if outputFile != "" {
|
|
|
|
dumpFile = outputFile
|
2021-07-23 13:10:43 +00:00
|
|
|
} else if csConfig.API.Client != nil && csConfig.API.Client.CredentialsFilePath != "" {
|
2020-11-30 09:37:17 +00:00
|
|
|
dumpFile = csConfig.API.Client.CredentialsFilePath
|
|
|
|
}
|
|
|
|
|
2022-03-24 10:07:54 +00:00
|
|
|
// create a password if it's not specified by user
|
2020-11-30 09:37:17 +00:00
|
|
|
if machinePassword == "" && !interactive {
|
|
|
|
if !autoAdd {
|
2022-03-10 12:55:25 +00:00
|
|
|
printHelp(cmd)
|
2020-11-30 09:37:17 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
machinePassword = generatePassword(passwordLength)
|
|
|
|
} else if machinePassword == "" && interactive {
|
|
|
|
qs := &survey.Password{
|
|
|
|
Message: "Please provide a password for the machine",
|
|
|
|
}
|
|
|
|
survey.AskOne(qs, &machinePassword)
|
|
|
|
}
|
|
|
|
password := strfmt.Password(machinePassword)
|
|
|
|
_, err = dbClient.CreateMachine(&machineID, &password, "", true, forceAdd)
|
|
|
|
if err != nil {
|
|
|
|
log.Fatalf("unable to create machine: %s", err)
|
|
|
|
}
|
2021-02-25 10:20:36 +00:00
|
|
|
log.Infof("Machine '%s' successfully added to the local API", machineID)
|
2020-11-30 09:37:17 +00:00
|
|
|
|
|
|
|
if apiURL == "" {
|
|
|
|
if csConfig.API.Client != nil && csConfig.API.Client.Credentials != nil && csConfig.API.Client.Credentials.URL != "" {
|
|
|
|
apiURL = csConfig.API.Client.Credentials.URL
|
|
|
|
} else if csConfig.API.Server != nil && csConfig.API.Server.ListenURI != "" {
|
|
|
|
apiURL = "http://" + csConfig.API.Server.ListenURI
|
|
|
|
} else {
|
|
|
|
log.Fatalf("unable to dump an api URL. Please provide it in your configuration or with the -u parameter")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
apiCfg := csconfig.ApiCredentialsCfg{
|
|
|
|
Login: machineID,
|
|
|
|
Password: password.String(),
|
|
|
|
URL: apiURL,
|
|
|
|
}
|
|
|
|
apiConfigDump, err := yaml.Marshal(apiCfg)
|
|
|
|
if err != nil {
|
|
|
|
log.Fatalf("unable to marshal api credentials: %s", err)
|
|
|
|
}
|
2022-01-07 15:53:56 +00:00
|
|
|
if dumpFile != "" && dumpFile != "-" {
|
2020-11-30 09:37:17 +00:00
|
|
|
err = ioutil.WriteFile(dumpFile, apiConfigDump, 0644)
|
|
|
|
if err != nil {
|
|
|
|
log.Fatalf("write api credentials in '%s' failed: %s", dumpFile, err)
|
|
|
|
}
|
|
|
|
log.Printf("API credentials dumped to '%s'", dumpFile)
|
|
|
|
} else {
|
|
|
|
fmt.Printf("%s\n", string(apiConfigDump))
|
|
|
|
}
|
|
|
|
},
|
|
|
|
}
|
|
|
|
cmdMachinesAdd.Flags().StringVarP(&machinePassword, "password", "p", "", "machine password to login to the API")
|
2022-02-01 09:34:53 +00:00
|
|
|
cmdMachinesAdd.Flags().StringVarP(&outputFile, "file", "f", "",
|
|
|
|
"output file destination (defaults to "+csconfig.DefaultConfigPath("local_api_credentials.yaml"))
|
2020-11-30 09:37:17 +00:00
|
|
|
cmdMachinesAdd.Flags().StringVarP(&apiURL, "url", "u", "", "URL of the local API")
|
|
|
|
cmdMachinesAdd.Flags().BoolVarP(&interactive, "interactive", "i", false, "interfactive mode to enter the password")
|
2021-03-10 13:58:19 +00:00
|
|
|
cmdMachinesAdd.Flags().BoolVarP(&autoAdd, "auto", "a", false, "automatically generate password (and username if not provided)")
|
2020-11-30 09:37:17 +00:00
|
|
|
cmdMachinesAdd.Flags().BoolVar(&forceAdd, "force", false, "will force add the machine if it already exist")
|
|
|
|
cmdMachines.AddCommand(cmdMachinesAdd)
|
|
|
|
|
|
|
|
var cmdMachinesDelete = &cobra.Command{
|
2021-08-31 13:03:47 +00:00
|
|
|
Use: "delete --machine MyTestMachine",
|
|
|
|
Short: "delete machines",
|
|
|
|
Example: `cscli machines delete "machine_name"`,
|
2021-09-02 10:23:06 +00:00
|
|
|
Args: cobra.MinimumNArgs(1),
|
2021-08-31 13:03:47 +00:00
|
|
|
DisableAutoGenTag: true,
|
2021-04-16 08:50:08 +00:00
|
|
|
PreRun: func(cmd *cobra.Command, args []string) {
|
2020-11-30 09:37:17 +00:00
|
|
|
var err error
|
|
|
|
dbClient, err = database.NewClient(csConfig.DbConfig)
|
|
|
|
if err != nil {
|
|
|
|
log.Fatalf("unable to create new database client: %s", err)
|
|
|
|
}
|
|
|
|
},
|
|
|
|
Run: func(cmd *cobra.Command, args []string) {
|
|
|
|
machineID = args[0]
|
2021-09-02 10:23:06 +00:00
|
|
|
for _, machineID := range args {
|
|
|
|
err := dbClient.DeleteWatcher(machineID)
|
|
|
|
if err != nil {
|
|
|
|
log.Errorf("unable to delete machine: %s", err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
log.Infof("machine '%s' deleted successfully", machineID)
|
2020-11-30 09:37:17 +00:00
|
|
|
}
|
|
|
|
},
|
|
|
|
}
|
|
|
|
cmdMachinesDelete.Flags().StringVarP(&machineID, "machine", "m", "", "machine to delete")
|
|
|
|
cmdMachines.AddCommand(cmdMachinesDelete)
|
|
|
|
|
|
|
|
var cmdMachinesValidate = &cobra.Command{
|
2021-08-31 13:03:47 +00:00
|
|
|
Use: "validate",
|
|
|
|
Short: "validate a machine to access the local API",
|
|
|
|
Long: `validate a machine to access the local API.`,
|
|
|
|
Example: `cscli machines validate "machine_name"`,
|
|
|
|
Args: cobra.ExactArgs(1),
|
|
|
|
DisableAutoGenTag: true,
|
2021-04-16 08:50:08 +00:00
|
|
|
PreRun: func(cmd *cobra.Command, args []string) {
|
2020-11-30 09:37:17 +00:00
|
|
|
var err error
|
|
|
|
dbClient, err = database.NewClient(csConfig.DbConfig)
|
|
|
|
if err != nil {
|
|
|
|
log.Fatalf("unable to create new database client: %s", err)
|
|
|
|
}
|
|
|
|
},
|
|
|
|
Run: func(cmd *cobra.Command, args []string) {
|
|
|
|
machineID = args[0]
|
|
|
|
if err := dbClient.ValidateMachine(machineID); err != nil {
|
|
|
|
log.Fatalf("unable to validate machine '%s': %s", machineID, err)
|
|
|
|
}
|
2021-12-06 16:29:23 +00:00
|
|
|
log.Infof("machine '%s' validated successfully", machineID)
|
2020-11-30 09:37:17 +00:00
|
|
|
},
|
|
|
|
}
|
|
|
|
cmdMachines.AddCommand(cmdMachinesValidate)
|
|
|
|
|
|
|
|
return cmdMachines
|
|
|
|
}
|