-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
212 lines (172 loc) · 4.94 KB
/
main.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
package main
import (
"encoding/json"
"fmt"
"github.com/hpcloud/tail"
"io"
"log"
"net/http"
"net/url"
"os"
"os/exec"
"strings"
"time"
)
type TelegramResponse struct {
OK bool `json:"ok"`
Description string `json:"description"`
}
func SendMessage(chat, token, message string) error {
if chat == "" || token == "" {
// If no configuration provided, don't do anything
return nil
}
endpoint := "https://api.telegram.org/bot" + token + "/sendMessage"
params := url.Values{}
params.Set("chat_id", chat)
params.Set("text", message)
c := http.Client{Timeout: 15 * time.Second}
resp, err := c.Get(endpoint + "?" + params.Encode())
if err != nil {
return err
}
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
if err != nil {
return err
}
tgResp := &TelegramResponse{}
err = json.Unmarshal(data, tgResp)
if err != nil {
return err
}
if !tgResp.OK {
return fmt.Errorf("telegram returned an error: %v", tgResp.Description)
}
return nil
}
func TryGeoIP(ip string) string {
// If `geoiplookup` is not available, don't attempt to call it
_, err := exec.LookPath("geoiplookup")
if err != nil {
return ""
}
cmd := exec.Command("geoiplookup", ip)
out, err := cmd.CombinedOutput()
if err != nil {
return ""
}
outStr := string(out)
outStr = strings.Trim(outStr, "\n")
_, country, _ := strings.Cut(outStr, ": ")
if strings.HasPrefix(country, "can't") || strings.HasPrefix(country, "IP") {
return ""
}
return country
}
func main() {
telegramChat := os.Getenv("TELEGRAM_CHAT")
telegramToken := os.Getenv("TELEGRAM_TOKEN")
logTail, err := tail.TailFile("/var/log/auth.log", tail.Config{
ReOpen: true,
Follow: true,
})
if err != nil {
log.Fatalln(err)
}
skipping := true
now := time.Now()
for line := range logTail.Lines {
entryFields := strings.SplitN(line.Text, ": ", 2)
if len(entryFields) != 2 {
continue
}
meta, text := entryFields[0], entryFields[1]
metaFields := strings.Fields(meta)
if len(metaFields) != 5 {
continue
}
date := strings.Join(metaFields[:3], " ")
hostname := metaFields[3]
unit := metaFields[4]
t, err := time.Parse("Jan 2 15:04:05", date)
if err != nil {
log.Println("cannot parse time:", err)
continue
}
// Skip all records that exist before starting the tail
if skipping && (t.Day() != now.Day() ||
t.Month() != now.Month() ||
t.Hour() < now.Hour() ||
(t.Hour() == now.Hour() && t.Minute() < now.Minute()) ||
(t.Hour() == now.Hour() && t.Minute() == now.Minute() && t.Second() <= now.Second())) {
continue
}
skipping = false
switch {
case strings.HasPrefix(unit, "sshd"):
if !strings.HasPrefix(text, "Accepted") {
continue
}
sshFields := strings.Fields(text)
if len(sshFields) < 6 {
continue
}
method, user, ip := sshFields[1], sshFields[3], sshFields[5]
country := TryGeoIP(ip)
if country == "" {
fmt.Printf("new ssh session for user %v (from %v; using %v)\n", user, ip, method)
err = SendMessage(telegramChat, telegramToken,
fmt.Sprintf("new ssh session started by user %v\n\nfrom: %v\nmethod: %v\nhostname: %v",
user, ip, method, hostname))
} else {
fmt.Printf("new ssh session for user %v (from %v; using %v; country %v)\n", user, ip, method, country)
err = SendMessage(telegramChat, telegramToken,
fmt.Sprintf("new ssh session started by user %v\n\nfrom: %v\nmethod: %v\nhostname: %v\ncountry: %v\n",
user, ip, method, hostname, country))
}
if err != nil {
fmt.Printf("could not send message: %v\n", err)
}
case strings.HasPrefix(unit, "sudo"):
text = strings.TrimSpace(text)
splitSudo := strings.SplitN(text, " : ", 2)
if len(splitSudo) != 2 {
continue
}
user, rest := splitSudo[0], splitSudo[1]
// Ignore command continuations. Maybe this can be handled at a later date.
if strings.Contains(rest, "(command continued)") {
continue
}
failed := strings.Contains(rest, "incorrect password")
entries := strings.Split(rest, " ; ")
var asUser, command string
for _, entry := range entries {
switch {
case strings.HasPrefix(entry, "USER="):
asUser = entry[5:]
case strings.HasPrefix(entry, "COMMAND="):
command = entry[8:]
}
}
if !failed {
fmt.Printf("sudo executed by %v (became %v; for command %v)\n", user, asUser, command)
err = SendMessage(telegramChat, telegramToken,
fmt.Sprintf("sudo started by %v\n\ntarget: %v\ncommand: %v\nhostname: %v",
user, asUser, command, hostname))
if err != nil {
fmt.Printf("could not send message: %v\n", err)
}
} else {
fmt.Printf("failed attempt to execute sudo by %v (to become %v; for command %v)\n", user, asUser, command)
err = SendMessage(telegramChat, telegramToken,
fmt.Sprintf("failed attempt to start sudo by %v\n\ntarget: %v\ncommand: %v\nhostname: %v",
user, asUser, command, hostname))
if err != nil {
fmt.Printf("could not send message: %v\n", err)
}
}
}
}
}