refactor:Added Integration test and tiny refactoring (#23)

* Refactoring name convention

* Added integration test

* Added Makefile

* Bump golang.org/x/crypto from 0.0.0-20220826181053-bd7e27e6170d to 0.6.0

Bumps [golang.org/x/crypto](https://github.com/golang/crypto) from 0.0.0-20220826181053-bd7e27e6170d to 0.6.0.
- [Release notes](https://github.com/golang/crypto/releases)
- [Commits](https://github.com/golang/crypto/commits/v0.6.0)

---
updated-dependencies:
- dependency-name: golang.org/x/crypto
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

* Upgrade go from 1.16 to 1.20

* Added integration test: HTTP, TCP, SSH

* Added Makefile Improve README.md

* Fixed unit test CI

* Fixed go-version

* Added integration test into C.I. actions

---------

Signed-off-by: Mario Candela <m4r10.php@gmail.com>
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
This commit is contained in:
Mario Candela
2023-02-26 18:04:05 +01:00
committed by GitHub
parent bbcc8c9094
commit 6468b5aa6f
23 changed files with 282 additions and 40 deletions

View File

@ -0,0 +1,110 @@
package strategies
import (
"beelzebub/parser"
"beelzebub/tracer"
"fmt"
"github.com/google/uuid"
log "github.com/sirupsen/logrus"
"io"
"net/http"
"regexp"
"strings"
)
type HypertextTransferProtocolStrategy struct {
beelzebubServiceConfiguration parser.BeelzebubServiceConfiguration
}
func (httpStrategy HypertextTransferProtocolStrategy) Init(beelzebubServiceConfiguration parser.BeelzebubServiceConfiguration, tr tracer.Tracer) error {
httpStrategy.beelzebubServiceConfiguration = beelzebubServiceConfiguration
serverMux := http.NewServeMux()
serverMux.HandleFunc("/", func(responseWriter http.ResponseWriter, request *http.Request) {
traceRequest(request, tr, beelzebubServiceConfiguration.Description)
for _, command := range httpStrategy.beelzebubServiceConfiguration.Commands {
matched, err := regexp.MatchString(command.Regex, request.RequestURI)
if err != nil {
log.Errorf("Error regex: %s, %s", command.Regex, err.Error())
continue
}
if matched {
setResponseHeaders(responseWriter, command.Headers, command.StatusCode)
fmt.Fprintf(responseWriter, command.Handler)
break
}
}
})
go func() {
err := http.ListenAndServe(httpStrategy.beelzebubServiceConfiguration.Address, serverMux)
if err != nil {
log.Errorf("Error during init HTTP Protocol: %s", err.Error())
return
}
}()
log.WithFields(log.Fields{
"port": beelzebubServiceConfiguration.Address,
"commands": len(beelzebubServiceConfiguration.Commands),
}).Infof("Init service: %s", beelzebubServiceConfiguration.Description)
return nil
}
func traceRequest(request *http.Request, tr tracer.Tracer, HoneypotDescription string) {
bodyBytes, err := io.ReadAll(request.Body)
body := ""
if err == nil {
body = string(bodyBytes)
}
tr.TraceEvent(tracer.Event{
Msg: "HTTP New request",
RequestURI: request.RequestURI,
Protocol: tracer.HTTP.String(),
HTTPMethod: request.Method,
Body: body,
HostHTTPRequest: request.Host,
UserAgent: request.UserAgent(),
Cookies: mapCookiesToString(request.Cookies()),
Headers: mapHeaderToString(request.Header),
Status: tracer.Stateless.String(),
RemoteAddr: request.RemoteAddr,
ID: uuid.New().String(),
Description: HoneypotDescription,
})
}
func mapHeaderToString(headers http.Header) string {
headersString := ""
for key := range headers {
for _, values := range headers[key] {
headersString += fmt.Sprintf("[Key: %s, values: %s],", key, values)
}
}
return headersString
}
func mapCookiesToString(cookies []*http.Cookie) string {
cookiesString := ""
for _, cookie := range cookies {
cookiesString += cookie.String()
}
return cookiesString
}
func setResponseHeaders(responseWriter http.ResponseWriter, headers []string, statusCode int) {
for _, headerStr := range headers {
keyValue := strings.Split(headerStr, ":")
if len(keyValue) > 1 {
responseWriter.Header().Add(keyValue[0], keyValue[1])
}
}
// http.StatusText(statusCode): empty string if the code is unknown.
if len(http.StatusText(statusCode)) > 0 {
responseWriter.WriteHeader(statusCode)
}
}

View File

@ -0,0 +1,129 @@
package strategies
import (
"beelzebub/parser"
"beelzebub/plugins"
"beelzebub/tracer"
"fmt"
"github.com/gliderlabs/ssh"
"github.com/google/uuid"
log "github.com/sirupsen/logrus"
"golang.org/x/crypto/ssh/terminal"
"regexp"
"strings"
"time"
)
type SecureShellStrategy struct {
}
func (SSHStrategy *SecureShellStrategy) Init(beelzebubServiceConfiguration parser.BeelzebubServiceConfiguration, tr tracer.Tracer) error {
go func() {
server := &ssh.Server{
Addr: beelzebubServiceConfiguration.Address,
MaxTimeout: time.Duration(beelzebubServiceConfiguration.DeadlineTimeoutSeconds) * time.Second,
IdleTimeout: time.Duration(beelzebubServiceConfiguration.DeadlineTimeoutSeconds) * time.Second,
Version: beelzebubServiceConfiguration.ServerVersion,
Handler: func(sess ssh.Session) {
uuidSession := uuid.New()
tr.TraceEvent(tracer.Event{
Msg: "New SSH Session",
Protocol: tracer.SSH.String(),
RemoteAddr: sess.RemoteAddr().String(),
Status: tracer.Start.String(),
ID: uuidSession.String(),
Environ: strings.Join(sess.Environ(), ","),
User: sess.User(),
Description: beelzebubServiceConfiguration.Description,
Command: sess.RawCommand(),
})
term := terminal.NewTerminal(sess, buildPrompt(sess.User(), beelzebubServiceConfiguration.ServerName))
var histories []plugins.History
for {
commandInput, err := term.ReadLine()
if err != nil {
break
}
tr.TraceEvent(tracer.Event{
Msg: "New SSH Terminal Session",
RemoteAddr: sess.RemoteAddr().String(),
Status: tracer.Interaction.String(),
Command: commandInput,
ID: uuidSession.String(),
Protocol: tracer.SSH.String(),
Description: beelzebubServiceConfiguration.Description,
})
if commandInput == "exit" {
break
}
for _, command := range beelzebubServiceConfiguration.Commands {
matched, err := regexp.MatchString(command.Regex, commandInput)
if err != nil {
log.Errorf("Error regex: %s, %s", command.Regex, err.Error())
continue
}
if matched {
commandOutput := command.Handler
if command.Plugin == plugins.ChatGPTPluginName {
openAIGPTVirtualTerminal := plugins.OpenAIGPTVirtualTerminal{Histories: histories, OpenAPIChatGPTSecretKey: beelzebubServiceConfiguration.Plugin.OpenAPIChatGPTSecretKey}
openAIGPTVirtualTerminal.InjectDependency()
if commandOutput, err = openAIGPTVirtualTerminal.GetCompletions(commandInput); err != nil {
log.Errorf("Error GetCompletions: %s, %s", commandInput, err.Error())
commandOutput = "command not found"
}
}
histories = append(histories, plugins.History{Input: commandInput, Output: commandOutput})
term.Write(append([]byte(commandOutput), '\n'))
break
}
}
}
tr.TraceEvent(tracer.Event{
Msg: "End SSH Session",
Status: tracer.End.String(),
ID: uuidSession.String(),
})
},
PasswordHandler: func(ctx ssh.Context, password string) bool {
tr.TraceEvent(tracer.Event{
Msg: "New SSH attempt",
Protocol: tracer.SSH.String(),
Status: tracer.Stateless.String(),
User: ctx.User(),
Password: password,
Client: ctx.ClientVersion(),
RemoteAddr: ctx.RemoteAddr().String(),
ID: uuid.New().String(),
Description: beelzebubServiceConfiguration.Description,
})
matched, err := regexp.MatchString(beelzebubServiceConfiguration.PasswordRegex, password)
if err != nil {
log.Errorf("Error regex: %s, %s", beelzebubServiceConfiguration.PasswordRegex, err.Error())
return false
}
return matched
},
}
err := server.ListenAndServe()
if err != nil {
log.Errorf("Error during init SSH Protocol: %s", err.Error())
}
}()
log.WithFields(log.Fields{
"port": beelzebubServiceConfiguration.Address,
"commands": len(beelzebubServiceConfiguration.Commands),
}).Infof("Init service %s", beelzebubServiceConfiguration.Protocol)
return nil
}
func buildPrompt(user string, serverName string) string {
return fmt.Sprintf("%s@%s:~$ ", user, serverName)
}

View File

@ -0,0 +1,57 @@
package strategies
import (
"beelzebub/parser"
"beelzebub/tracer"
"fmt"
"github.com/google/uuid"
log "github.com/sirupsen/logrus"
"net"
"time"
)
type TransmissionControlProtocolStrategy struct {
}
func (TCPStrategy *TransmissionControlProtocolStrategy) Init(beelzebubServiceConfiguration parser.BeelzebubServiceConfiguration, tr tracer.Tracer) error {
listen, err := net.Listen("tcp", beelzebubServiceConfiguration.Address)
if err != nil {
log.Errorf("Error during init TCP Protocol: %s", err.Error())
return err
}
go func() {
for {
if conn, err := listen.Accept(); err == nil {
go func() {
conn.SetDeadline(time.Now().Add(time.Duration(beelzebubServiceConfiguration.DeadlineTimeoutSeconds) * time.Second))
conn.Write([]byte(fmt.Sprintf("%s\n", beelzebubServiceConfiguration.Banner)))
buffer := make([]byte, 1024)
command := ""
if n, err := conn.Read(buffer); err == nil {
command = string(buffer[:n])
}
tr.TraceEvent(tracer.Event{
Msg: "New TCP attempt",
Protocol: tracer.TCP.String(),
Command: command,
Status: tracer.Stateless.String(),
RemoteAddr: conn.RemoteAddr().String(),
ID: uuid.New().String(),
Description: beelzebubServiceConfiguration.Description,
})
conn.Close()
}()
}
}
}()
log.WithFields(log.Fields{
"port": beelzebubServiceConfiguration.Address,
"banner": beelzebubServiceConfiguration.Banner,
}).Infof("Init service %s", beelzebubServiceConfiguration.Protocol)
return nil
}