diff --git a/cmd/zeroward/buckets.go b/cmd/zeroward/buckets.go index ba75c12..ed73493 100644 --- a/cmd/zeroward/buckets.go +++ b/cmd/zeroward/buckets.go @@ -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", diff --git a/cmd/zeroward/decrypt.go b/cmd/zeroward/decrypt.go index 3a9c920..c2d8745 100644 --- a/cmd/zeroward/decrypt.go +++ b/cmd/zeroward/decrypt.go @@ -10,7 +10,6 @@ import ( "github.com/spf13/viper" ) -// decryptCmd represents the decrypt command var decryptCmd = &cobra.Command{ Use: "decrypt", Short: "Command to decrypt user encrypted file", @@ -18,7 +17,7 @@ var decryptCmd = &cobra.Command{ 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") @@ -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) @@ -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!") } diff --git a/cmd/zeroward/download.go b/cmd/zeroward/download.go index e631fc1..16442c9 100644 --- a/cmd/zeroward/download.go +++ b/cmd/zeroward/download.go @@ -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.", diff --git a/cmd/zeroward/encrypt.go b/cmd/zeroward/encrypt.go index 38ea33b..7cdaac3 100644 --- a/cmd/zeroward/encrypt.go +++ b/cmd/zeroward/encrypt.go @@ -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", @@ -36,7 +35,7 @@ var encryptCmd = &cobra.Command{ } common.UpdateKEKKey(kekKey) } - // Use the existing KEKKey + kekk := viper.GetString("KEKkey") kekBytes, err := hex.DecodeString(kekk) @@ -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 { diff --git a/cmd/zeroward/objects.go b/cmd/zeroward/objects.go index 829b582..a5909b9 100644 --- a/cmd/zeroward/objects.go +++ b/cmd/zeroward/objects.go @@ -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", diff --git a/cmd/zeroward/removeFile.go b/cmd/zeroward/removeFile.go index 85bd7c9..47b553b 100644 --- a/cmd/zeroward/removeFile.go +++ b/cmd/zeroward/removeFile.go @@ -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", diff --git a/cmd/zeroward/root.go b/cmd/zeroward/root.go index 9997327..600e8f2 100644 --- a/cmd/zeroward/root.go +++ b/cmd/zeroward/root.go @@ -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 @@ -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) } @@ -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) diff --git a/cmd/zeroward/upload.go b/cmd/zeroward/upload.go index 934edbb..ba2aa7d 100644 --- a/cmd/zeroward/upload.go +++ b/cmd/zeroward/upload.go @@ -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 { diff --git a/pkg/zeroward/buckets/buckets..go b/pkg/zeroward/buckets/buckets..go index e8e681a..4d522d7 100644 --- a/pkg/zeroward/buckets/buckets..go +++ b/pkg/zeroward/buckets/buckets..go @@ -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)), diff --git a/pkg/zeroward/common/credentialscrea.go b/pkg/zeroward/common/credentialscrea.go index 1351848..df772ee 100644 --- a/pkg/zeroward/common/credentialscrea.go +++ b/pkg/zeroward/common/credentialscrea.go @@ -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") @@ -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 { @@ -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 { @@ -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 { diff --git a/pkg/zeroward/common/s3utils.go b/pkg/zeroward/common/s3utils.go index f3496b0..4cfc75f 100644 --- a/pkg/zeroward/common/s3utils.go +++ b/pkg/zeroward/common/s3utils.go @@ -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("│") @@ -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() } diff --git a/pkg/zeroward/decryption/decrypt.go b/pkg/zeroward/decryption/decrypt.go index 06dd38d..6f5bfb5 100644 --- a/pkg/zeroward/decryption/decrypt.go +++ b/pkg/zeroward/decryption/decrypt.go @@ -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 } @@ -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 { @@ -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 @@ -93,7 +118,7 @@ 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) @@ -101,7 +126,7 @@ func VerifyChecksum(data []byte) ([]byte, error) { 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") diff --git a/pkg/zeroward/downloading/downloadobject.go b/pkg/zeroward/downloading/downloadobject.go index a710e40..7115df1 100644 --- a/pkg/zeroward/downloading/downloadobject.go +++ b/pkg/zeroward/downloading/downloadobject.go @@ -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 { @@ -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, @@ -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) } } @@ -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, @@ -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") @@ -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 { @@ -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) @@ -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, @@ -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) } } @@ -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, diff --git a/pkg/zeroward/encryption/encrypt.go b/pkg/zeroward/encryption/encrypt.go index cac1511..191a0cd 100644 --- a/pkg/zeroward/encryption/encrypt.go +++ b/pkg/zeroward/encryption/encrypt.go @@ -9,7 +9,6 @@ import ( "hash/crc32" "io" "os" - "path/filepath" ) func EncryptKey(dek []byte, kek []byte, filePath string) error { @@ -17,15 +16,19 @@ func EncryptKey(dek []byte, kek []byte, filePath string) error { if err != nil { return err } - - outputDEKDir := filepath.Dir(filePath) - outputDEKFilePath := filepath.Join(outputDEKDir, "DEK.key.enc") - - file, err := os.Create(outputDEKFilePath) + // outputDEKDir := filepath.Dir(filePath) + // outputDEKFilePath := filepath.Join(outputDEKDir, "DEK.key.enc") + outputFilePath := filePath + ".enc" + file, err := os.OpenFile(outputFilePath, os.O_APPEND|os.O_WRONLY, 0644) if err != nil { return err } defer file.Close() + // file, err := os.Create(outputDEKFilePath) + // if err != nil { + // return err + // } + // defer file.Close() _, err = file.Write(encryptedData) if err != nil { diff --git a/pkg/zeroward/genekeys/genedek.go b/pkg/zeroward/genekeys/genedek.go index 9c209a0..871e529 100644 --- a/pkg/zeroward/genekeys/genedek.go +++ b/pkg/zeroward/genekeys/genedek.go @@ -6,10 +6,9 @@ import ( ) const ( - dekSize = 32 // DEK key size in bytes + dekSize = 32 ) -// GenerateDEK generates a cryptographically secure random DEK func GenerateDek() ([]byte, error) { dek := make([]byte, dekSize) _, err := rand.Read(dek) diff --git a/pkg/zeroward/genekeys/genekek.go b/pkg/zeroward/genekeys/genekek.go index e839277..3520eae 100644 --- a/pkg/zeroward/genekeys/genekek.go +++ b/pkg/zeroward/genekeys/genekek.go @@ -14,13 +14,12 @@ const ( ) func GenerateKek(passphrase string) ([]byte, error) { - // Generate a random salt + salt := make([]byte, saltSize) if _, err := rand.Read(salt); err != nil { return nil, err } - // Derive the key using PBKDF2 key := pbkdf2.Key([]byte(passphrase), salt, iteration, keySize, sha256.New) return key, nil diff --git a/pkg/zeroward/objects/objects.go b/pkg/zeroward/objects/objects.go index 5f331d1..0d31473 100644 --- a/pkg/zeroward/objects/objects.go +++ b/pkg/zeroward/objects/objects.go @@ -30,7 +30,7 @@ func ListObjects(awsRegion string, accessKeyId string, accessKeySecret string, b for _, object := range result.Contents { size := formatSize(*object.Size) - // Add a row for each object + rows = append(rows, []string{ aws.ToString(object.Key), size, diff --git a/pkg/zeroward/uploading/uploadobject.go b/pkg/zeroward/uploading/uploadobject.go index eea419f..fa1c080 100644 --- a/pkg/zeroward/uploading/uploadobject.go +++ b/pkg/zeroward/uploading/uploadobject.go @@ -22,7 +22,6 @@ func UploadFile(awsRegion, accessKeyId, accessKeySecret, bucketName, filePath st return fmt.Errorf("failed to set up S3 client: %v", err) } - // Check if the file exists if _, err := os.Stat(filePath); os.IsNotExist(err) { return fmt.Errorf("file not found: %s", filePath) } @@ -38,9 +37,8 @@ func UploadFile(awsRegion, accessKeyId, accessKeySecret, bucketName, filePath st }() fileName := filepath.Base(filePath) - objectKey = filepath.Join(objectKey, fileName) // Using specified path as object key + objectKey = filepath.Join(objectKey, fileName) - // Check if the bucket exists _, err = client.HeadBucket(context.TODO(), &s3.HeadBucketInput{ Bucket: &bucketName, }) @@ -52,7 +50,6 @@ func UploadFile(awsRegion, accessKeyId, accessKeySecret, bucketName, filePath st case *types.NotFound: return fmt.Errorf("bucket not found: %s", bucketName) default: - // Handle other errors return fmt.Errorf("error checking if the bucket exists: %v", err) } }