Skip to content
This repository has been archived by the owner on Jul 25, 2022. It is now read-only.

OIDC md5sum check #490

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ require (
github.com/onsi/gomega v1.7.0
github.com/pkg/browser v0.0.0-20180916011732-0a3d74bf9ce4
github.com/spf13/cobra v0.0.6
github.com/srfrog/slices v1.0.1
golang.org/x/lint v0.0.0-20191125180803-fdd1cda4f05f
gopkg.in/yaml.v2 v2.2.8
k8s.io/api v0.17.0
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -534,6 +534,8 @@ github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An
github.com/spf13/viper v1.3.2/go.mod h1:ZiWeW+zYFKm7srdB9IoDzzZXaJaI5eL9QjNiN/DMA2s=
github.com/spf13/viper v1.4.0/go.mod h1:PTJ7Z/lr49W6bUbkmS1V3by4uWynFiR9p7+dSq/yZzE=
github.com/spf13/viper v1.6.1/go.mod h1:t3iDnF5Jlj76alVNuyFBk5oUMCvsrkbvZK0WQdfDi5k=
github.com/srfrog/slices v1.0.1 h1:AfFmBRaTFK3YmIArR4q/cwhKI2seK+bbjJr/X+4mhmw=
github.com/srfrog/slices v1.0.1/go.mod h1:5OuxzTo5jO70/qZx6BVixf9u7VKO86tAKVkQEi+zz4Q=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.2.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoHMkEqE=
Expand Down
8 changes: 3 additions & 5 deletions pkg/cmd/miscellaneous.go
Original file line number Diff line number Diff line change
Expand Up @@ -108,11 +108,9 @@ func clientToTarget(target TargetKind) (*k8s.Clientset, error) {
checkError(err)
clientConfig, err := clientcmd.NewClientConfigFromBytes(kubeconfig)
checkError(err)
rawConfig, err := clientConfig.RawConfig()
checkError(err)
if err := ValidateClientConfig(rawConfig); err != nil {
return nil, err
}

gardenKubeConfigHashCheck()

config, err := clientConfig.ClientConfig()
checkError(err)
clientset, err := k8s.NewForConfig(config)
Expand Down
10 changes: 3 additions & 7 deletions pkg/cmd/target.go
Original file line number Diff line number Diff line change
Expand Up @@ -972,13 +972,9 @@ func getServerValueFromKubeconfig(kubeconfigPath string, kubeconfigReader Kubeco
if err != nil {
return "", err
}
rawConfig, err := clientConfig.RawConfig()
if err != nil {
return "", err
}
if err := ValidateClientConfig(rawConfig); err != nil {
return "", err
}

gardenKubeConfigHashCheck()

config, err := clientConfig.ClientConfig()
if err != nil {
return "", err
Expand Down
14 changes: 10 additions & 4 deletions pkg/cmd/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -133,10 +133,16 @@ type GardenClusters struct {

// GardenClusterMeta contains name and path to kubeconfig of gardencluster
type GardenClusterMeta struct {
Name string `yaml:"name,omitempty" json:"name,omitempty"`
KubeConfig string `yaml:"kubeConfig,omitempty" json:"kubeConfig,omitempty"`
DashboardURL string `yaml:"dashboardUrl,omitempty" json:"dashboardUrl,omitempty"`
AccessRestrictions []AccessRestriction `yaml:"accessRestrictions,omitempty" json:"accessRestrictions,omitempty"`
Name string `yaml:"name,omitempty" json:"name,omitempty"`
KubeConfig string `yaml:"kubeConfig,omitempty" json:"kubeConfig,omitempty"`
DashboardURL string `yaml:"dashboardUrl,omitempty" json:"dashboardUrl,omitempty"`
AccessRestrictions []AccessRestriction `yaml:"accessRestrictions,omitempty" json:"accessRestrictions,omitempty"`
TrustedKubeConfigMd5 string `yaml:"TrustedKubeConfigMd5,omitempty" json:"kubeConfigTrusteds,omitempty"`
}

// TrustedKubeConfigMd5 contains key
type TrustedKubeConfigMd5 struct {
Key string `yaml:"key,omitempty" json:"key,omitempty"`
}

// AccessRestrictionsOption contains key / notifyIf / msg
Expand Down
158 changes: 156 additions & 2 deletions pkg/cmd/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@
package cmd

import (
"bufio"
"crypto/md5"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
Expand All @@ -31,13 +34,19 @@ import (

gardencorev1beta1 "github.com/gardener/gardener/pkg/apis/core/v1beta1"
gardenerlogger "github.com/gardener/gardener/pkg/logger"
slices "github.com/srfrog/slices"
yaml "gopkg.in/yaml.v2"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
restclient "k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
)

const (
red = "\033[1;31m%s\033[0m"
green = "\033[1;32m%s\033[0m"
)

// checkError checks if an error during execution occurred
func checkError(err error) {
if err != nil {
Expand Down Expand Up @@ -245,11 +254,11 @@ func ValidateClientConfig(config clientcmdapi.Config) error {
case authInfo.Impersonate != "" || len(authInfo.ImpersonateGroups) > 0:
return fmt.Errorf("impersonation is not supported, these are the valid fields: %+v", validFields)
case authInfo.AuthProvider != nil && len(authInfo.AuthProvider.Config) > 0:
fmt.Printf("Kubeconfig under path %s contains auth provider configurations that could contain malicious code. Please only continue if you have verified it to be uncritical\n", pathOfKubeconfig)
fmt.Printf(green, "Kubeconfig under path "+pathOfKubeconfig+" contains auth provider configurations that could contain malicious code. Please only continue if you have verified it to be uncritical\n")
return nil
// return fmt.Errorf("auth provider configurations are not supported (user %q), these are the valid fields: %+v", user, validFields)
case authInfo.Exec != nil:
fmt.Printf("Kubeconfig under path %s contains exec configurations that could contain malicious code. Please only continue if you have verified it to be uncritical\n", pathOfKubeconfig)
fmt.Printf(green, "Kubeconfig under path "+pathOfKubeconfig+" contains exec configurations that could contain malicious code. Please only continue if you have verified it to be uncritical\n")
return nil
// return fmt.Errorf("exec configurations are not supported (user %q), these are the valid fields: %+v", user, validFields)
}
Expand All @@ -258,6 +267,90 @@ func ValidateClientConfig(config clientcmdapi.Config) error {
return nil
}

func md5sum(path string) string {
md5 := md5.New()
data, err := ioutil.ReadFile(path)
checkError(err)
_, err = md5.Write([]byte(data))
checkError(err)
return hex.EncodeToString(md5.Sum(nil))
}

func kubeConfigMd5sumInit(input bool, gardenConfig *GardenConfig) {
if input {
rewriteGardenKubeConfig()
} else {
os.Exit(0)
}
}

func hashCheck(value string, gardenConfig *GardenConfig) bool {
for _, items := range gardenConfig.GardenClusters {
if items.TrustedKubeConfigMd5 == value {
return true
}
}
return false
}

//gardenKubeConfigHashCheck hash check
func gardenKubeConfigHashCheck() bool {
var gardenConfig *GardenConfig
pathOfKubeconfig := getKubeConfigOfClusterType("garden")
md5sum := md5sum(pathOfKubeconfig)

tempFile, err := ioutil.ReadFile(pathGardenConfig)
checkError(err)
err = yaml.Unmarshal(tempFile, &gardenConfig)
checkError(err)

switch gardenConfig.GardenClusters[0].TrustedKubeConfigMd5 {
case "":
for _, items := range gardenConfig.GardenClusters {
data, err := ioutil.ReadFile(items.KubeConfig)
checkError(err)
clientConfig, err := clientcmd.NewClientConfigFromBytes(data)
checkError(err)
rawConfig, err := clientConfig.RawConfig()
checkError(err)
if err := ValidateClientConfig(rawConfig); err != nil {
checkError(err)
}
}

text := askForConfirmation()
kubeConfigMd5sumInit(text, gardenConfig)
return true

default:
if hashCheck(md5sum, gardenConfig) {
return true
}
}
fmt.Printf(red, "The Kubeconfig under path "+pathOfKubeconfig+" is difference compare with last time, Please check !!! \n")
text := askForConfirmation()
kubeConfigMd5sumInit(text, gardenConfig)
return false
}

func askForConfirmation() bool {
fmt.Printf(red, "Do you wants to trust this kubeconfig Y/N: ")
reader := bufio.NewReader(os.Stdin)
text, err := reader.ReadString('\n')
if err != nil {
log.Fatal(err)
}

text = strings.ToLower(strings.TrimSpace(text))[0:1]
if !(text == "y" || text == "n") {
fmt.Println("Please Yes or No only")
os.Exit(0)
} else if text == "y" {
return true
}
return false
}

// FetchShootFromTarget fetches shoot object from given target
func FetchShootFromTarget(target TargetInterface) (*gardencorev1beta1.Shoot, error) {
gardenClientset, err := target.GardenerClient()
Expand Down Expand Up @@ -370,3 +463,64 @@ func CheckIPPortReachable(ip string, port string) error {
}
return fmt.Errorf("IP %s port %s is not reachable", ip, port)
}

//rewriteGardenKubeConfig with md5sum and comments
func rewriteGardenKubeConfig() {
backupfile := pathGardenConfig + ".bak"
backup(pathGardenConfig, backupfile)

readerfile, err := os.OpenFile(backupfile, os.O_RDONLY, 0644)
if err != nil {
log.Fatal("Error: ", err)
}
defer readerfile.Close()

writefile, err := os.OpenFile(pathGardenConfig, os.O_RDWR|os.O_TRUNC, 0644)
if err != nil {
log.Fatal("Error: ", err)
}
defer writefile.Close()
reader := bufio.NewReader(readerfile)
writer := bufio.NewWriter(writefile)

for {
line, _, err := reader.ReadLine()
if err == io.EOF {
break
}
_, err = writer.WriteString(string(line) + "\n")
if err != nil {
log.Fatal("Error: ", err)
}

slc := strings.Split(string(line), " ")
var tempLine string
if slices.ContainsPrefix(slc, "kubeConfig:") {
if slices.ContainsPrefix(slc, "#") {
tempLine = "# TrustedKubeConfigMd5: " + md5sum(slc[3])
} else {
tempLine = " TrustedKubeConfigMd5: " + md5sum(slc[3])
}

_, err = writer.WriteString(tempLine + "\n")
if err != nil {
log.Fatal("Error: ", err)
}
}
}
writer.Flush()
}

//back up file
func backup(source string, destination string) {
input, err := ioutil.ReadFile(source)
if err != nil {
fmt.Println("Error loading", source)
log.Fatal(err)
}

err = ioutil.WriteFile(destination, input, 0644)
if err != nil {
log.Fatal(err)
}
}
3 changes: 3 additions & 0 deletions vendor/github.com/srfrog/slices/.gitignore

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

21 changes: 21 additions & 0 deletions vendor/github.com/srfrog/slices/LICENSE

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

79 changes: 79 additions & 0 deletions vendor/github.com/srfrog/slices/README.md

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 8 additions & 0 deletions vendor/github.com/srfrog/slices/doc.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions vendor/github.com/srfrog/slices/go.mod

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading