Skip to content

Commit

Permalink
added save\current\secure and .enc cont cli command, fixed few bugs
Browse files Browse the repository at this point in the history
  • Loading branch information
refaktor committed Mar 21, 2024
1 parent cbeef02 commit 8cd2391
Show file tree
Hide file tree
Showing 7 changed files with 162 additions and 8 deletions.
2 changes: 1 addition & 1 deletion env/object.go
Original file line number Diff line number Diff line change
Expand Up @@ -505,7 +505,7 @@ func (i Word) Equal(o Object) bool {
}

func (i Word) Dump(e Idxs) string {
return e.GetWord(i.Index)
return "'" + e.GetWord(i.Index)
}

//
Expand Down
53 changes: 53 additions & 0 deletions evaldo/builtins.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import (

"github.com/refaktor/rye/util"

"golang.org/x/crypto/ssh/terminal"

Check failure on line 26 in evaldo/builtins.go

View workflow job for this annotation

GitHub Actions / lint

SA1019: "golang.org/x/crypto/ssh/terminal" is deprecated: this package moved to golang.org/x/term. (staticcheck)
"golang.org/x/sync/errgroup"
"golang.org/x/text/cases"
"golang.org/x/text/language"
Expand Down Expand Up @@ -680,6 +681,32 @@ var builtins = map[string]*env.Builtin{
},
},

"get": { // *** currently a concept in testing ... for getting a code of a function, maybe same would be needed for context?
Argsn: 1,
Doc: "Returns value of the word in context",
Pure: true,
Fn: func(ps *env.ProgramState, arg0 env.Object, arg1 env.Object, arg2 env.Object, arg3 env.Object, arg4 env.Object) env.Object {
switch w := arg0.(type) {
case env.Word:
object, found := ps.Ctx.Get(w.Index)
if found {
return object
} else {
return MakeBuiltinError(ps, "Word not found in contexts ", "get")
}
case env.Opword:
object, found := ps.Ctx.Get(w.Index)
if found {
return object
} else {
return MakeBuiltinError(ps, "Word not found in contexts ", "get")
}
default:
return MakeArgError(ps, 1, []env.Type{env.WordType}, "set")
}
},
},

// CONTINUE WORK HERE - SYSTEMATISATION

"dump": { // *** currently a concept in testing ... for getting a code of a function, maybe same would be needed for context?
Expand Down Expand Up @@ -710,6 +737,32 @@ var builtins = map[string]*env.Builtin{
},
},

// TODO -- make save\\context ctx %file
"save\\current\\secure": {
Argsn: 0,
Doc: "Saves current state of the program to a file.",
Pure: true,
Fn: func(ps *env.ProgramState, arg0 env.Object, arg1 env.Object, arg2 env.Object, arg3 env.Object, arg4 env.Object) (res env.Object) {
s := ps.Dump()
fileName := fmt.Sprintf("console_%s.rye.enc", time.Now().Format("060102_150405"))

fmt.Print("Enter Password: ")
bytePassword, err := terminal.ReadPassword(int(os.Stdin.Fd()))
if err != nil {
panic(err)
}
password := string(bytePassword)

util.SaveSecure(s, fileName, password)
/* err != nil {
ps.FailureFlag = true
return MakeBuiltinError(ps, fmt.Sprintf("error writing state: %s", err.Error()), "save\\state")
}*/
fmt.Println("State current context to \033[1m" + fileName + "\033[0m.")
return *env.NewInteger(1)
},
},

