Stopwatch go lang - go

i have a firewall that sends a discord webhook whenever an attack is detected and whenever the attack is no longer detected. I want to add something where it starts a stopwatch whenever it sends the webhook for attack detected. then stops the stopwatch whenever its no longer detected so that it sends how long the attack lasted in seconds with the no longer detected webhook.
This is for when its detected.
fmt.Println("Rlimit Final", rLimit)
cmd := exec.Command("php", "start.php", strconv.Itoa(reqs), strconv.Itoa(rps), strconv.Itoa(requested), strconv.Itoa(passedcaptcha), "ONLINE", "200", "FIREWALL")
cmd.Run()```
/*and this is when it's no longer detected:*/
if rps <= 20 && mitigation != 0 {
cmd := exec.Command("php", "end.php", strconv.Itoa(totalreqs), strconv.Itoa(largerNumber), strconv.Itoa(totalver), strconv.Itoa(passedcaptcha), "ONLINE", "200", "FIREWALL")
cmd.Run()

Could be something like this, as Burak suggested. Note, that it implies that you have only one firewall which can have only one attack, and the webhooks are located on the same instance, so the attackStartTime.tmp file is reachable for attackEnd.
package main
import (
"fmt"
"io/ioutil"
"log"
"time"
)
func main() {
attackStart()
time.Sleep(time.Second*3)
attackEnd()
}
func attackStart() {
//... my cmd PHP code
fileName := "/tmp/attackStartTime.tmp"
timeAttackStarted := []byte(time.Now().Local().Format(time.RFC3339))
if err := ioutil.WriteFile(fileName, timeAttackStarted, 0666); err != nil {
log.Fatal(err)
}
}
func attackEnd() {
//... my cmd PHP code
fileName := "/tmp/attackStartTime.tmp"
filecontent, err := ioutil.ReadFile(fileName)
timeAttackEnded := time.Now().Local()
if err != nil {
log.Fatal(err)
}
timeAttackStarted, err := time.Parse(time.RFC3339, string(filecontent))
if err != nil {
log.Fatal(err)
}
duration := timeAttackEnded.Sub(timeAttackStarted)
fmt.Printf("attack started at %v:\nattack ended: %v\nduration(seconds): %v\n",timeAttackStarted, timeAttackEnded, duration.Seconds())
}

Related

Undefined: ctx was encountered while running go libp2p

The code is following,it is the an offical demo of go-libp2p.And I didn't encounter any other references or undefined errors
// if a remote peer has been passed on the command line, connect to it
// and send it 5 ping messages, otherwise wait for a signal to stop
if len(os.Args) > 1 {
addr, err := multiaddr.NewMultiaddr(os.Args[1])
if err != nil {
panic(err)
}
peer, err := peerstore.AddrInfoFromP2pAddr(addr)
if err != nil {
panic(err)
}
if err := node.Connect(ctx, *peer); err != nil {
panic(err)
}
fmt.Println("sending 5 ping messages to", addr)
The import is following:
import (
"fmt"
"os"
"os/signal"
"syscall"
"github.com/libp2p/go-libp2p"
peerstore "github.com/libp2p/go-libp2p-core/peer"
"github.com/libp2p/go-libp2p/p2p/protocol/ping"
multiaddr "github.com/multiformats/go-multiaddr"
)
Looks like you are following the "Getting Started" tutorial.
You'll need to import context and prior to the code block in your question, you'll need to create a context:
// create context
ctx:=context.Background()
// if a remote peer has been passed on the command line, connect to it
// and send it 5 ping messages, otherwise wait for a signal to stop
if len(os.Args) > 1 {
addr, err := multiaddr.NewMultiaddr(os.Args[1])
if err != nil {
panic(err)
}
peer, err := peerstore.AddrInfoFromP2pAddr(addr)
if err != nil {
panic(err)
}
if err := node.Connect(ctx, *peer); err != nil {
panic(err)
}
fmt.Println("sending 5 ping messages to", addr)

How to start a telegram bot with different tokens, on 1 server in golang

There is a piece of working code that launches a bot to receive webhooks.
package main
import (
"log"
"net/http"
)
func main() {
bot, err := tgbotapi.NewBotAPI("MyAwesomeBotToken")
if err != nil {
log.Fatal(err)
}
bot.Debug = true
log.Printf("Authorized on account %s", bot.Self.UserName)
_, err = bot.SetWebhook(tgbotapi.NewWebhookWithCert("https://example.com:8443/"+bot.Token, "cert.pem"))
if err != nil {
log.Fatal(err)
}
info, err := bot.GetWebhookInfo()
if err != nil {
log.Fatal(err)
}
if info.LastErrorDate != 0 {
log.Printf("Telegram callback failed: %s", info.LastErrorMessage)
}
updates := bot.ListenForWebhook("/" + bot.Token)
go http.ListenAndServeTLS("0.0.0.0:8443", "cert.pem", "key.pem", nil)
for update := range updates {
log.Printf("%+v\n", update)
}
}
Library for golang - tgbotapi
When I try to launch another bot on the same server, with the same code,
but with a different token, of course, the following happens, the bot is successfully authorized but does not respond to commands, or it simply does not receive a webhook, who knows the reason?
I turn off 1 bot, then the second one starts without problems, at the same time they do not want to..

execute functions in specific order

I have the following function
func (c *Connection) ConnectVpn() error {
cmd := exec.Command(c.Command, c.Args...)
var password bytes.Buffer
password.WriteString(os.Getenv("PASSWORD"))
cmd.Stdin = &password
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err := cmd.Start()
if err != nil {
return err
}
return err
}
This function call the openconnect binary and connects in a private vpn to be able to reach a specific server (it works fine).
The problem is that when I call cmd.Start() it creates a thread and allows me to execute the another function named checkCertificate() but then this function is called before the vpn connects so it fails.
When I try to let the VPN connects and use cmd.RUN() this process do not run on background so the process never finish and it never tells to cmd.Wait() it finished because it shouldn't finish.
days, err := domain.CheckCertificate()
if err != nil {
log.Fatalln(err)
}
I have tried to use channels to try to sync the results between them but when I do this the checkCertificate() function keeps being executed before the VPN executes and I can't reach the server I need.
Any idea in how I could let the ConnectVPN() function be running on foreground and even so send some signal to my other function to say vpn is connected now, please run?
I have tried to send the openconnect to background with cmd.Process.Signal(syscall.SIGTSTP) but when I bring it back it breaks the main function.
I have implemented the function to check if this is connected as was suggested before.
Now it only triggers the other functions if this VPN is connected.
package main
import (
"fmt"
"gitlabCertCheck/request"
"gitlabCertCheck/teams"
"gitlabCertCheck/vpn"
"net/http"
"os"
"strconv"
)
func checker() {
client := http.Client{}
_, err := client.Get(os.Getenv("HTTPS_HOST"))
if err != nil {
checker()
}
return
}
func main() {
args := []string{"--user", os.Getenv("USERNAME"), "--authgroup", "default", "--background",os.Getenv("VPN_SERVER")}
conn := vpn.NewConnection("openconnect", args)
err := conn.ConnectVpn()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
checker()
client := request.Request{}
domain := client.NewRequest(os.Getenv("HOST"), os.Getenv("PORT"))
days, err := domain.CheckCertificate()
if err != nil {
fmt.Println(err)
}
card := teams.Card{}
card.CustomCard.Title = "Certificate Alert"
card.CustomCard.Text = "Certificate will expire in " + strconv.Itoa(days) + " days"
card.NewCard(card.CustomCard)
err = card.SendMessageCard(os.Getenv("TEAMS_WEBHOOK"))
if err != nil {
fmt.Println(err)
}
}
Thank you everyone

Send request repeatedly to the tcp server at regular interval

This is the code taken from the go book. The client enters the message and the request is sent to the server. How to send the same request repeatedly without entering values every time? Also, the time interval between successive requests should be 3 seconds. Should I use goroutines?
package main
import (
"bufio"
"fmt"
"net"
"os"
)
func main() {
arguments := os.Args
if len(arguments) == 1 {
fmt.Println("Please provide host:port.")
return
}
CONNECT := arguments[1]
c, err := net.Dial("tcp", CONNECT)
if err != nil {
fmt.Println(err)
return
}
for {
reader := bufio.NewReader(os.Stdin)
fmt.Print(">>")
text, _ := reader.ReadString('\n')
fmt.Fprintf(c, text+"\n")
}
}
Use a time.Ticker to execute code at some specified interval:
t := time.NewTicker(3 * time.Second)
defer t.Stop()
for range t.C {
_, err := c.Write([]byte("Hello!\n"))
if err != nil {
log.Fatal(err)
}
}
Run it on the playground.

How to works with Golang echo framework and Telegram bot?

I want to use "telegram bot" with "echo framework" (When the server started, echo and telegram bot work together). I used the below code, but when I ran that, the telegram bot didn't start.
My main.go:
package main
import (
"database/sql"
"log"
"net/http"
"strings"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api"
"github.com/labstack/echo"
_ "github.com/mattn/go-sqlite3"
)
func main() {
e := echo.New()
e.GET("/", func(c echo.Context) error {
return c.String(http.StatusOK, "Hello, World!")
})
_ = e.Start(":1323")
db, err := sql.Open("sqlite3", "./criticism.db")
if err != nil {
log.Fatal(err)
}
defer db.Close()
bot, err := tgbotapi.NewBotAPI("")
if err != nil {
log.Fatal(err)
}
bot.Debug = true
log.Printf("Authorized on account %s", bot.Self.UserName)
u := tgbotapi.NewUpdate(0)
u.Timeout = 60
updates, err := bot.GetUpdatesChan(u)
for update := range updates {
if update.Message == nil {
continue
}
gp_msg := tgbotapi.NewMessage(update.Message.Chat.ID, "Hi")
bot.Send(gp_msg)
}
}
The problem is that when you start the echo server, then the code does not go any further.
In order to use both of them, you need to separate each of them into a different thread and also stop your program to finish and stop everything.
The simplest way is to separate the web server and telegram bot and start them separately:
func StartEcho() {
e := echo.New()
e.GET("/", func(c echo.Context) error {
return c.String(http.StatusOK, "Hello, World!")
})
_ = e.Start(":1323")
}
func StartBot() {
bot, err := tgbotapi.NewBotAPI("")
if err != nil {
log.Fatal(err)
}
bot.Debug = true
log.Printf("Authorized on account %s", bot.Self.UserName)
u := tgbotapi.NewUpdate(0)
u.Timeout = 60
updates, err := bot.GetUpdatesChan(u)
for update := range updates {
if update.Message == nil {
continue
}
gp_msg := tgbotapi.NewMessage(update.Message.Chat.ID, "Hi")
bot.Send(gp_msg)
}
}
And then call them:
func main() {
# Start the echo server in a separate thread
go StartEcho()
db, err := sql.Open("sqlite3", "./criticism.db")
if err != nil {
log.Fatal(err)
}
defer db.Close()
# Start the bot in a separate thread
go StartBot()
# To stop the program to finish and close
select{}
# You can also use https://golang.org/pkg/sync/#WaitGroup instead.
}
Or you can just run the last one in the main thread:
func main() {
# Start the echo server in a separate thread
go StartEcho()
db, err := sql.Open("sqlite3", "./criticism.db")
if err != nil {
log.Fatal(err)
}
defer db.Close()
# Start the bot
StartBot()
}
But if the last one stops, so will your entire program and the echo server with it. So you have to recover any panics and don't allow it to stop.

Resources