Skip to content

Commit

Permalink
handle review comments
Browse files Browse the repository at this point in the history
Signed-off-by: Naiming Shen <naiming@Admins-MacBook-Pro-3.local>
Signed-off-by: Naiming Shen <naiming@admins-mbp-3.lan>
Signed-off-by: Naiming Shen <naiming@Admins-MacBook-Pro-3.local>
  • Loading branch information
Naiming Shen authored and eriknordmark committed May 15, 2024
1 parent e6a0635 commit 12c54c2
Show file tree
Hide file tree
Showing 5 changed files with 74 additions and 310 deletions.
68 changes: 10 additions & 58 deletions pkg/edgeview/src/basics.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (
"os"
"os/exec"
"path/filepath"
"regexp"
"strconv"
"strings"
"time"
Expand Down Expand Up @@ -143,53 +144,6 @@ func initOpts() {
}
}

// this script is automatically installed into your /tmp/download/bin
// and can be used to run your kubectl with the download kubeconfig file
// decrypted by the ssh private key
const kubeConfdecrpytScript = `#!/bin/bash
usage() {
echo "Usage: $0 [-keypath=\"your ssh private key file path\"]"
}
# Parse command line arguments
while [[ $# -gt 0 ]]; do
key="$1"
case $key in
-keypath=*)
keypath="${key#*=}"
shift # Shift to the next argument after the keypath value
;;
*)
# Unknown option or argument
usage
exit 1
;;
esac
done
# Set the private key path based on the provided -keypath or use the default
if [ -n "$keypath" ]; then
privateKeyFile="$keypath"
else
# use default ssh private key
privateKeyFile="$HOME/.ssh/id_rsa"
fi
# the symmetric key is encrypted by ssh public key
symmetricKeyEncFile="/tmp/download/kube-symmetric-file.enc"
# the kubeconfig file is encrypted by the symmetric key
symmetricEncFile="/tmp/download/kube-config-yaml"
# Decrypt the symmetric key using the SSH private key
symmetricKey=$(openssl pkeyutl -decrypt -inkey "$privateKeyFile" -in "$symmetricKeyEncFile")
# decrypt the kube config with openssl
kconfig=$(openssl enc -aes-256-cbc -d -in "$symmetricEncFile" -k "$symmetricKey" 2>/dev/null)
echo "$kconfig"`

// checkOpts -
// a pre-defined sets of 'network', 'system', 'pub' commands are supported, the command options can be
// multiple and separated by ',', this function to verify each of the command is valid and supported
Expand Down Expand Up @@ -632,22 +586,20 @@ func listRecursiveFiles(path, pattern string) ([]string, error) {
return jfiles, nil
}

