Skip to content

Commit

Permalink
Check if vpn files exists
Browse files Browse the repository at this point in the history
  • Loading branch information
qu35t-code committed Jan 7, 2024
1 parent d3b3124 commit 919942a
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 19 deletions.
3 changes: 2 additions & 1 deletion cmd/vpn.go
Original file line number Diff line number Diff line change
Expand Up @@ -107,11 +107,12 @@ var vpnCmd = &cobra.Command{
os.Exit(1)
}
} else if stopVPNParam {
_, err := vpn.Stop()
message, err := vpn.Stop()
if err != nil {
config.GlobalConfig.Logger.Error("", zap.Error(err))
os.Exit(1)
}
fmt.Println(message)
}
config.GlobalConfig.Logger.Info("Exit vpn command correctly")
},
Expand Down
23 changes: 12 additions & 11 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ func ConfigureLogger() error {
var err error
GlobalConfig.Logger, err = cfg.Build()
if err != nil {
return fmt.Errorf("Logger configuration error: %v", err)
return fmt.Errorf("logger configuration error: %v", err)
}
zap.ReplaceGlobals(GlobalConfig.Logger)
return nil
Expand All @@ -88,7 +88,7 @@ func LoadConfig(filepath string) (map[string]string, error) {

parts := strings.SplitN(line, "=", 2)
if len(parts) != 2 {
return nil, fmt.Errorf("Incorrectly formatted line in configuration file: %s", line)
return nil, fmt.Errorf("incorrectly formatted line in configuration file: %s", line)
}

key := strings.TrimSpace(parts[0])
Expand All @@ -112,15 +112,15 @@ func validateConfig(key, value string) error {
switch key {
case "Logging", "Batch":
if value != "True" && value != "False" {
return fmt.Errorf("The value for '%s' must be 'True' or 'False', got : %s", key, value)
return fmt.Errorf("the value for '%s' must be 'True' or 'False', got : %s", key, value)
}
case "Proxy":
if value != "False" && !isValidHTTPorHTTPSURL(value) {
return fmt.Errorf("The URL for '%s' must be a valid URL starting with http or https, got : %s", key, value)
return fmt.Errorf("the URL for '%s' must be a valid URL starting with http or https, got : %s", key, value)
}
case "Discord":
if value != "False" && !isValidDiscordWebhook(value) {
return fmt.Errorf("The Discord webhook URL is invalid : %s", value)
return fmt.Errorf("the Discord webhook URL is invalid : %s", value)
}
}

Expand All @@ -145,7 +145,7 @@ func Init() error {
GlobalConfig.Logger.Info(fmt.Sprintf("The \"%s\" folder does not exist, creation in progress...\n", BaseDirectory))
err := os.MkdirAll(BaseDirectory, os.ModePerm)
if err != nil {
return fmt.Errorf("Error folder creation: %s", err)
return fmt.Errorf("error folder creation: %s", err)
}

GlobalConfig.Logger.Info(fmt.Sprintf("\"%s\" folder created successfully\n\n", BaseDirectory))
Expand All @@ -155,21 +155,22 @@ func Init() error {
if _, err := os.Stat(confFilePath); os.IsNotExist(err) {
file, err := os.Create(confFilePath)
if err != nil {
return fmt.Errorf("Error creating file: %v", err)
return fmt.Errorf("error creating file: %v", err)
}
defer file.Close()

configContent := `Discord = False`
configContent := `Discord = False
Update = False`

writer := bufio.NewWriter(file)
_, err = writer.WriteString(configContent)
if err != nil {
return fmt.Errorf("Error when writing to file: %v", err)
return fmt.Errorf("error when writing to file: %v", err)
}

err = writer.Flush()
if err != nil {
return fmt.Errorf("Error clearing buffer: %v", err)
return fmt.Errorf("error clearing buffer: %v", err)
}

GlobalConfig.Logger.Info("Configuration file created successfully.")
Expand All @@ -178,7 +179,7 @@ func Init() error {
GlobalConfig.Logger.Info("Loading configuration file...")
config, err := LoadConfig(BaseDirectory + "/default.conf")
if err != nil {
return fmt.Errorf("Error loading configuration file: %v", err)
return fmt.Errorf("error loading configuration file: %v", err)
}

GlobalConfig.Logger.Info("Configuration successfully loaded")
Expand Down
30 changes: 23 additions & 7 deletions lib/vpn/vpn.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"net/http"
"os"
"os/exec"
"path/filepath"
"strings"
"sync"

Expand Down Expand Up @@ -182,7 +183,21 @@ func DownloadAll() error {

// Start starts the VPN connection using an OpenVPN configuration file.
func Start(configPath string) (string, error) {
fmt.Println("VPN is starting...")
config.GlobalConfig.Logger.Debug(fmt.Sprintf("VPN config file : %s", configPath))
files, err := filepath.Glob(configPath)
if err != nil {
return "", fmt.Errorf("search error : %v", err)
}
if len(files) == 0 {
isConfirmed := utils.AskConfirmation("VPN was not found. Would you like to download it ?")
if isConfirmed {
err := DownloadAll()
if err != nil {
return "", err
}
}
}
config.GlobalConfig.Logger.Info("VPN is starting...")
cmd := "pgrep -fa openvpn"
hacktheboxFound := false
processes, err := exec.Command("sh", "-c", cmd).Output()
Expand Down Expand Up @@ -278,12 +293,12 @@ func Status() (bool, error) {
var result []map[string]interface{}
jsonBody, err := io.ReadAll(resp.Body)
if err != nil {
return false, fmt.Errorf("Error reading response body: %s", err)
return false, fmt.Errorf("error reading response body: %s", err)
}

err = json.Unmarshal(jsonBody, &result)
if err != nil {
return false, fmt.Errorf("Error unmarshalling JSON: %s", err)
return false, fmt.Errorf("error unmarshalling JSON: %s", err)
}

if len(result) == 0 {
Expand All @@ -293,7 +308,7 @@ func Status() (bool, error) {
for _, item := range result {
connectionData, ok := item["connection"].(map[string]interface{})
if !ok {
return false, errors.New("Error asserting connection data")
return false, errors.New("error asserting connection data")
}

name := connectionData["name"]
Expand Down Expand Up @@ -329,7 +344,7 @@ func Stop() (string, error) {
cmd := "pgrep -fa openvpn"
processes, err := exec.Command("sh", "-c", cmd).Output()
if err != nil {
return "", fmt.Errorf("error retrieving OpenVPN processes : %v", err)
return "No vpn connection is active", nil
}

lines := strings.Split(string(processes), "\n")
Expand Down Expand Up @@ -359,7 +374,8 @@ func Stop() (string, error) {
fmt.Printf("Killed HackTheBox VPN process %s\n", processID)
}
}
}
return "Completed checking and stopping HackTheBox VPN processes.", nil

return "Completed checking and stopping HackTheBox VPN processes.", nil
}
return "", nil
}

0 comments on commit 919942a

Please sign in to comment.