Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

⭐️ new login and logout subcommands #141

Merged
merged 1 commit into from
Oct 22, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
254 changes: 254 additions & 0 deletions apps/cnspec/cmd/login.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,254 @@
package cmd

import (
"context"
"net/http"
"strings"
"time"

"github.com/rs/zerolog/log"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"go.mondoo.com/cnquery"
cnquery_config "go.mondoo.com/cnquery/apps/cnquery/cmd/config"
"go.mondoo.com/cnquery/cli/config"
"go.mondoo.com/cnquery/cli/sysinfo"
"go.mondoo.com/cnquery/upstream"
"go.mondoo.com/ranger-rpc"
"go.mondoo.com/ranger-rpc/plugins/authentication/statictoken"
"go.mondoo.com/ranger-rpc/plugins/scope"
)

func init() {
rootCmd.AddCommand(loginCmd)
loginCmd.Flags().StringP("token", "t", "", "Set a client registration token")
loginCmd.Flags().String("name", "", "Set asset name")
loginCmd.Flags().String("api-endpoint", "", "Set the Mondoo API endpoint")
}

var loginCmd = &cobra.Command{
Use: "login",
Aliases: []string{"register"},
Short: "Register with Mondoo Platform",
Long: `
Log in to Mondoo platform by using a registration token. To pass in the token, use
the '--token' flag.

You can generate a new registration token via the Mondoo Dashboard
https://console.mondoo.com -> Space -> Settings -> Registration Token. Copy the token and pass it in
as the '--token' argument.

Every client remains logged in until you explicitly log out. You can
log out by using 'lgoout' subcommand.
`,
PreRun: func(cmd *cobra.Command, args []string) {
viper.BindPFlag("api_endpoint", cmd.Flags().Lookup("api-endpoint"))
viper.BindPFlag("name", cmd.Flags().Lookup("name"))
},
Run: func(cmd *cobra.Command, args []string) {
token, _ := cmd.Flags().GetString("token")
register(token)
},
}