"doc": { // ***
Argsn: 1,
Doc: "Sets docstring of the current context.",
Expand Down
2 changes: 1 addition & 1 deletion evaldo/builtins_spreadsheet.go
Original file line number Diff line number Diff line change
Expand Up @@ -814,7 +814,7 @@ func GenerateColumnRegexReplace(ps *env.ProgramState, s *env.Spreadsheet, name e
newVal = ""
} else {
// replace the value with the regex
newVal = env.NewString(re.ReplaceAllString(valStr.Value, pattern))
newVal = *env.NewString(re.ReplaceAllString(valStr.Value, pattern))
}
// set the result of code block as the new column value in this row
row.Values = append(row.Values, newVal)
Expand Down
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ require (
github.com/yusufpapurcu/wmi v1.2.3 // indirect
go.etcd.io/bbolt v1.3.7 // indirect
golang.org/x/sys v0.17.0 // indirect
golang.org/x/term v0.17.0 // indirect
google.golang.org/protobuf v1.26.0 // indirect
gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc // indirect
gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df // indirect
Expand Down
3 changes: 2 additions & 1 deletion go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,6 @@ github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJ
github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
github.com/modern-go/reflect2 v1.0.1 h1:9f412s+6RmYXLWZSEzVVgPGK7C2PphHj5RJrvfx9AWI=
github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe/go.mod h1:wL8QJuTMNUDYhXwkmfOly8iTdp5TEcJFWZD2D7SIkUc=
github.com/mrz1836/postmark v1.6.4 h1:x5g0zjFE1q1wOgZ3N22rtGMyfKd3GBo4O874cAUw6bQ=
github.com/mrz1836/postmark v1.6.4/go.mod h1:6z5MxAH00Kj44owtQaryv9Pbqp5OKT3wWcRSydB0p0A=
github.com/mschoch/smat v0.2.0 h1:8imxQsjDm8yFEAVBe7azKmKSgzSkZXDuKkSq9374khM=
Expand Down Expand Up @@ -196,6 +195,8 @@ golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBc
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.17.0 h1:25cE3gD+tdBA7lp7QfhuV+rJiE9YXTcS3VG1SqssI/Y=
golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/term v0.17.0 h1:mkTF7LCd6WGJNL3K1Ad7kwxNfYAW6a8a8QqtMblp/4U=
golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk=
golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
Expand Down
23 changes: 18 additions & 5 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"sort"

"github.com/refaktor/rye/contrib"

Check failure on line 11 in main.go

View workflow job for this annotation

GitHub Actions / lint

File is not `goimports`-ed with -local github.com/refaktor/rye (goimports)
"golang.org/x/crypto/ssh/terminal"

Check failure on line 12 in main.go

View workflow job for this annotation

GitHub Actions / lint

SA1019: "golang.org/x/crypto/ssh/terminal" is deprecated: this package moved to golang.org/x/term. (staticcheck)

"bufio"
"errors"
Expand Down Expand Up @@ -363,12 +364,24 @@ func main_rye_file(file string, sig bool, subc bool, interactive bool, code stri
//util.PrintHeader()
//defer profile.Start(profile.CPUProfile).Stop()

bcontent, err := os.ReadFile(file)
if err != nil {
log.Fatal(err)
}
var content string

if file[len(file)-4:] == ".enc" {
fmt.Print("Enter Password: ")
bytePassword, err := terminal.ReadPassword(int(os.Stdin.Fd()))
if err != nil {
panic(err)
}
password := string(bytePassword)

content := string(bcontent)
content = util.ReadSecure(file, password)
} else {
bcontent, err := os.ReadFile(file)
if err != nil {
log.Fatal(err)
}
content = string(bcontent)
}

if info {
pattern := regexp.MustCompile(`^; (#[^\n]*)`)
Expand Down
86 changes: 86 additions & 0 deletions util/securesave.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
package util

import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"crypto/sha256"
"io"
"os"

"golang.org/x/crypto/pbkdf2"
)

func SaveSecure(textToEncrypt string, filename string, password string) {
// Example usage
// password := "your-password"
// textToEncrypt := "Hello, World!"

// Encrypt
encryptedData, err := encrypt([]byte(textToEncrypt), password)
if err != nil {
panic(err)
}

// Write encrypted data to a file
err = os.WriteFile(filename, encryptedData, 0644)

Check failure on line 26 in util/securesave.go

View workflow job for this annotation

GitHub Actions / lint

G306: Expect WriteFile permissions to be 0600 or less (gosec)
if err != nil {
panic(err)
}

Check failure on line 30 in util/securesave.go

View workflow job for this annotation

GitHub Actions / lint

unnecessary trailing newline (whitespace)
}

func ReadSecure(filename string, password string) string {
// Read encrypted data from the file
data, err := os.ReadFile(filename)
if err != nil {
panic(err)
}

// Decrypt
decryptedData, err := decrypt(data, password)
if err != nil {
panic(err)
}

return string(decryptedData)
}

func encrypt(data []byte, passphrase string) ([]byte, error) {
key := createPBKDF2Key(passphrase)
block, _ := aes.NewCipher(key)
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
nonce := make([]byte, gcm.NonceSize())
if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
return nil, err
}
ciphertext := gcm.Seal(nonce, nonce, data, nil)
return ciphertext, nil
}

func decrypt(data []byte, passphrase string) ([]byte, error) {
key := createPBKDF2Key(passphrase)
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
nonceSize := gcm.NonceSize()
nonce, ciphertext := data[:nonceSize], data[nonceSize:]
plaintext, err := gcm.Open(nil, nonce, ciphertext, nil)
if err != nil {
return nil, err
}
return plaintext, nil
}

func createPBKDF2Key(passphrase string) []byte {
salt := []byte("your-unique-salt") // Use a unique and random salt.
return pbkdf2.Key([]byte(passphrase), salt, 4096, 32, sha256.New)
}

0 comments on commit 8cd2391

Please sign in to comment.