From 28371084d38e636b16d0c9db6930d34eebfa968d Mon Sep 17 00:00:00 2001 From: Simone Margaritelli Date: Fri, 10 Jun 2022 22:39:29 +0200 Subject: [PATCH] new: added saveJSON function to the session scripting runtime --- session/script_builtin_runtime.go | 30 ++++++++++++++++++++++++++++-- session/session.go | 1 + 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/session/script_builtin_runtime.go b/session/script_builtin_runtime.go index 33aec042..f044bb08 100644 --- a/session/script_builtin_runtime.go +++ b/session/script_builtin_runtime.go @@ -3,6 +3,7 @@ package session import ( "encoding/json" "io/ioutil" + "os" "github.com/bettercap/bettercap/js" "github.com/evilsocket/islazy/log" @@ -84,13 +85,38 @@ func jsOnEventFunc(call otto.FunctionCall) otto.Value { return js.NullValue } +func jsSaveJSONFunc(call otto.FunctionCall) otto.Value { + argv := call.ArgumentList + argc := len(argv) + if argc != 2 { + return js.ReportError("saveJSON accepts one object and one string arguments") + } else if argv[0].IsObject() == false { + return js.ReportError("saveJSON accepts one object and one string arguments") + } else if argv[1].IsString() == false { + return js.ReportError("saveJSON accepts one object and one string arguments") + } + + obj := argv[0] + fileName := argv[1].String() + + if exp, err := obj.Export(); err != nil { + return js.ReportError("error exporting object: %v", err) + } else if raw, err := json.Marshal(exp); err != nil { + return js.ReportError("error serializing object: %v", err) + } else if err = ioutil.WriteFile(fileName, raw, os.ModePerm); err != nil { + return js.ReportError("error writing to '%s': %v", fileName, err) + } + + return js.NullValue +} + func jsLoadJSONFunc(call otto.FunctionCall) otto.Value { argv := call.ArgumentList argc := len(argv) if argc != 1 { - return js.ReportError("LoadJSON accepts one string argument") + return js.ReportError("loadJSON accepts one string argument") } else if argv[0].IsString() == false { - return js.ReportError("LoadJSON accepts one string argument") + return js.ReportError("loadJSON accepts one string argument") } fileName := argv[0].String() diff --git a/session/session.go b/session/session.go index 88cd5028..ddfb50b9 100644 --- a/session/session.go +++ b/session/session.go @@ -313,6 +313,7 @@ func (s *Session) Start() error { plugin.Defines["env"] = jsEnvFunc plugin.Defines["run"] = jsRunFunc plugin.Defines["loadJSON"] = jsLoadJSONFunc + plugin.Defines["saveJSON"] = jsSaveJSONFunc plugin.Defines["onEvent"] = jsOnEventFunc plugin.Defines["session"] = s