func register(token string) {
var err error
var credential *upstream.ServiceAccountCredentials

// determine information about the client
sysInfo, err := sysinfo.GatherSystemInfo()
if err != nil {
log.Fatal().Err(err).Msg("could not gather client information")
}
defaultPlugins := defaultRangerPlugins(sysInfo, cnquery.DefaultFeatures)

apiEndpoint := viper.GetString("api_endpoint")
token = strings.TrimSpace(token)

// we handle three cases here:
// 1. user has a token provided
// 2. user has no token provided, but has a service account file is already there
//
if token != "" {
// print token details
claims, err := upstream.ExtractTokenClaims(token)
if err != nil {
log.Warn().Err(err).Msg("could not read the token")
} else {
if len(claims.Description) > 0 {
log.Info().Msg("token description: " + claims.Description)
}
if claims.IsExpired() {
log.Warn().Msg("token is expired")
} else {
log.Info().Msg("token will expire at " + claims.Claims.Expiry.Time().Format(time.RFC1123))
}

if apiEndpoint == "" {
apiEndpoint = claims.ApiEndpoint
}
}

// gather service account
plugins := []ranger.ClientPlugin{}
plugins = append(plugins, defaultPlugins...)
plugins = append(plugins, statictoken.NewRangerPlugin(token))

client, err := upstream.NewAgentManagerClient(apiEndpoint, ranger.DefaultHttpClient(), plugins...)
if err != nil {
log.Fatal().Err(err).Msg("could not connect to mondoo platform")
}

name := viper.GetString("name")
if name == "" {
name = sysInfo.Hostname
}

confirmation, err := client.RegisterAgent(context.Background(), &upstream.AgentRegistrationRequest{
Token: token,
Name: name,
AgentInfo: &upstream.AgentInfo{
Mrn: "",
Version: sysInfo.Version,
Build: sysInfo.Build,
PlatformName: sysInfo.Platform.Name,
PlatformRelease: sysInfo.Platform.Version,
PlatformArch: sysInfo.Platform.Arch,
PlatformIp: sysInfo.IP,
PlatformHostname: sysInfo.Hostname,
Labels: nil,
PlatformId: sysInfo.PlatformId,
},
})
if err != nil {
log.Fatal().Err(err).Msg("failed to log in client")
}

log.Debug().Msg("store configuration")
// overwrite force, otherwise it will be stored
viper.Set("force", false)

// update configuration file, api-endpoint is set automatically
viper.Set("agent_mrn", confirmation.AgentMrn)
viper.Set("api_endpoint", confirmation.Credential.ApiEndpoint)
viper.Set("space_mrn", confirmation.Credential.GetParentMrn())
viper.Set("mrn", confirmation.Credential.Mrn)
viper.Set("private_key", confirmation.Credential.PrivateKey)
viper.Set("certificate", confirmation.Credential.Certificate)

credential = confirmation.Credential
} else {
// try to read local options
opts, optsErr := cnquery_config.ReadConfig()
if optsErr != nil {
log.Fatal().Msg("could not load configuration, please use --token or --config with the appropriate values")
}

// print the used config to the user
config.DisplayUsedConfig()

if opts.AgentMrn != "" {
// already authenticated
log.Info().Msg("client is already logged in, skip")
credential = opts.GetServiceCredential()
} else {
credential = opts.GetServiceCredential()

// run ping pong
plugins := []ranger.ClientPlugin{}
plugins = append(plugins, defaultPlugins...)
certAuth, err := upstream.NewServiceAccountRangerPlugin(credential)
if err != nil {
log.Warn().Err(err).Msg("could not initialize certificate authentication")
}
plugins = append(plugins, certAuth)

client, err := upstream.NewAgentManagerClient(apiEndpoint, ranger.DefaultHttpClient(), plugins...)
if err != nil {
log.Fatal().Err(err).Msg("could not connect to Mondoo Platform")
}

name := viper.GetString("name")
if name == "" {
name = sysInfo.Hostname
}

confirmation, err := client.RegisterAgent(context.Background(), &upstream.AgentRegistrationRequest{
Name: name,
AgentInfo: &upstream.AgentInfo{
Mrn: opts.AgentMrn,
Version: sysInfo.Version,
Build: sysInfo.Build,
PlatformName: sysInfo.Platform.Name,
PlatformRelease: sysInfo.Platform.Version,
PlatformArch: sysInfo.Platform.Arch,
PlatformIp: sysInfo.IP,
PlatformHostname: sysInfo.Hostname,
Labels: opts.Labels,
PlatformId: sysInfo.PlatformId,
},
})
if err != nil {
log.Fatal().Err(err).Msg("failed to log in client")
}

// update configuration file, api-endpoint is set automatically
// NOTE: we ignore the credentials from confirmation since the service never returns the credentials again
viper.Set("agent_mrn", confirmation.AgentMrn)
}
}

err = config.StoreConfig()
if err != nil {
log.Fatal().Err(err).Msg("could not write mondoo configuration")
}

// run ping pong to validate the service account
plugins := []ranger.ClientPlugin{}
plugins = append(plugins, defaultPlugins...)
certAuth, err := upstream.NewServiceAccountRangerPlugin(credential)
if err != nil {
log.Warn().Err(err).Msg("could not initialize certificate authentication")
}
plugins = append(plugins, certAuth)
client, err := upstream.NewAgentManagerClient(apiEndpoint, ranger.DefaultHttpClient(), plugins...)
if err != nil {
log.Fatal().Err(err).Msg("could not connect to mondoo platform")
}

_, err = client.PingPong(context.Background(), &upstream.Ping{})
if err != nil {
log.Fatal().Msg(err.Error())
}

log.Info().Msgf("client %s has logged in successfully", viper.Get("agent_mrn"))
}

func defaultRangerPlugins(sysInfo *sysinfo.SystemInfo, features cnquery.Features) []ranger.ClientPlugin {
plugins := []ranger.ClientPlugin{}
plugins = append(plugins, scope.NewRequestIDRangerPlugin())
plugins = append(plugins, sysInfoHeader(sysInfo, features))
return plugins
}

func sysInfoHeader(sysInfo *sysinfo.SystemInfo, features cnquery.Features) ranger.ClientPlugin {
const (
HttpHeaderUserAgent = "User-Client"
HttpHeaderClientFeatures = "Mondoo-Features"
HttpHeaderPlatformID = "Mondoo-PlatformID"
)

h := http.Header{}
h.Set(HttpHeaderUserAgent, scope.XInfoHeader(map[string]string{
"cnquery": cnquery.Version,
"build": cnquery.Build,
"PN": sysInfo.Platform.Name,
"PR": sysInfo.Platform.Version,
"PA": sysInfo.Platform.Arch,
"IP": sysInfo.IP,
"HN": sysInfo.Hostname,
}))
h.Set(HttpHeaderClientFeatures, features.Encode())
h.Set(HttpHeaderPlatformID, sysInfo.PlatformId)
return scope.NewCustomHeaderRangerPlugin(h)
}
123 changes: 123 additions & 0 deletions apps/cnspec/cmd/logout.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
package cmd

