forked from hardentools/hardentools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
342 lines (299 loc) · 8.73 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
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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
// Hardentools
// Copyright (C) 2018 Security Without Borders
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://wweventsDialog.gnu.org/licenses/>.
package main
/*
// some C code for managing elevated privileges
#include <windows.h>
#include <shellapi.h>
// checks if we are running with elevated privileges (admin rights)
int IsElevated( ) {
boolean fRet = FALSE;
HANDLE hToken = NULL;
if( OpenProcessToken( GetCurrentProcess( ),TOKEN_QUERY,&hToken ) ) {
TOKEN_ELEVATION Elevation;
DWORD cbSize = sizeof( TOKEN_ELEVATION );
if( GetTokenInformation( hToken, TokenElevation, &Elevation, sizeof( Elevation ), &cbSize ) ) {
fRet = Elevation.TokenIsElevated;
}
}
if( hToken ) {
CloseHandle( hToken );
}
if( fRet ){
return 1;
}
else {
return 0;
}
}
// executes the executable in the current directory (or in path) with "runas"
// to aquire admin privileges
int ExecuteWithRunas(char execName[]){
SHELLEXECUTEINFO shExecInfo;
shExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
shExecInfo.fMask = 0x00008000;
shExecInfo.hwnd = NULL;
shExecInfo.lpVerb = "runas";
shExecInfo.lpFile = execName;
shExecInfo.lpParameters = NULL;
shExecInfo.lpDirectory = NULL;
shExecInfo.nShow = SW_NORMAL;
shExecInfo.hInstApp = NULL;
boolean success = ShellExecuteEx(&shExecInfo);
if (success)
return 1;
else
return 0;
}
*/
import "C"
import (
"fmt"
"io"
"log"
"os"
"golang.org/x/sys/windows/registry"
)
// global configuration constants
const hardentoolsKeyPath = "SOFTWARE\\Security Without Borders\\"
const logpath = "hardentools.log"
const defaultLogLevel = "Info"
// allHardenSubjects contains all top level harden subjects that should
// be considered
// Elevated rights are needed by: UAC, PowerShell, FileAssociations, Autorun, WindowsASR
var allHardenSubjects = []HardenInterface{}
var allHardenSubjectsWithAndWithoutElevatedPrivileges = []HardenInterface{
// WSH.
WSH,
// Office.
OfficeOLE,
OfficeMacros,
OfficeActiveX,
OfficeDDE,
// PDF.
AdobePDFJS,
AdobePDFObjects,
AdobePDFProtectedMode,
AdobePDFProtectedView,
AdobePDFEnhancedSecurity,
// Autorun.
Autorun,
// PowerShell.
PowerShell,
// UAC.
UAC,
// Explorer.
FileAssociations,
ShowFileExt,
// Windows 10 / 1709 ASR
WindowsASR,
}
var allHardenSubjectsForUnprivilegedUsers = []HardenInterface{
// WSH.
WSH,
// Office.
OfficeOLE,
OfficeMacros,
OfficeActiveX,
OfficeDDE,
// PDF.
AdobePDFJS,
AdobePDFObjects,
AdobePDFProtectedMode,
AdobePDFProtectedView,
AdobePDFEnhancedSecurity,
}
var expertConfig map[string]bool
// Loggers for log output (we only need info and trace, errors have to be
// displayed in the GUI)
var (
Trace *log.Logger
Info *log.Logger
)
// initLogging inits loggers
func initLogging(traceHandle io.Writer, infoHandle io.Writer) {
Trace = log.New(traceHandle,
"TRACE: ",
log.Ldate|log.Ltime|log.Lshortfile)
Info = log.New(infoHandle,
"INFO: ",
log.Ldate|log.Ltime|log.Lshortfile)
}
// checkStatus checks status of hardentools registry key
// (that tells if user environment is hardened / not hardened)
func checkStatus() bool {
key, err := registry.OpenKey(registry.CURRENT_USER, hardentoolsKeyPath, registry.READ)
if err != nil {
return false
}
defer key.Close()
value, _, err := key.GetIntegerValue("Harden")
if err != nil {
return false
}
if value == 1 {
return true
}
return false
}
// markStatus sets hardentools status registry key
// (that tells if user environment is hardened / not hardened)
func markStatus(hardened bool) {
if hardened {
key, _, err := registry.CreateKey(registry.CURRENT_USER, hardentoolsKeyPath, registry.ALL_ACCESS)
if err != nil {
Info.Println(err.Error())
panic(err)
}
defer key.Close()
// set value that states that we have hardened the system
err = key.SetDWordValue("Harden", 1)
if err != nil {
Info.Println(err.Error())
showErrorDialog("Could not set hardentools registry keys - restore will not work!")
panic(err)
}
} else {
// on restore delete all hardentools registry keys afterwards
err := registry.DeleteKey(registry.CURRENT_USER, hardentoolsKeyPath)
if err != nil {
Info.Println(err.Error())
events.AppendText("Could not remove hardentools registry keys - nothing to worry about.")
}
}
}
// hardenAll starts harden procedure
func hardenAll() {
showEventsTextArea()
// use goroutine to allow lxn/walk to update window
go func() {
triggerAll(true)
markStatus(true)
showStatus()
showInfoDialog("Done!\nI have hardened all risky features!\nFor all changes to take effect please restart Windows.")
os.Exit(0)
}()
}
// restoreAll starts restore procedure
func restoreAll() {
showEventsTextArea()
// use goroutine to allow lxn/walk to update window
go func() {
triggerAll(false)
restoreSavedRegistryKeys()
markStatus(false)
showStatus()
showInfoDialog("Done!\nI have restored all risky features!\nFor all changes to take effect please restart Windows.")
os.Exit(0)
}()
}
// triggerAll is used for harden and restore, depending on the harden parameter
// harden == true => harden
// harden == false => restore
// triggerAll evaluates the expertConfig settings and hardens/restores only
// the active items
func triggerAll(harden bool) {
var outputString string
if harden {
events.AppendText("Now we are hardening ")
outputString = "Hardening"
} else {
events.AppendText("Now we are restoring ")
outputString = "Restoring"
}
for _, hardenSubject := range allHardenSubjects {
if expertConfig[hardenSubject.Name()] == true {
events.AppendText(fmt.Sprintf("%s, ", hardenSubject.Name()))
err := hardenSubject.Harden(harden)
if err != nil {
events.AppendText(fmt.Sprintf("\n!! %s %s FAILED !!\n", outputString, hardenSubject.Name()))
Info.Printf("Error for operation %s: %s", hardenSubject.Name(), err.Error())
} else {
Trace.Printf("%s %s has been successful", outputString, hardenSubject.Name())
}
}
}
events.AppendText("\n")
}
// hardenDefaultsAgain restores the original settings and
// hardens using the default settings (no custom settings apply)
func hardenDefaultsAgain() {
showEventsTextArea()
// use goroutine to allow lxn/walk to update window
go func() {
// restore hardened settings
triggerAll(false)
restoreSavedRegistryKeys()
markStatus(false)
// reset expertConfig (is set to currently already hardened settings
// in case of restore
expertConfig = make(map[string]bool)
for _, hardenSubject := range allHardenSubjects {
// TODO: sets all harden subjects to active for now. Better: replace
// this with default settings (to be implemented)
expertConfig[hardenSubject.Name()] = true
}
// harden all settings
triggerAll(true)
markStatus(true)
showInfoDialog("Done!\nI have hardened all risky features!\nFor all changes to take effect please restart Windows.")
os.Exit(0)
}()
}
// showStatus iterates all harden subjects and prints status of each
// (checks real status on system)
func showStatus() {
for _, hardenSubject := range allHardenSubjects {
if hardenSubject.IsHardened() {
eventText := fmt.Sprintf("%s is now hardened\n", hardenSubject.Name())
events.AppendText(eventText)
Info.Print(eventText)
} else {
eventText := fmt.Sprintf("%s is now NOT hardened\n", hardenSubject.Name())
events.AppendText(eventText)
Info.Print(eventText)
}
}
}
// restartWithElevatedPrivileges tries to restart hardentools.exe with admin privileges
func restartWithElevatedPrivileges() {
// find out our program (exe) name
progName := os.Args[0]
// start us again, this time with elevated privileges
if C.ExecuteWithRunas(C.CString(progName)) == 1 {
// exit this instance (the unprivileged one)
os.Exit(0)
} else {
// something went wrong
showErrorDialog("Error while trying to gain elevated privileges. Starting in unprivileged mode...")
}
}
// main method for hardentools
func main() {
// check if hardentools has been started with elevated rights. If not
// ask user if he wants to elevate
if C.IsElevated() == 0 {
askElevationDialog()
}
elevationStatus := false
if C.IsElevated() == 1 {
elevationStatus = true
}
// show splash screen
splashChannel := make(chan bool, 1)
showSplash(splashChannel)
openMainWindow(splashChannel, elevationStatus)
}