Skip to content

Commit

Permalink
Add level logger to all code
Browse files Browse the repository at this point in the history
  • Loading branch information
qu35t-code committed Dec 19, 2023
1 parent 1c297d0 commit 1911deb
Show file tree
Hide file tree
Showing 9 changed files with 89 additions and 54 deletions.
58 changes: 37 additions & 21 deletions cmd/info.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
"os"
"strings"
Expand All @@ -14,6 +13,7 @@ import (
"github.com/GoToolSharing/htb-cli/config"
"github.com/GoToolSharing/htb-cli/lib/utils"
"github.com/spf13/cobra"
"go.uber.org/zap"
)

type Response struct {
Expand All @@ -24,7 +24,7 @@ type Response struct {
// Retrieves data for user profile
func fetchData(itemID string, endpoint string, infoKey string) (map[string]interface{}, error) {
url := config.BaseHackTheBoxAPIURL + endpoint + itemID
log.Println("URL :", url)
config.GlobalConfig.Logger.Debug(fmt.Sprintf("URL: %s", url))

resp, err := utils.HtbRequest(http.MethodGet, url, nil)
if err != nil {
Expand Down Expand Up @@ -67,8 +67,8 @@ func fetchAndDisplayInfo(url, header string, params []string, elementType string
return fmt.Errorf("infoKey not defined")
}

log.Println("URL :", url)
log.Println("InfoKey :", infoKey)
config.GlobalConfig.Logger.Debug(fmt.Sprintf("URL: %s", url))
config.GlobalConfig.Logger.Debug(fmt.Sprintf("InfoKey: %s", infoKey))

info := utils.ParseJsonMessage(resp, infoKey)
data := info.(map[string]interface{})
Expand Down Expand Up @@ -150,7 +150,7 @@ func coreInfoCmd(machineName []string, challengeName []string, usernameName []st
if isConfirmed {
err := displayActiveMachine(machineHeader)
if err != nil {
log.Fatal(err)
return err
}
}
// Get current account
Expand All @@ -176,7 +176,7 @@ func coreInfoCmd(machineName []string, challengeName []string, usernameName []st
if isConfirmed {
err := displayActiveMachine(info.Header)
if err != nil {
log.Fatal(err)
return err
}
}
}
Expand Down Expand Up @@ -209,13 +209,19 @@ func getIPStatus(data map[string]interface{}) interface{} {

// displayActiveMachine displays information about the active machine if one is found.
func displayActiveMachine(header string) error {
machineID := utils.GetActiveMachineID()
expiresTime := utils.GetActiveExpiredTime()
machineID, err := utils.GetActiveMachineID()
if err != nil {
return err
}
expiresTime, err := utils.GetActiveExpiredTime()
if err != nil {
return err
}

if machineID != "" {
log.Println("Active machine found !")
log.Println("Machine ID:", machineID)
log.Println("Expires At:", expiresTime)
config.GlobalConfig.Logger.Info("Active machine found !")
config.GlobalConfig.Logger.Debug(fmt.Sprintf("Machine ID: %s", machineID))
config.GlobalConfig.Logger.Debug(fmt.Sprintf("Expires At: %v", expiresTime))

layout := "2006-01-02 15:04:05"

Expand All @@ -225,7 +231,7 @@ func displayActiveMachine(header string) error {
}

now := time.Now()
log.Println("Actual date :", now)
config.GlobalConfig.Logger.Debug(fmt.Sprintf("Actual date: %v", now))
var remainingTime string
if date.After(now) {
duration := date.Sub(now)
Expand All @@ -241,18 +247,18 @@ func displayActiveMachine(header string) error {
jsonData := []byte("{\"machine_id\":" + machineID + "}")
resp, err := utils.HtbRequest(http.MethodPost, config.BaseHackTheBoxAPIURL+"/vm/extend", jsonData)
if err != nil {
log.Fatal(err)
return err
}
var response Response
if err := json.NewDecoder(resp.Body).Decode(&response); err != nil {
log.Fatalf("Error decoding JSON response: %v", err)
return fmt.Errorf("Error decoding JSON response: %v", err)
}

inputLayout := time.RFC3339Nano

date, err := time.Parse(inputLayout, response.ExpiresAt)
if err != nil {
log.Fatalf("Error decoding JSON response: %v", err)
return fmt.Errorf("Error decoding JSON response: %v", err)
}

outputLayout := "2006-01-02 -> 15h 04m 05s"
Expand Down Expand Up @@ -283,17 +289,26 @@ func displayActiveMachine(header string) error {
return err
}

machineType := utils.GetMachineType(machineID)
log.Printf("Machine Type: %s", machineType)
machineType, err := utils.GetMachineType(machineID)
if err != nil {
return err
}
config.GlobalConfig.Logger.Debug(fmt.Sprintf("Machine Type: %s", machineType))

userSubscription := utils.GetUserSubscription()
log.Printf("User subscription: %s", userSubscription)
userSubscription, err := utils.GetUserSubscription()
if err != nil {
return err
}
config.GlobalConfig.Logger.Debug(fmt.Sprintf("User subscription: %s", userSubscription))

ip := "Undefined"
_ = ip
switch {
case userSubscription == "vip+" || machineType == "release":
ip = utils.GetActiveMachineIP()
ip, err = utils.GetActiveMachineIP()
if err != nil {
return err
}
default:
ip = getIPStatus(data).(string)
}
Expand Down Expand Up @@ -336,7 +351,8 @@ var infoCmd = &cobra.Command{
}
err = coreInfoCmd(machineParam, challengeParam, usernameParam)
if err != nil {
log.Fatal(err)
config.GlobalConfig.Logger.Error("", zap.Error(err))
os.Exit(1)
}
},
}
Expand Down
3 changes: 1 addition & 2 deletions cmd/pwnbox.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package cmd

import (
"fmt"
"log"
"net/http"

"github.com/GoToolSharing/htb-cli/config"
Expand Down Expand Up @@ -56,7 +55,7 @@ var pwnboxCmd = &cobra.Command{
}

// Check subscription
log.Println("Mode :" + modeFlag)
config.GlobalConfig.Logger.Debug(fmt.Sprintf("Mode: %s", modeFlag))

if startFlag {
fmt.Println("Sorry, but HackTheBox currently uses a v3 recaptcha to start a pwnbox.")
Expand Down
30 changes: 18 additions & 12 deletions cmd/reset.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,27 +3,34 @@ package cmd
import (
"encoding/json"
"fmt"
"log"
"net/http"
"os"

"github.com/GoToolSharing/htb-cli/config"
"github.com/GoToolSharing/htb-cli/lib/utils"
"github.com/GoToolSharing/htb-cli/lib/webhooks"
"github.com/spf13/cobra"
"go.uber.org/zap"
)

// coreResetCmd sends a reset request for an active machine.
func coreResetCmd() (string, error) {
// Retrieve the ID of the active machine.
machineID := utils.GetActiveMachineID()
machineID, err := utils.GetActiveMachineID()
if err != nil {
return "", err
}
if machineID == "" {
return "No active machine found", nil
}
log.Printf("Machine ID: %s", machineID)
config.GlobalConfig.Logger.Debug(fmt.Sprintf("Machine ID: %s", machineID))

// Retrieve the type of the machine.
machineType := utils.GetMachineType(machineID)
log.Printf("Machine Type: %s", machineType)
machineType, err := utils.GetMachineType(machineID)
if err != nil {
return "", err
}
config.GlobalConfig.Logger.Debug(fmt.Sprintf("Machine Type: %s", machineType))

// Determine the API endpoint and construct JSON data based on the machine type.
var endpoint string
Expand Down Expand Up @@ -64,14 +71,13 @@ var resetCmd = &cobra.Command{
// Execute the core reset function and handle the results.
output, err := coreResetCmd()
if err != nil {
log.Fatalf("Error: %v", err)
config.GlobalConfig.Logger.Error("", zap.Error(err))
os.Exit(1)
}
if config.ConfigFile["Discord"] != "False" {
err := webhooks.SendToDiscord("[RESET] - " + output)
if err != nil {
fmt.Println(err)
return
}
err = webhooks.SendToDiscord("[RESET] - " + output)
if err != nil {
config.GlobalConfig.Logger.Error("", zap.Error(err))
os.Exit(1)
}
fmt.Println(output)
},
Expand Down
3 changes: 1 addition & 2 deletions cmd/sherlocks.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package cmd

import (
"fmt"
"log"
"net/http"
"os"

Expand Down Expand Up @@ -48,7 +47,7 @@ var sherlocksCmd = &cobra.Command{
fmt.Println(err)
return
}
log.Println("SherlockID :", sherlockID)
config.GlobalConfig.Logger.Debug(fmt.Sprintf("SherlockID: %s", sherlockID))

if sherlockTaskID != 0 {
err := sherlocks.GetTaskByID(sherlockID, sherlockTaskID, sherlockHint)
Expand Down
15 changes: 12 additions & 3 deletions cmd/start.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,16 @@ func coreStartCmd(machineChoosen string) (string, error) {
}
config.GlobalConfig.Logger.Info(fmt.Sprintf("Machine ID: %s", machineID))

machineType := utils.GetMachineType(machineID)
machineType, err := utils.GetMachineType(machineID)
if err != nil {
return "", err
}
config.GlobalConfig.Logger.Info(fmt.Sprintf("Machine Type: %s", machineType))

userSubscription := utils.GetUserSubscription()
userSubscription, err := utils.GetUserSubscription()
if err != nil {
return "", err
}
config.GlobalConfig.Logger.Info(fmt.Sprintf("User subscription: %s", userSubscription))

// isActive := utils.CheckVPN()
Expand Down Expand Up @@ -87,7 +93,10 @@ func coreStartCmd(machineChoosen string) (string, error) {
s.Stop()
return "", nil
default:
ip = utils.GetActiveMachineIP()
ip, err = utils.GetActiveMachineIP()
if err != nil {
return "", err
}
if ip != "Undefined" {
s.Stop()
break Loop
Expand Down
15 changes: 12 additions & 3 deletions cmd/stop.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,16 +45,25 @@ func coreStopCmd() (string, error) {
// if err != nil {
// return "", err
// }
machineID := utils.GetActiveMachineID()
machineID, err := utils.GetActiveMachineID()
if err != nil {
return "", err
}
if machineID == "" {
return "No machine is running", nil
}
config.GlobalConfig.Logger.Debug(fmt.Sprintf("Machine ID: %s", machineID))

machineType := utils.GetMachineType(machineID)
machineType, err := utils.GetMachineType(machineID)
if err != nil {
return "", err
}
config.GlobalConfig.Logger.Debug(fmt.Sprintf("Machine Type: %s", machineType))

userSubscription := utils.GetUserSubscription()
userSubscription, err := utils.GetUserSubscription()
if err != nil {
return "", err
}
config.GlobalConfig.Logger.Debug(fmt.Sprintf("User subscription: %s", userSubscription))

apiEndpoint, jsonData := buildMachineStopRequest(machineType, userSubscription, machineID)
Expand Down
7 changes: 3 additions & 4 deletions lib/sherlocks/sherlocks.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import (
"errors"
"fmt"
"io"
"log"
"net/http"
"os"
"strconv"
Expand Down Expand Up @@ -46,7 +45,7 @@ func getDownloadLink(sherlockID string) (string, error) {
return "", err
}

log.Println("Download URL :", data.URL)
config.GlobalConfig.Logger.Debug(fmt.Sprintf("Download URL: %s", data.URL))
return data.URL, nil
}

Expand Down Expand Up @@ -138,7 +137,7 @@ func GetTaskByID(sherlockID string, sherlockTaskID int, sherlockHint bool) error
return err
}
flag = strings.TrimSpace(flag)
log.Println(flag)
config.GlobalConfig.Logger.Debug(fmt.Sprintf("Flag: %s", flag))
taskID := strconv.Itoa(sherlockData.Tasks[sherlockTaskID-1].ID)

message, err := submitTask(sherlockID, taskID, flag)
Expand Down Expand Up @@ -196,7 +195,7 @@ func GetGeneralInformations(sherlockID string, sherlockDownloadPath string) erro
}
}

log.Println(info)
config.GlobalConfig.Logger.Debug(fmt.Sprintf("Informations: %v", info))
fmt.Println("Scenario :", info["scenario"])
fmt.Println("\nFile :", info["file_name"])
fmt.Println("File Size :", info["file_size"])
Expand Down
3 changes: 1 addition & 2 deletions lib/sherlocks/tui.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package sherlocks

import (
"fmt"
"log"

"github.com/GoToolSharing/htb-cli/config"
"github.com/rivo/tview"
Expand Down Expand Up @@ -39,7 +38,7 @@ func GetColorFromDifficultyText(difficultyText string) string {

// CreateFlex creates and returns a Flex view with machine information
func CreateFlex(info interface{}, title string, isScheduled bool) (*tview.Flex, error) {
log.Println("Info :", info)
config.GlobalConfig.Logger.Debug(fmt.Sprintf("Info: %v", info))
flex := tview.NewFlex().SetDirection(tview.FlexRow)
flex.SetBorder(true).SetTitle(title).SetTitleAlign(tview.AlignLeft)

Expand Down
9 changes: 4 additions & 5 deletions lib/submit/submit.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
"os"
"strconv"
Expand Down Expand Up @@ -47,7 +46,7 @@ func CoreSubmitCmd(difficultyParam int, machineNameParam string, challengeNamePa
if err != nil {
return "", err
}
log.Printf("Machine Type: %s", machineType)
config.GlobalConfig.Logger.Debug(fmt.Sprintf("Machine Type: %s", machineType))

if machineType == "release" {
url = config.BaseHackTheBoxAPIURL + "/arena/own"
Expand All @@ -68,7 +67,7 @@ func CoreSubmitCmd(difficultyParam int, machineNameParam string, challengeNamePa
if err != nil {
return "", err
}
log.Printf("Machine Type: %s", machineType)
config.GlobalConfig.Logger.Debug(fmt.Sprintf("Machine Type: %s", machineType))

if machineType == "release" {
url = config.BaseHackTheBoxAPIURL + "/arena/own"
Expand All @@ -89,8 +88,8 @@ func CoreSubmitCmd(difficultyParam int, machineNameParam string, challengeNamePa
flag := strings.ReplaceAll(flagOriginal, " ", "")
payload["flag"] = flag

log.Println("Flag :", flag)
log.Println("Difficulty :", difficultyString)
config.GlobalConfig.Logger.Debug(fmt.Sprintf("Flag: %s", flag))
config.GlobalConfig.Logger.Debug(fmt.Sprintf("Difficulty: %s", difficultyString))

jsonData, err := json.Marshal(payload)
if err != nil {
Expand Down

0 comments on commit 1911deb

Please sign in to comment.