Skip to content

Commit

Permalink
removed the dekkey passing as parameter
Browse files Browse the repository at this point in the history
  • Loading branch information
Abdiooa committed Mar 12, 2024
1 parent 911ddbf commit 06c9efe
Show file tree
Hide file tree
Showing 18 changed files with 65 additions and 60 deletions.
1 change: 0 additions & 1 deletion cmd/zeroward/buckets.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import (
"github.com/spf13/viper"
)

// bucketsCmd represents the buckets command
var bucketsCmd = &cobra.Command{
Use: "buckets",
Short: "List All Buckets(Folders) stored on the Cloud Storage",
Expand Down
15 changes: 7 additions & 8 deletions cmd/zeroward/decrypt.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,14 @@ import (
"github.com/spf13/viper"
)

// decryptCmd represents the decrypt command
var decryptCmd = &cobra.Command{
Use: "decrypt",
Short: "Command to decrypt user encrypted file",
Long: `This command is used to decrypt user encrypted files, so he can read and have the file `,
Run: func(cmd *cobra.Command, args []string) {
filePath, _ := cmd.Flags().GetString("filePath")

dekkeyPath, _ := cmd.Flags().GetString("dekkey")
// dekkeyPath, _ := cmd.Flags().GetString("dekkey")

kekk := viper.GetString("KEKkey")

Expand All @@ -28,7 +27,7 @@ var decryptCmd = &cobra.Command{
fmt.Println("Error:", err)
return
}
dekkey, err := decryption.DecryptKey(dekkeyPath, kekBytes)
dekkey, err := decryption.DecryptKey(filePath, kekBytes)

if err != nil {
fmt.Println("Error:", err)
Expand Down Expand Up @@ -57,15 +56,15 @@ var decryptCmd = &cobra.Command{
}

}
if err := os.Remove(dekkeyPath); err != nil {
fmt.Println("Error:", err)
return
}
// if err := os.Remove(dekkeyPath); err != nil {
// fmt.Println("Error:", err)
// return
// }
},
}

func init() {
rootCmd.AddCommand(decryptCmd)

decryptCmd.Flags().StringP("dekkey", "k", "", "DEK Key to decrypt the file please!")
// decryptCmd.Flags().StringP("dekkey", "k", "", "DEK Key to decrypt the file please!")
}
1 change: 0 additions & 1 deletion cmd/zeroward/download.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import (
"github.com/spf13/cobra"
)

// downloadCmd represents the download command
var downloadCmd = &cobra.Command{
Use: "download",
Short: "Download Command to download Files from the cloud.",
Expand Down
4 changes: 2 additions & 2 deletions cmd/zeroward/encrypt.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import (
"github.com/spf13/viper"
)

// encryptCmd represents the encrypt command
var encryptCmd = &cobra.Command{
Use: "encrypt",
Short: "Encrypt a file Locally",
Expand All @@ -36,7 +35,7 @@ var encryptCmd = &cobra.Command{
}
common.UpdateKEKKey(kekKey)
}
// Use the existing KEKKey

kekk := viper.GetString("KEKkey")

kekBytes, err := hex.DecodeString(kekk)
Expand All @@ -47,6 +46,7 @@ var encryptCmd = &cobra.Command{
}

dek, err := genekeys.GenerateDek()

cobra.CheckErr(err)
if filePath != "" {
if err := encryption.EncryptFile(filePath, dek); err != nil {
Expand Down
1 change: 0 additions & 1 deletion cmd/zeroward/objects.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import (
"github.com/spf13/viper"
)

// ObjectsCmd represents the Objects command
var ObjectsCmd = &cobra.Command{
Use: "objects",
Short: "List All Objects(Files/Images/Docs) stored on the Cloud Storage",
Expand Down
1 change: 0 additions & 1 deletion cmd/zeroward/removeFile.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import (
"github.com/spf13/viper"
)

// removeFileCmd represents the removeFile command
var removeCmd = &cobra.Command{
Use: "remove",
Short: "Remove Command to delete a file from cloud storage",
Expand Down
5 changes: 2 additions & 3 deletions cmd/zeroward/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,6 @@ func initConfig() {
}
}

// CreateConfigFile attempts to create the config file and CLSD folder
func CreateConfigFile() error {
// Get user's home directory based on OS
var homeDir string
Expand All @@ -119,7 +118,7 @@ func CreateConfigFile() error {
clsdFolderPath := filepath.Join(homeDir, ".config", clsdFolderName)

if _, err := os.Stat(clsdFolderPath); os.IsNotExist(err) {
err := os.Mkdir(clsdFolderPath, 0700) // Set read-write-execute for the owner only
err := os.Mkdir(clsdFolderPath, 0700)
if err != nil {
fmt.Printf("Error creating CLSD folder: %v", err)
}
Expand All @@ -132,7 +131,7 @@ func CreateConfigFile() error {
AWSSecretAccessKey: defaultAWSSecretKey,
}

viper.SetDefault("KEKkey", config.KEKkey) // Set default value for KEKkey in viper
viper.SetDefault("KEKkey", config.KEKkey)
viper.SetDefault("Region", config.Region)
viper.SetDefault("AWSAccessKeyID", config.AWSAccessKeyID)
viper.SetDefault("AWSSecretAccessKey", config.AWSSecretAccessKey)
Expand Down
2 changes: 1 addition & 1 deletion cmd/zeroward/upload.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ var uploadCmd = &cobra.Command{
passphrase, _ := cmd.Flags().GetString("passphrase")
filePath, _ := cmd.Flags().GetString("filePath")
objectkey, _ := cmd.Flags().GetString("objectkey")
encrypt, _ := cmd.Flags().GetBool("encrypt") // Change to GetBool
encrypt, _ := cmd.Flags().GetBool("encrypt")

if encrypt {
if err := handleEncryptionAndUpload(accessKeyID, secretAccessKey, bcktName, filePath, passphrase, objectkey); err != nil {
Expand Down
2 changes: 1 addition & 1 deletion pkg/zeroward/buckets/buckets..go
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ func ListBuckets(awsRegion string, accessKeyId string, accessKeySecret string) (
if err != nil {
return fmt.Errorf("listing objects in bucket %s failed: %s", aws.ToString(bucket.Name), err)
}
// Add a row for each bucket

rows = append(rows, []string{
aws.ToString(bucket.Name),
fmt.Sprintf("%dobjcs", len(objResult.Contents)),
Expand Down
4 changes: 0 additions & 4 deletions pkg/zeroward/common/credentialscrea.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ func StoreCredentials(accessKeyID, secretAccessKey, region string) {
var credentialsFilePath string
var awsConfigFilePath string

// Get user's home directory based on OS
switch runtime.GOOS {
case "windows":
homeDir := os.Getenv("USERPROFILE")
Expand All @@ -42,7 +41,6 @@ func StoreCredentials(accessKeyID, secretAccessKey, region string) {
os.Exit(1)
}

// Create the .aws directory if it doesn't exist
if _, err := os.Stat(awsDir); os.IsNotExist(err) {
err := os.Mkdir(awsDir, 0700)
if err != nil {
Expand All @@ -51,7 +49,6 @@ func StoreCredentials(accessKeyID, secretAccessKey, region string) {
}
}

// Write credentials to credentials file
credentialsFilePath = filepath.Join(awsDir, "credentials")
credentialsFile, err := os.Create(credentialsFilePath)
if err != nil {
Expand All @@ -63,7 +60,6 @@ func StoreCredentials(accessKeyID, secretAccessKey, region string) {
credentialsFile.WriteString(fmt.Sprintf("aws_access_key_id = %s\n", accessKeyID))
credentialsFile.WriteString(fmt.Sprintf("aws_secret_access_key = %s\n", secretAccessKey))

// Write region to config file
awsConfigFilePath = filepath.Join(awsDir, "config")
awsconfigFile, err := os.Create(awsConfigFilePath)
if err != nil {
Expand Down
6 changes: 2 additions & 4 deletions pkg/zeroward/common/s3utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,16 +62,15 @@ func SetupS3Client(awsRegion, accessKeyId, accessKeySecret string) (*s3.Client,
}

func RenderTable(header []string, rows [][]string) {
// Create a table

table := tablewriter.NewWriter(os.Stdout)
table.SetHeader(header)

for _, row := range rows {
// Add a row for each item

table.Append(row)
}

// Optionally, customize the table
table.SetBorder(true)
table.SetCenterSeparator("│")
table.SetColumnSeparator("│")
Expand All @@ -82,6 +81,5 @@ func RenderTable(header []string, rows [][]string) {
table.SetHeaderColor(tablewriter.Color(tablewriter.BgBlackColor), tablewriter.Color(tablewriter.FgGreenColor), tablewriter.Color(tablewriter.FgGreenColor))
}

// Render the table
table.Render()
}
41 changes: 33 additions & 8 deletions pkg/zeroward/decryption/decrypt.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,21 +6,46 @@ import (
"encoding/binary"
"fmt"
"hash/crc32"
"io"
"os"
)

func DecryptKey(encryptedKeyFile string, kekKey []byte) ([]byte, error) {
// Read the encrypted DEK key from the file
encryptedKey, err := os.ReadFile(encryptedKeyFile)
func DecryptKey(filePath string, kekKey []byte) ([]byte, error) {

file, err := os.OpenFile(filePath, os.O_RDWR, 0644)
if err != nil {
return nil, err
}
defer file.Close()

fileInfo, err := file.Stat()
if err != nil {
return nil, err
}
fileSize := fileInfo.Size()

// Use the KEK key to decrypt the DEK key
offset := fileSize - 60
_, err = file.Seek(offset, io.SeekStart)
if err != nil {
return nil, err
}
encryptedKey := make([]byte, 60)
_, err = file.Read(encryptedKey)
if err != nil {
return nil, err
}
// encryptedKey, err := os.ReadFile(encryptedKeyFile)
// if err != nil {
// return nil, err
// }
decryptedKey, err := DecryptData(encryptedKey, kekKey)
if err != nil {
return nil, err
}
err = file.Truncate(offset)
if err != nil {
return nil, err
}

return decryptedKey, nil
}
Expand All @@ -31,7 +56,7 @@ func DecryptFile(ciphertext []byte, dekKey []byte) ([]byte, error) {
// return fmt.Errorf("error reading ciphertext file: %v", err)
// }

blockSize := 1024 + 4 + 16 + 12 // Include space for checksum
blockSize := 1024 + 4 + 16 + 12
var decryptedData []byte

for i := 0; i < len(ciphertext); i += blockSize {
Expand All @@ -40,7 +65,7 @@ func DecryptFile(ciphertext []byte, dekKey []byte) ([]byte, error) {
end = len(ciphertext)
}
block := ciphertext[i:end]
// Decrypt each block

decryptedBlock, err := DecryptData(block, dekKey)
if err != nil {
return nil, err
Expand Down Expand Up @@ -93,15 +118,15 @@ func DecryptData(ciphertext, key []byte) ([]byte, error) {
func VerifyChecksum(data []byte) ([]byte, error) {
blockSize := 1024
var originalData []byte
for i := 0; i < len(data); i += blockSize + 4 { // the 4 bytes for checksum bytes
for i := 0; i < len(data); i += blockSize + 4 {
end := i + blockSize + 4
if end > len(data) {
end = len(data)
}
blockWithChecksum := data[i:end]
checksumBytes := blockWithChecksum[:4]
block := blockWithChecksum[4:]
// verify checksum

checksum := crc32.ChecksumIEEE(block)
if binary.BigEndian.Uint32(checksumBytes) != checksum {
return nil, fmt.Errorf("checksum verification failed")
Expand Down
14 changes: 4 additions & 10 deletions pkg/zeroward/downloading/downloadobject.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import (
"github.com/spf13/viper"
)

const DEKKeyMetadataKey = "dek-key" // Metadata key for the DEK key
const DEKKeyMetadataKey = "dek-key"

func DownloadObject(awsRegion, accessKeyId, accessKeySecret, bucketName, localFilePath string, objectKey string, removeAfterDownload bool) error {

Expand All @@ -26,7 +26,6 @@ func DownloadObject(awsRegion, accessKeyId, accessKeySecret, bucketName, localFi
return err
}

// Check if the object exists in the bucket
_, err = client.HeadObject(context.TODO(), &s3.HeadObjectInput{
Bucket: &bucketName,
Key: &objectKey,
Expand All @@ -39,7 +38,7 @@ func DownloadObject(awsRegion, accessKeyId, accessKeySecret, bucketName, localFi
case *types.NotFound:
return fmt.Errorf("object not found: %s/%s", bucketName, objectKey)
default:
// Handle other errors

return fmt.Errorf("error checking if the object exists: %v", err)
}
}
Expand All @@ -57,7 +56,6 @@ func DownloadObject(awsRegion, accessKeyId, accessKeySecret, bucketName, localFi
}
}()

// Download the object from S3
result, err := client.GetObject(context.TODO(), &s3.GetObjectInput{
Bucket: &bucketName,
Key: &objectKey,
Expand All @@ -74,7 +72,6 @@ func DownloadObject(awsRegion, accessKeyId, accessKeySecret, bucketName, localFi
return fmt.Errorf("error reading the body of the file: %v", err)
}

// Retrieve DEK key from metadata
dekKeyString, ok := result.Metadata[DEKKeyMetadataKey]
if !ok {
return fmt.Errorf("dek key not found in metadata")
Expand All @@ -84,7 +81,6 @@ func DownloadObject(awsRegion, accessKeyId, accessKeySecret, bucketName, localFi
return fmt.Errorf("error decoding DEK key: %v", err)
}

// Decrypt the DEK key with the KEK
kekk := viper.GetString("KEKkey")
kekBytes, err := hex.DecodeString(kekk)
if err != nil {
Expand All @@ -96,7 +92,6 @@ func DownloadObject(awsRegion, accessKeyId, accessKeySecret, bucketName, localFi
return fmt.Errorf("error decrypting DEK key: %v", err)
}

// Decrypt the body with the DEK key
body, err := decryption.DecryptFile(encryptedBody, dekkey)
if err != nil {
return fmt.Errorf("error decrypting file body: %v", err)
Expand Down Expand Up @@ -126,7 +121,6 @@ func DownloadNormalObject(awsRegion, accessKeyId, accessKeySecret, bucketName, l
return err
}

// Check if the object exists in the bucket
_, err = client.HeadObject(context.TODO(), &s3.HeadObjectInput{
Bucket: &bucketName,
Key: &objectKey,
Expand All @@ -139,7 +133,7 @@ func DownloadNormalObject(awsRegion, accessKeyId, accessKeySecret, bucketName, l
case *types.NotFound:
return fmt.Errorf("object not found: %s/%s", bucketName, objectKey)
default:
// Handle other errors

return fmt.Errorf("error checking if the object exists: %v", err)
}
}
Expand All @@ -156,7 +150,7 @@ func DownloadNormalObject(awsRegion, accessKeyId, accessKeySecret, bucketName, l
fmt.Printf("error closing the local file: %v\n", closeErr)
}
}()
// Download the object from S3

result, err := client.GetObject(context.TODO(), &s3.GetObjectInput{
Bucket: &bucketName,
Key: &objectKey,
Expand Down
Loading

0 comments on commit 06c9efe

Please sign in to comment.