// this script is used to run your kubectl with the download kubeconfig file
// decrypted by the ssh private key
func checkAndInstallKubeDecryptScript() error {
scriptfile := filepath.Join(fileCopyDir, "bin", "edgeview-kube-decrypt.sh")
err := os.MkdirAll(filepath.Dir(scriptfile), os.ModePerm)
// get the cluster api-server IP and port from kubeconfig file
func getKubeServerIPandPort(kubeConfigFile string) (string, error) {
content, err := os.ReadFile(kubeConfigFile)
if err != nil {
fmt.Println("Error creating directory:", err)
return err
return "", err
}

if err := os.WriteFile(scriptfile, []byte(kubeConfdecrpytScript), 0755); err != nil {
fmt.Println("Error writing script to file:", err)
return err
regex := regexp.MustCompile(`\s+server: https://([^ ]+)`)
matches := regex.FindStringSubmatch(string(content))
if len(matches) != 2 {
return "", fmt.Errorf("failed to find server in kubeconfig")
}

return nil
return strings.TrimSpace(matches[1]), nil
}

var helpStr = `eve-edgeview [ -token <session-token> ] [ -inst <instance-id> ] <query command>
Expand Down
74 changes: 0 additions & 74 deletions pkg/edgeview/src/copyfile.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import (
"bytes"
"encoding/json"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
Expand Down Expand Up @@ -383,8 +382,6 @@ func recvCopyFile(msg []byte, fstatus *fileCopyStatus, mtype int) {
} else {
fmt.Printf("\nfile size %d, saved at %s\n", fstatus.currSize, fileCopyDir+fileNameClean)
}
} else if fstatus.cType == copyKubeConfig {
splitKubeConfigFiles(fstatus.filename)
}
transferStr := fmt.Sprintf("\n file %s size %d", fileNameClean, fstatus.currSize)
if serverSentSize != 0 && fstatus.currSize != int64(serverSentSize) {
Expand Down Expand Up @@ -446,77 +443,6 @@ func sendCopyDone(context string, err error) {
}
}

// split files into key and encrypted files
// since the edgeview copy operation only downloaded a combined file
// you need your ssh private key to descript the symmetric key file, and use that
// to decrypt the kubeconfig file
func splitKubeConfigFiles(combFile string) {
fileStrs := strings.Split(combFile, ".")
if len(fileStrs) != 2 {
fmt.Printf("get file name incorrect %s\n", combFile)
return
}
numBytes := fileStrs[1]

bytesPlusOne, err := strconv.Atoi(numBytes)
if err != nil {
fmt.Printf("get file name incorrect num %s\n", numBytes)
return
}

// Open the combined file
combFilePath := filepath.Join(fileCopyDir, combFile)
cleanCombFilePath := filepath.Clean(combFilePath)
// To fix CodeQL warning, Check if the cleaned path is still within the intended directory
if !strings.HasPrefix(cleanCombFilePath, fileCopyDir) {
fmt.Println("potential path traversal attempt detected")
return
}

combFileHandle, err := os.Open(cleanCombFilePath)
if err != nil {
fmt.Printf("error opening combined file: %v\n", err)
return
}
defer combFileHandle.Close()

// Create the symKeyClientFile
symFileHandle, err := os.Create(symKeyClientFile)
if err != nil {
fmt.Printf("error creating sym file: %v\n", err)
return
}
defer symFileHandle.Close()

// Copy the first 'bytesPlusOne' bytes from the combined file to the symKeyClientFile
_, err = io.CopyN(symFileHandle, combFileHandle, int64(bytesPlusOne))
if err != nil {
fmt.Printf("error copying to sym file: %v\n", err)
return
}

// Create the kubeClientFile
kubeFileHandle, err := os.Create(kubeClientFile)
if err != nil {
fmt.Printf("error creating kube file: %v\n", err)
return
}
defer kubeFileHandle.Close()

// Copy the rest of the combined file to the kubeClientFile
_, err = io.Copy(kubeFileHandle, combFileHandle)
if err != nil {
fmt.Printf("error copying to kube file: %v\n", err)
return
}

// Remove the combined file
err = os.Remove(cleanCombFilePath)
if err != nil {
fmt.Printf("error removing combined file: %v\n", err)
}
}

// untarLogfile - unzip and make into a single .txt
// with sequential log entries for dev and each of the apps
// this is done only if the tar file size is not too large
Expand Down
4 changes: 0 additions & 4 deletions pkg/edgeview/src/edge-view.go
Original file line number Diff line number Diff line change
Expand Up @@ -222,10 +222,6 @@ func main() {
}
if kubecfg {
fstatus.cType = copyKubeConfig
err := checkAndInstallKubeDecryptScript()
if err != nil {
return
}
}
pnetopt = pqueryopt
} else if strings.HasPrefix(pqueryopt, "cp/") {
Expand Down
30 changes: 27 additions & 3 deletions pkg/edgeview/src/policy.go
Original file line number Diff line number Diff line change
Expand Up @@ -255,17 +255,41 @@ func checkAddrKube(addr string) bool {
return false
}

_, subnet1, err := net.ParseCIDR("10.42.0.0/16")
// part of the cluster --cluster-cidr prefix block for this node
cni0Prefix, err := getCNIPrefix()
if err != nil {
return false
}

_, subnet2, err := net.ParseCIDR("10.43.0.0/16")
// this is the --service-cidr for kubernetes service prefix block,
// and default is 10.43/16
_, kubeServicePrefix, err := net.ParseCIDR("10.43.0.0/16")
if err != nil {
return false
}
return cni0Prefix.Contains(ipa) || kubeServicePrefix.Contains(ipa)
}

// get the CNI0 interface IP prefix
func getCNIPrefix() (*net.IPNet, error) {
iface, err := net.InterfaceByName("cni0")
if err != nil {
return nil, err
}

addrs, err := iface.Addrs()
if err != nil {
return nil, err
}

for _, addr := range addrs {
switch v := addr.(type) {
case *net.IPNet:
return v, nil
}
}

return subnet1.Contains(ipa) || subnet2.Contains(ipa)
return nil, fmt.Errorf("no valid IPNet address found for cni0")
}

func checkAddrLocal(addr string) bool {
Expand Down
Loading

0 comments on commit 12c54c2

Please sign in to comment.