-
Notifications
You must be signed in to change notification settings - Fork 256
/
utils.go
287 lines (253 loc) · 7.62 KB
/
utils.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
// Hardentools
// Copyright (C) 2017-2022 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://www.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"
"io/ioutil"
"log"
"os"
"os/exec"
"strings"
"syscall"
"unsafe"
"golang.org/x/sys/windows/registry"
)
// isElevated verifies if program is running with admin privileges
func isElevated() bool {
isElevated := C.IsElevated()
if isElevated == 1 {
return true
}
return false
}
// startWithElevatedPrivs starts progName with elevated privileges
func startWithElevatedPrivs(progName string) bool {
cprogname := C.CString(progName)
defer C.free(unsafe.Pointer(cprogname))
ret := C.ExecuteWithRunas(cprogname)
if ret == 1 {
return true
}
return false
}
// Helper method for executing cmd commands (does not open cmd window).
func executeCommand(cmd string, args ...string) (string, error) {
var out []byte
command := exec.Command(cmd, args...)
command.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
out, err := command.CombinedOutput()
return string(out), err
}
// 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())
ShowFailure("Remove hardentools registry keys", "Could not remove")
}
}
}
// 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 {
Info.Println("Now we are hardening...")
outputString = "Hardening"
} else {
Info.Println("Now we are restoring...")
outputString = "Restoring"
}
Trace.Println(outputString)
for _, hardenSubject := range allHardenSubjects {
if expertConfig[hardenSubject.Name()] == true {
err := hardenSubject.Harden(harden)
if err != nil {
ShowFailure(hardenSubject.Name(), err.Error())
Info.Printf("Error for operation %s: %s", hardenSubject.Name(), err.Error())
} else {
ShowSuccess(hardenSubject.Name())
Trace.Printf("%s %s has been successful", outputString, hardenSubject.Name())
}
}
}
}
func cmdHardenRestore(harden bool) {
// check if hardentools has been started with elevated rights.
elevationStatus := isElevated()
if elevationStatus {
Info.Println("Started with elevated rights")
allHardenSubjects = hardenSubjectsForPrivilegedUsers
} else {
Info.Println("Started without elevated rights")
allHardenSubjects = hardenSubjectsForUnprivilegedUsers
}
// TODO: verify if hardening has been done with elevate privileges and now restoring
// should be done without elevated privileges (needs additional registry key)
// check hardening status
status := checkStatus()
if status == false && harden == false {
fmt.Println("Not hardened. Please harden before restoring.")
os.Exit(-1)
} else if status == true && harden == true {
fmt.Println("Already hardened. Please restore before hardening again.")
os.Exit(-1)
}
// build up expert settings checkboxes and map
expertConfig = make(map[string]bool)
for _, hardenSubject := range allHardenSubjects {
var subjectIsHardened = hardenSubject.IsHardened()
//var enableField bool
if status == false {
// harden only settings which are not hardened yet
expertConfig[hardenSubject.Name()] = !subjectIsHardened && hardenSubject.HardenByDefault()
} else {
// restore only hardened settings
expertConfig[hardenSubject.Name()] = subjectIsHardened
}
}
triggerAll(harden)
if !harden {
restoreSavedRegistryKeys()
}
markStatus(harden)
showStatus()
}
// initLogging initializes loggers.
func initLogging(traceHandle io.Writer, infoHandle io.Writer, guiVersion bool) {
if guiVersion {
Trace = log.New(traceHandle, "TRACE: ", log.Lshortfile)
Info = log.New(infoHandle, "INFO: ", log.Lshortfile)
} else {
Trace = log.New(traceHandle, "", 0)
Info = log.New(infoHandle, "", 0)
}
log.SetOutput(infoHandle)
}
// initLoggingWithCmdParameters initializes logging considering if cli version specifics
func initLoggingWithCmdParameters(logLevelPtr *string, cmd bool) {
var logfile *os.File
var err error
if cmd {
// command line only => use stdout
logfile = os.Stdout
} else {
// UI => use logfile
logfile, err = os.Create(logPath)
if err != nil {
panic(err)
}
}
if strings.EqualFold(*logLevelPtr, "Info") {
// only standard log output
initLogging(ioutil.Discard, logfile, !cmd)
} else if strings.EqualFold(*logLevelPtr, "Trace") {
// standard + trace logging
initLogging(logfile, logfile, !cmd)
} else if strings.EqualFold(*logLevelPtr, "Off") {
// no logging
initLogging(ioutil.Discard, ioutil.Discard, !cmd)
} else {
// default logging (only standard log output)
initLogging(ioutil.Discard, logfile, !cmd)
}
}