import (
"context"
"os"

"github.com/rs/zerolog/log"
"github.com/spf13/cobra"
"github.com/spf13/viper"
cnquery_cmd "go.mondoo.com/cnquery/apps/cnquery/cmd"
cnquery_config "go.mondoo.com/cnquery/apps/cnquery/cmd/config"
"go.mondoo.com/cnquery/cli/config"
"go.mondoo.com/cnquery/cli/sysinfo"
"go.mondoo.com/cnquery/upstream"
"go.mondoo.com/ranger-rpc"
"sigs.k8s.io/yaml"
)

func init() {
rootCmd.AddCommand(logoutCmd)
logoutCmd.Flags().Bool("force", false, "Force re-authentication")
}

var logoutCmd = &cobra.Command{
Use: "logout",
Aliases: []string{"unregister"},
Short: "Log out from Mondoo Platform",
Long: `
This process also initiates a revocation of the client's service account to ensure
the credentials cannot be used in future anymore.
`,
PreRun: func(cmd *cobra.Command, args []string) {
viper.BindPFlag("force", cmd.Flags().Lookup("force"))
},
Run: func(cmd *cobra.Command, args []string) {
var err error

// its perfectly fine not to have a config here, therefore we ignore errors
opts, optsErr := cnquery_config.ReadConfig()
if optsErr != nil {
log.Fatal().Msg("could not load configuration")
}

// print the used config to the user
config.DisplayUsedConfig()

// determine information about the client
sysInfo, err := sysinfo.GatherSystemInfo()
if err != nil {
log.Fatal().Err(err).Msg("could not gather client information")
}

// check valid client authentication
serviceAccount := opts.GetServiceCredential()
if serviceAccount == nil {
log.Error().Err(err).Msg("could not initialize client authentication")
os.Exit(cnquery_cmd.ConfigurationErrorCode)
}

plugins := defaultRangerPlugins(sysInfo, opts.GetFeatures())
certAuth, err := upstream.NewServiceAccountRangerPlugin(serviceAccount)
if err != nil {
log.Error().Err(err).Msg("could not initialize client authentication")
os.Exit(cnquery_cmd.ConfigurationErrorCode)
}
plugins = append(plugins, certAuth)

client, err := upstream.NewAgentManagerClient(opts.UpstreamApiEndpoint(), ranger.DefaultHttpClient(), plugins...)
if err != nil {
log.Error().Err(err).Msg("could not initialize client authentication")
os.Exit(cnquery_cmd.ConfigurationErrorCode)
}

if !viper.GetBool("force") {
log.Info().Msg("are you sure you want to revoke client access to Mondoo Platform? Use --force if you are sure")
os.Exit(1)
return
}

// try to load config into credentials struct
credentials := opts.GetServiceCredential()

// if we have credentials, we are going to self-destroy
ctx := context.Background()
if credentials != nil && len(credentials.Mrn) > 0 {
_, err = client.PingPong(ctx, &upstream.Ping{})

if err == nil {
log.Info().Msgf("client %s authenticated successfully", credentials.Mrn)

// un-register the agent
_, err = client.UnRegisterAgent(ctx, &upstream.Mrn{
Mrn: opts.AgentMrn,
})
if err != nil {
log.Error().Err(err).Msg("failed to unregister client")
}
} else {
log.Error().Err(err).Msg("communication with Mondoo Platform failed")
}
}

// delete config if it exists
path := viper.ConfigFileUsed()
fi, err := os.Stat(path)
if err == nil {
log.Debug().Str("path", path).Msg("remove client information from config")

opts.AgentMrn = ""

data, err := yaml.Marshal(opts)
if err != nil {
log.Error().Err(err).Msg("could not update Mondoo config")
}
err = os.WriteFile(path, data, fi.Mode())
if err != nil {
log.Error().Err(err).Msg("could not update Mondoo config")
}
}

log.Info().Msgf("Bye bye space cowboy, client %s unregistered successfully", credentials.Mrn)
},
}