added random suffix and prefix list

This commit is contained in:
gurkenhabicht 2025-01-11 02:36:21 +01:00
parent 35ec77e5c6
commit b6056297f4
5 changed files with 1034 additions and 16 deletions

View File

@ -7,8 +7,12 @@ import (
"log"
"net/http"
"net/url"
// "os"
"os/exec"
// "time"
"time"
"math/rand"
"math"
"strconv"
"github.com/gorilla/websocket"
)
@ -17,12 +21,13 @@ const(
webServerAddr = "127.0.0.1:3333"
webSocketAddr = "127.0.0.1:5555"
registerURL = "http://" + webServerAddr + "/agents"
wsURL = "ws://" + webSocketAddr + "/data"
// wsURL = "ws://" + webSocketAddr + "/data"
)
type Agent struct {
AgentName string `json:"agentName"`
AgentID string `json:"agentId"`
AgentIP string `json:"agentIp"`
InitialContact string `json:"initialContact"`
LastContact string `json:"lastContact"`
}
@ -30,7 +35,7 @@ type Agent struct {
var conn *websocket.Conn
func registerAgent(agentName string, agentId string) error {
func registerAgent(agentName string, agentId string, agentIp string) error {
// agent:= Agent{
// AgentName: agentName,
// InitialContact: time.Now().Format(time.RFC3339),
@ -47,6 +52,7 @@ func registerAgent(agentName string, agentId string) error {
form := url.Values{}
form.Add("agentId", agentId)
form.Add("agentName", agentName)
form.Add("IPv4Address", agentIp)
resp, err := http.PostForm(registerURL, form)
if err != nil {
@ -63,7 +69,8 @@ func registerAgent(agentName string, agentId string) error {
}
func connectToWebSocket() error {
func connectToWebSocket(agentName string, agentIp string) error {
wsURL := fmt.Sprintf("ws://%s/data?agentName=%s&IPv4Address=%s", webSocketAddr, url.QueryEscape(agentName), url.QueryEscape(agentIp))
var err error
conn, _, err = websocket.DefaultDialer.Dial(wsURL, nil)
if err != nil {
@ -102,15 +109,25 @@ func listenForCommands() {
}
}
func randomInt(length int) int {
rand.Seed(time.Now().UnixNano())
min := int(math.Pow10(length-1))
max := int(math.Pow10(length)) -1
return rand.Intn(max-min+1) + min
}
func main() {
agentName := "Agent-001"
agentId := "1234"
// agentId := "1234"
agentId := strconv.Itoa(randomInt(5))
agentIp := "127.0.0.1"
if err := registerAgent(agentName, agentId); err != nil {
if err := registerAgent(agentName, agentId, agentIp); err != nil {
log.Fatalf("Agent registration failed: %v", err)
}
if err := connectToWebSocket(); err != nil {
if err := connectToWebSocket(agentName, agentIp); err != nil {
log.Fatalf("Websocket connection failed: %v", err)
}

65
main.go
View File

@ -2,6 +2,7 @@ package main
import (
"context"
"encoding/json"
"os"
"strings"
"time"
@ -271,7 +272,7 @@ func updateAgent(w http.ResponseWriter, r *http.Request, agentId string) {
lastContact := r.FormValue("lastContact")
IPv4Address := r.FormValue("IPv4Address")
query := "UPDATE agents SET agentName = ?, IPv4Address= ?, lastContact = ? where agentId = ?"
query := "UPDATE agents SET agentName = ?, IPv4Address = ?, lastContact = ? where agentId = ?"
_, err = db.Exec(query, agentName, IPv4Address, lastContact, agentId)
if err != nil {
http.Error(w, "Failed to update agent", http.StatusInternalServerError)
@ -342,6 +343,29 @@ func getAgent(w http.ResponseWriter, r *http.Request, agentId string) {
}
func getAgentNames(w http.ResponseWriter, r *http.Request) {
query := "SELECT agentName from agents"
rows, err := db.Query(query)
if err != nil {
http.Error(w, "Failed to fetch agent names", http.StatusInternalServerError)
return
}
defer rows.Close()
var agentNames []string
for rows.Next() {
var name string
if err := rows.Scan(&name); err != nil {
http.Error(w, "Error reading agent names", http.StatusInternalServerError)
return
}
agentNames = append(agentNames, name)
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(agentNames)
}
type webSocketHandler struct {
upgrader websocket.Upgrader
}
@ -368,6 +392,42 @@ func (wsh webSocketHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
}
// func executeCommand(w http.ResponseWrite, r *http.Request) {
// }
var agentSockets = make(map[string]*websocket.Conn)
var agentSocketsMutex sync.Mutex
var executeCommand http.HandlerFunc = func(w http.ResponseWriter, r *http.Request){
err := r.ParseForm()
if err != nil {
http.Error(w, "Invalid form data", http.StatusBadRequest)
}
agentName := r.FormValue("agentName")
command := r.FormValue("command")
agentSocketsMutex.Lock()
conn, ok := agentSockets[agentName]
agentSocketsMutex.Unlock()
if !ok {
http.Error(w, "Agent not connected", http.StatusNotFound)
return
}
err = conn.WriteMessage(websocket.TextMessage, []byte(command))
if err != nil {
http.Error(w, "Failed to send command to the agent", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
w.Write([]byte("Command sent successfully"))
}
func main() {
ctx, cancel := context.WithCancel(context.Background())
@ -380,7 +440,9 @@ func main() {
}
webSocketMux := http.NewServeMux()
// webSocketMux.Handle("/data", webSocketHandler)
webSocketMux.Handle("/data", webSocketHandler)
webSocketMux.Handle("/executeCommand", executeCommand)
websocketServer := &http.Server{
Addr: ":5555",
Handler: webSocketMux,
@ -392,6 +454,7 @@ func main() {
// webMux.HandleFunc("/hello", getHello)
// webMux.HandleFunc("/agents", fetchAgents)
webMux.HandleFunc("/agents", agentsHandler)
webMux.HandleFunc("/agentNames", getAgentNames)
// webMux.HandleFunc("/newagentform", getAgentForm)
// webMux.HandleFunc("/getagentupdateform/{agentId}", getAgentUpdateForm)
webMux.HandleFunc("/agents/{agentId}", agentsHandler)

712
prefix_adjectives Normal file
View File

@ -0,0 +1,712 @@
abiding
abounding
abundant
academic
acceptable
accepting
accessible
acclaimed
accommodating
accountable
accurate
actionable
active
actual
adaptable
adaptive
adequate
admirable
adored
advantageous
advisable
affectionate
agreeable
agricultural
alert
alive
alluring
amazed
ambitious
amicable
amusing
animated
appealing
appetizing
appreciative
approachable
appropriate
ardent
arresting
artful
articulate
artistic
aspiring
assertive
assured
assuring
astonishing
astounding
astronomical
astute
athletic
attainable
attractive
auspicious
authoritative
avid
awake
aware
balance
banging
beaming
beautiful
bedazzled
bedazzling
believable
beloved
beneficial
benevolent
benign
better
bewildering
bewitching
big-hearted
bilingual
blameless
blazing
blessed
blissful
blooming
blossoming
blushing
bodacious
boisterous
bold
bouncy
boundless
boyish
brainy
brave
bravo
brawny
brazen
breathtaking
breezy
bright
brilliant
buoyant
bustling
calm
calming
candid
capable
captivated
captivating
carefree
careful
caring
cautious
ceaseless
celebrated
celestial
centered
cerebral
ceremonial
certified
changeable
charismatic
charitable
charmed
charming
chatty
cheeky
cheerful
cheery
childlike
chivalrous
choice
chuckling
cinematic
civilized
classic
classical
clean
clear
clearheaded
clever
close
coachable
cognitive
coherent
cohesive
collaborative
collegial
colloquial
colorful
colossal
comfortable
comforted
comforting
commanding
commemorative
commendable
committed
communicative
compact
compassionate
compelling
competent
complete
completed
complex
complimentary
comprehensive
conceivable
concerted
concise
confident
confidential
confirmable
confirmed
congruent
connected
conscientious
conscious
consensual
consenting
conservative
considerate
consistent
consoling
conspiratorial
contented
cool
countryside
courageous
cozy
creative
cryptic
cultured
dainty
dapper
daring
dashing
daughterly
dazzling
dear
debonair
decadent
decisive
decorative
decorous
dedicated
deep
defendable
defensible
definable
definitive
delectable
deliberate
deliberative
delicious
delighted
delightful
demonstrative
demure
dependable
designer
desirous
detailed
determined
devoted
devout
didactic
dignified
diligent
dim
diplomatic
direct
disarming
disciplined
discontented
discreet
discriminating
distant
distinct
distinguished
distracting
diverse
diversified
dizzying
doable
dogged
dogmatic
domestic
dominant
doting
dramatic
dreamy
dressy
driven
dusky
dutiful
dynamic
early
earnest
earthy
easy-going
easygoing
eccentric
economical
ecstatic
edgy
educated
educational
effective
effervescent
efficient
effortless
effusive
egalitarian
elaborate
electric
electrifying
elegant
elevated
eligible
elite
eloquent
emblematic
emboldened
empathetic
empirical
enamored
enchanted
enchanting
encouraged
encouraging
endearing
endurable
enduring
energetic
energizing
enforceable
engrossing
enhanced
enigmatic
enjoyable
enlightened
enough
enterprising
entertained
entertaining
enthralled
enthused
enthusiastic
enticing
entire
entranced
entrepreneurial
enumerable
enviable
equal
equitable
erect
essential
established
eternal
ethereal
ethical
euphoric
even
eventful
everlasting
evocative
exact
exalted
excellent
exceptional
excitable
excited
exciting
exclusive
executable
exhaustive
exhilarated
exhilarating
exotic
expansive
expectant
expected
exquisite
extensive
extraordinary
exuberant
fabled
fabulous
factual
fair
fairy-tale-like
faithful
famous
fantastic
far-flung
farming-related
fascinated
fascinating
fashionable
fastidious
fateful
fatherly
fathomable
favorable
favourite
fearless
fertile
fervent
fetching
fierce
fiery
fine
firm
first
fit
flamboyant
flashy
flattered
flattering
flavorful
flawless
flexible
flirtatious
flowery
fluent
fluffy
focused
fond
foreseeable
forgivable
forgiving
formal
formative
formidable
forthright
fortuitous
fortunate
forward
foxy
fragrant
frank
fraternal
free
freedom
fresh
friendly
frisky
fulfilled
fulfilling
full
fun
functional
fundamental
funny
futuristic
gainful
gallant
game
generous
genial
genius
gentle
genuine
giant
giddy
gifted
gigantic
giggling
giving
glad
glaring
gleaming
glittering
glorious
glossy
glowing
golden
good-looking
goof
gorgeous
graceful
gracious
grandiose
grateful
gratified
gratifying
great
greatest
grinning
gripping
groomed
groovy
guaranteed
guiltless
gutsy
hallowed
handsome
happy
hard-working
hardworking
hardy
harmless
harmonic
harmonious
heady
healthy
heart-warming
hearty
heavenly
heedful
helpful
heroic
high
historic
historical
holistic
homey
honest
honourable
hopeful
hot
huggable
human
humble
hygienic
idealistic
illimitable
illuminating
illustrious
imaginative
immaculate
immeasurable
immense
immortal
immovable
impartial
impassioned
impenetrable
impervious
important
impressive
improved
improving
inalienable
incandescent
inclusive
incomparable
incontrovertible
incredible
industrious
inexpensive
infinite
influenced
influential
informative
informed
ingenuous
inhabitable
innovative
inquisitive
insightful
inspirational
inspiring
intelligent
intense
intensity
interesting
intriguing
invaluable
inviting
iridescent
jadeite
jaunty
jazzed
jentacular
jocular
jocund
jovial
joyful
jubilant
judicious
kaleidoscopic
keen
kidding
kind
kindhearted
kinetic
kingly
king-sized
kissable
kissy
knowable
knowledgeable
kooky
kosher
kudos
laughable
lengthy
liberal
light-hearted
likable
limitless
listenable
lively
lofty
logical
loveable
loving
loyal
lucky
luminous
luxurious
luxury
magical
magnetic
marketable
maternal
mature
meaningful
meditative
merciful
merry
mindful
miraculous
modest
motivational
moving
mysterious
mystical
naughty
neighborly
new
nostalgic
notable
noteworthy
nutritious
obedient
observant
okay
open
open-minded
optimistic
organized
original
otherworldly
outstanding
overflowing
palatial
parental
passionate
pastoral
paternal
patient
peaceful
peerless
perceptive
personable
phenomenal
pioneering
playful
pleasant
polite
positive
powerful
practical
precocious
premium
pretty
pristine
productive
prolific
protective
proud
pure
qualified
quantifiable
quick
quiet
quirky
quotable
radiant
rational
real
realistic
refreshing
regal
rejuvenating
relaxed
relevant
reliable
remarkable
reserved
resilient
resourceful
respectful
responsive
reverent
rich
right
romantic
roomy
rural
safety
sand-covered
sandy
sane
satisfied
scrupulous
seemly
sensational
sensible
sensitive
sentimental
serene
sexy
shiny
sincere
smart
sociable
soulful
spacious
spirited
spotless
steady
stimulating
straightforward
strong
stunning
suave
successful
sufficient
sun-drenched
sun-soaked
superb
sweet
tactful
tenacious
terrific
thoughtful
towering
tranquil
trustworthy
unique
unspoiled/unspoilt
uplifting
vast
vibrant
vivacious
wholesome
willing
xenial
yielding
youthful
zestful

194
suffix_names Normal file
View File

@ -0,0 +1,194 @@
Ai
Albjofe
Alfr
Amras
Amrod
An
Anarr
Anduin
Andvari
Aragorn
Arathorn
Aredhel
Artanis
Arwen
Austri
Bafurr
Beleg
Beorn
Beren
Bilbo
Billingr
Bomburr
Boromir
Bruni
Bufurr
Buldr
Buri
Caranthir
Celeborn
Celebrian
Celebrían
Celegorm
Cirdan
Círdan
Cotton
Curufin
Dainn
Damrod
Denethor
Dilgbrasir
Dori
Draupnir
Dufr
Duilin
Durinn
Dvalinn
Eärendil
Eärwen
Ecthelion
Eikinskjaldi
Eldarion
Elendil
Elessar
Elladan
Elrohir
Elrond
Eluréd
Elurín
Elwing
Envinyatar
Eöl
Eomer
Eowyn
Éowyn
Erestor
Faniel
Faramir
Fëanor
Fili
Finduilas
Fingolfin
Fingon
Finnr
Finrod
Flalarr
Frar
Frawgr
Frodo
Frosti
Fundinn
Galadriel
Gandalf
Gandalfr
Gildor
Gil-galad
Gilwen
Gimli
Ginnarr
Gloinn
Glorfindel
Goldberry
Gollum
Haldir
Hanarr
Har
Haugspori
Hepti
Hirnbori
Hlevangr
Húrin
Idril
Imladris
Indis
Isildur
Isilme
Istarien
Itarillë
Idril
Jari
Kili
Lalaith
Legolas
Lindir
Lissë
Litr
Lofarr
Loni
Lothíriel
Luthien
Lúthien
Maedhros
Maeglin
Maglor
Melian
Meneldor
Merry
Brandybuck
Míriel
Morwen
Motsognir
Nainn
Nali
Nar
Narr
Nellas
Nerdanel
Nessa
Nienna
Nienor
Nimloth
Nimrodel
Níniel
Nioi
Nipingr
Nori
Norori
Nyraor
Nyu
Ori
Orodreth
Orophin
Pekkr
Pengolodh
Pippin
Took
Porinn
Prainn
Pror
Qurvangr
Raosvidr
Reginn
Rosamunda
Rúmil
Samwise
Gamgee
Saruman
Sauron
Skafidr
Skirvir
Suori
Sviorr
Tauriel
Theoden
Théoden
Thingol
Thorin
Thranduil
Tinúviel
Treebeard
Tuor
Turambar
Turgon
Urwen
Vairë
Varda
Veigr
Vestri
Vievir
Vili
Vindalfr
Vitr
Wormtongue
Yavanna
Yngvi

View File

@ -17,6 +17,22 @@
console.error(evt.detail.xhr.responseText);
});
</script>
<script>
document.addEventListener('DOMContentLoaded', () => {
fetch('/agentNames')
.then(response => response.json())
.then(agentNames => {
const dropdown = document.getElementById('agentName');
agentNames.forEach(name => {
const option = document.createElement('option');
option.value = name;
option.textContent = name;
dropdown.appendChild(option);
});
})
.catch(error => console.error('Error fetching agent names:', error));
});
</script>
</head>
<body>
<div class="container">
@ -26,15 +42,31 @@
<!-- Agent List -->
<div id="agentList" hx-get="/agents" hx-trigger="load" hx-swap="innerHTML"></div>
<!-- Agent Commands -->
<div id="agentCommands">
<h3>Command Execution</h3>
<form hx-post="/agents/{agentId}/commands" hx-target="#commandOutput" hx-swap="innerHTML">
<input type="text" name="command" placeholder="Enter command" required>
<button type="submit" class="btn btn-primary">Execute</button>
</form>
<pre id="commandOutput"></pre>
</div>
<h3>Command Execution</h3>
<form hx-post="/executeCommand" hx-target="#commandOutput" hx-swap="innerHTML">
<div class="mb-3">
<label for="agentName" class="form-label">Agent Name</label>
<select class="form-select" id="agentName" name="agentName" required>
<!-- Dynamically populated with agent names -->
</select>
</div>
<div class="mb-3">
<label for="command" class="form-label">Command</label>
<input type="text" class="form-control" id="command" name="command" placeholder="Enter command" required>
</div>
<button type="submit" class="btn btn-primary">Execute</button>
</form>
<pre id="commandOutput"></pre>
</div>
<!-- <form hx-post="/agents/{agentId}/commands" hx-target="#commandOutput" hx-swap="innerHTML"> -->
<!-- <input type="text" name="command" placeholder="Enter command" required> -->
<!-- <button type="submit" class="btn btn-primary">Execute</button> -->
<!-- </form> -->
<!-- <pre id="commandOutput"></pre> -->
</div>
<!-- Add Agent Form -->
<button class="btn btn-primary mt-3" data-bs-toggle="collapse" data-bs-target="#addAgentForm">Add Agent</button>