-
Notifications
You must be signed in to change notification settings - Fork 0
/
failedLogins.go
95 lines (89 loc) · 2.12 KB
/
failedLogins.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package main
import (
"bufio"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
"github.com/alecthomas/kingpin/v2"
"github.com/clly/failedLogins/assets"
"github.com/vjeantet/grok"
)
var (
file = kingpin.Arg("file", "Filename to get IP addresses from").String()
ipMap = make(map[string]int)
reportPath = "/root/report/%s"
)
func main() {
kingpin.Parse()
absolutePath, err := filepath.Abs(*file)
assets.RestoreAssets("/tmp", "patterns")
parser, err := grok.NewWithConfig(&grok.Config{NamedCapturesOnly: true})
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
parser.AddPatternsFromPath("/tmp/patterns")
if err != nil {
fmt.Println(err)
}
if err != nil {
fmt.Println(err)
}
fd, err := os.Open(absolutePath)
if err != nil {
fmt.Println(err)
}
defer fd.Close()
scanner := bufio.NewScanner(fd)
for scanner.Scan() {
line := scanner.Text()
values, err := parser.Parse("%{IP_FROM_SECURE}", line)
if err != nil {
fmt.Println(err)
}
ip := values["ip"]
if ip != "" {
ipMap[ip]++
}
}
dateFormat := time.Now().Format(time.DateOnly)
dateReportPath := fmt.Sprintf(reportPath, dateFormat)
fmt.Println(dateReportPath)
wfd, err := os.OpenFile(dateReportPath, os.O_RDWR, 0666)
if serr, ok := err.(*os.PathError); ok {
wfd, err = os.Create(dateReportPath)
fmt.Println(serr, "Creating Path")
}
defer wfd.Close()
buffWriter := bufio.NewWriter(wfd)
for k, v := range ipMap {
if v > 30 {
line := fmt.Sprintf("/usr/bin/sudo firewall-cmd --permanent --add-rich-rule 'rule family=\"ipv4\" source address=\"%s\" service name=\"ssh\" log limit value=\"30/m\" audit reject' # Requested %v times\n", k, v)
err := blockIP(line)
if err != nil {
errLine := fmt.Sprintf("Failed to block ip %s requested %v times", k, v)
buffWriter.WriteString(errLine)
}
fmt.Print(line)
buffWriter.WriteString(line)
}
}
buffWriter.Flush()
}
func blockIP(cmd string) error {
cmdSl := strings.SplitN(cmd, " ", 1)
command := cmdSl[0]
args := cmdSl[1]
eCmd := exec.Command(command, args)
err := eCmd.Run()
return err
}
/*
func getReportPath() {
now := time.Now()
now.Format()
}
*/