forked from 0xrawsec/whids
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsysmon_windows.go
273 lines (217 loc) · 6.16 KB
/
sysmon_windows.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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
//go:build windows
// +build windows
package sysmon
import (
"errors"
"fmt"
"io"
"os"
"path/filepath"
"regexp"
"strings"
"time"
"github.com/0xrawsec/golang-utils/crypto/file"
"github.com/0xrawsec/golang-utils/fsutil"
"github.com/0xrawsec/golang-utils/regexp/submatch"
"github.com/0xrawsec/golang-win32/win32"
"github.com/0xrawsec/golang-win32/win32/advapi32"
"github.com/0xrawsec/whids/utils"
"github.com/0xrawsec/whids/utils/command"
)
const (
servicesPath = `HKLM\SYSTEM\CurrentControlSet\Services`
driverPath = `C:\Windows`
)
var (
versionRe = regexp.MustCompile(
`(?s:System\sMonitor\s(?P<version>v\d+(\.\d+)?)\s-[.\s].*` +
`<manifest schemaversion="(?P<schemaversion>\d+(\.\d+)?)" binaryversion="(?P<binaryversion>\d+(\.\d+)?)">)`,
)
DefaultTimeout = 5 * time.Second
)
func stdCmdOutput(b []byte) []byte {
if len(b) >= 2 {
// check UTF16 BOM
if b[1] == '\xfe' && b[0] == '\xff' {
b = []byte(win32.UTF16BytesToString(b))
}
}
return b
}
func Versions(image string) (version, schema, binary string, err error) {
var out []byte
sh := submatch.NewHelper(versionRe)
if fsutil.IsFile(image) {
c := command.CommandTimeout(
DefaultTimeout,
image,
"-s",
)
defer c.Terminate()
if out, err = c.CombinedOutput(); err != nil {
err = fmt.Errorf("failed to run sysmon schema command: %s", err)
return
}
// standardize output
out = stdCmdOutput(out)
sh.Prepare(out)
if v, err := sh.GetBytes("version"); err == nil {
version = string(v)
}
if sv, err := sh.GetBytes("schemaversion"); err == nil {
schema = string(sv)
}
if bv, err := sh.GetBytes("binaryversion"); err == nil {
binary = string(bv)
}
}
return
}
func InstallOrUpdate(image string) (err error) {
var out []byte
// we first uninstall existing installation
// if Sysmon is not installed yet we should not get any error
if err = Uninstall(); err != nil && !errors.Is(err, ErrSysmonNotInstalled) {
return
}
// we run install
c := command.CommandTimeout(DefaultTimeout, image, "-accepteula", "-i")
defer c.Terminate()
if out, err = c.CombinedOutput(); err != nil {
out = stdCmdOutput(out)
return fmt.Errorf("failed to install sysmon: %w\n%s", err, out)
}
return
}
func Configure(r io.Reader) (err error) {
var tmp, config string
var i *Info
// retrieve sysmon information
if i, err = NewSysmonInfo(); err != nil {
return
}
image := i.Service.Image
if !fsutil.IsFile(image) {
return ErrSysmonNotInstalled
}
if tmp, err = utils.HidsMkTmpDir(); err != nil {
return fmt.Errorf("failed to create tmp dir: %w", err)
}
// remove temporary file
defer os.RemoveAll(tmp)
config = filepath.Join(tmp, "sysmon.xml")
if err = utils.HidsWriteReader(config, r, false); err != nil {
return fmt.Errorf("failed to create config file: %w", err)
}
c := command.CommandTimeout(DefaultTimeout, image, "-c", config)
defer c.Terminate()
if err = c.Run(); err != nil {
return fmt.Errorf("command to configure sysmon failed: %w", err)
}
return
}
func Uninstall() (err error) {
var i *Info
var out []byte
// retrieve sysmon information
if i, err = NewSysmonInfo(); err != nil {
return
}
image := i.Service.Image
//means sysmon is already installed
if fsutil.IsFile(image) {
// we uninstall it
// force flag forces all components to uninstall
c := command.CommandTimeout(DefaultTimeout, image, "-u", "force")
defer c.Terminate()
if out, err = c.CombinedOutput(); err != nil {
out = stdCmdOutput(out)
return fmt.Errorf("failed to uninstall sysmon: %w\n%s", err, string(out))
}
if err = os.Remove(image); err != nil {
return fmt.Errorf("failed to remove sysmon binary: %w", err)
}
}
// we don't return any error if Sysmon is not yet installed
return
}
func findMatchingSysmonServiceKeys() (keys []string) {
keys = make([]string, 0)
if skeys, err := advapi32.RegEnumKeys(servicesPath); err != nil {
return
} else {
for _, skey := range skeys {
fullSubKey := utils.RegJoin(servicesPath, skey)
descValue := utils.RegJoin(fullSubKey, "Description")
if desc := utils.RegValueToString(descValue); desc != "" {
if strings.EqualFold(desc, "System Monitor service") {
keys = append(keys, skey)
}
}
}
}
return
}
func NewSysmonInfo() (i *Info, err error) {
var sysmonRegPath string
i = &Info{}
// validate that we find only one entry in registry
keys := findMatchingSysmonServiceKeys()
// sysmon is not installed
if len(keys) == 0 {
err = ErrSysmonNotInstalled
return
}
// more than one key found -> not normal
if len(keys) > 1 {
err = fmt.Errorf("more than one key looking like Sysmon: %v", keys)
return
}
i.Service.Name = keys[0]
sysmonRegPath = utils.RegJoin(servicesPath, i.Service.Name)
i.Service.Image = utils.RegValueToString(sysmonRegPath, "ImagePath")
i.Service.Sha256, _ = file.Sha256(i.Service.Image)
i.Driver.Name = i.DriverName()
i.Driver.Image = filepath.Join(driverPath, utils.RegValueToString(i.DriverRegistry(), "ImagePath"))
i.Driver.Sha256, _ = file.Sha256(i.Driver.Image)
i.Config.Hash = i.ConfigHash()
// parse schema and populate version information
err = i.parseSchema()
return
}
func (i *Info) ServiceRegistry() string {
return utils.RegJoin(servicesPath, i.Service.Name)
}
func (i *Info) ServiceParametersRegistry() string {
return utils.RegJoin(servicesPath, i.Service.Name, "Parameters")
}
func (i *Info) DriverName() string {
if i.Driver.Name != "" {
return i.Driver.Name
}
return utils.RegValueToString(i.ServiceParametersRegistry(), "DriverName")
}
func (i *Info) DriverRegistry() string {
return utils.RegJoin(servicesPath, i.DriverName())
}
func (i *Info) DriverParametersRegistry() string {
return utils.RegJoin(i.DriverRegistry(), "Parameters")
}
func (i *Info) ConfigHash() string {
if i.Config.Hash != "" {
return i.Config.Hash
}
hash := utils.RegValueToString(i.DriverParametersRegistry(), "ConfigHash")
if i := strings.Index(hash, "="); i > -1 && i+1 < len(hash) {
hash = strings.ToLower(hash[i+1:])
}
return hash
}
func (i *Info) parseSchema() (err error) {
var version, schema, binary string
version, schema, binary, err = Versions(i.Service.Image)
i.Version = version
i.Config.Version.Schema = schema
i.Config.Version.Binary = binary
return
}