85 lines
1.7 KiB
Go
Raw Normal View History

2025-04-17 11:52:47 +02:00
package wazuh
import (
2025-04-18 16:53:31 +02:00
"crypto/tls"
2025-04-17 11:52:47 +02:00
"encoding/json"
2025-04-18 16:53:31 +02:00
"fmt"
"io"
2025-04-17 11:52:47 +02:00
"log"
"net/http"
"forge.cadoles.com/cadoles/wazuh-agent-k8s-autoadd/internal/config"
)
2025-04-18 16:53:31 +02:00
const APIAuthenticate = "/security/user/authenticate"
const APIAgents = "/agents"
2025-04-17 11:52:47 +02:00
2025-04-18 16:53:31 +02:00
type AuthResponse struct {
Data struct {
Token string `json:"token"`
} `json:"data"`
Error int `json:"error"`
}
func getJWT(cfg *config.Config) (string, error) {
req, err := http.NewRequest(http.MethodPost, cfg.BaseURL+APIAuthenticate, http.NoBody)
2025-04-18 16:23:34 +02:00
if err != nil {
2025-04-18 16:53:31 +02:00
return "", fmt.Errorf("cannot create request for %v : %+v", cfg.BaseURL+APIAuthenticate, err)
2025-04-18 16:23:34 +02:00
}
req.SetBasicAuth(cfg.User, cfg.Passwd)
2025-04-18 16:53:31 +02:00
client := http.DefaultClient
if cfg.SkipSSLVerification {
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client = &http.Client{Transport: tr}
}
res, err := client.Do(req)
2025-04-18 16:23:34 +02:00
if err != nil {
2025-04-18 16:53:31 +02:00
return "", err
2025-04-18 16:23:34 +02:00
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
2025-04-18 16:53:31 +02:00
return "", fmt.Errorf("Bad status on %v: %d", cfg.BaseURL+APIAuthenticate, res.StatusCode)
2025-04-18 16:23:34 +02:00
}
2025-04-18 16:53:31 +02:00
body, err := io.ReadAll(res.Body)
2025-04-18 16:23:34 +02:00
if err != nil {
log.Fatal(err)
}
2025-04-18 16:53:31 +02:00
var authInfo AuthResponse
if err := json.Unmarshal(body, &authInfo); err != nil {
return "", fmt.Errorf("Cannot unmarshal JSON: %v", string(body))
}
return authInfo.Data.Token, nil
2025-04-18 16:23:34 +02:00
}
2025-04-18 16:53:31 +02:00
func AddAgent(cfg *config.Config) error {
token, err := getJWT(cfg)
2025-04-18 16:23:34 +02:00
if err != nil {
return err
}
2025-04-18 16:53:31 +02:00
print(token) /*
resp, err := http.DefaultClient.Post(cfg.BaseURL + APIAgents)
if err != nil {
return err
}
defer resp.Body.Close()
2025-04-18 16:23:34 +02:00
2025-04-18 16:53:31 +02:00
switch resp.StatusCode {
case http.StatusOK:
return nil
default:
return false, fmt.Errorf("Bad status: %d", resp.StatusCode)
}
*/
2025-04-18 16:23:34 +02:00
return nil
2025-04-17 11:52:47 +02:00
}