forked from iamacarpet/go-win64api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bitlocker.go
executable file
·360 lines (311 loc) · 11.6 KB
/
bitlocker.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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
//go:build windows && amd64
// +build windows,amd64
package winapi
import (
"fmt"
"github.com/go-ole/go-ole"
"github.com/go-ole/go-ole/oleutil"
so "github.com/racktopsystems/winapi/shared"
"github.com/scjalliance/comshim"
)
// BackupBitLockerRecoveryKeys backups up volume recovery information to Active Directory.
// Requires one or more PersistentVolumeIDs, available from GetBitLockerRecoveryInfo.
//
// Ref: https://docs.microsoft.com/en-us/windows/win32/secprov/backuprecoveryinformationtoactivedirectory-win32-encryptablevolume
func BackupBitLockerRecoveryKeys(persistentVolumeIDs []string) error {
comshim.Add(1)
defer comshim.Done()
w := &wmi{}
if err := w.Connect(); err != nil {
return fmt.Errorf("wmi.Connect: %w", err)
}
defer w.Close()
for _, pvid := range persistentVolumeIDs {
raw, err := oleutil.CallMethod(w.svc, "ExecQuery",
fmt.Sprintf(`SELECT * FROM Win32_EncryptableVolume WHERE PersistentVolumeID="%s"`, pvid),
)
if err != nil {
return fmt.Errorf("ExecQuery: %w", err)
}
result := raw.ToIDispatch()
defer result.Release()
itemRaw, err := oleutil.CallMethod(result, "ItemIndex", 0)
if err != nil {
return fmt.Errorf("failed to fetch result row while processing BitLocker info: %w", err)
}
item := itemRaw.ToIDispatch()
defer item.Release()
keys, err := getKeyProtectors(item)
if err != nil {
return fmt.Errorf("getKeyProtectors: %w", err)
}
for _, k := range keys {
statusResultRaw, err := oleutil.CallMethod(item, "BackupRecoveryInformationToActiveDirectory", k)
if err != nil {
return fmt.Errorf("unable to backup bitlocker information to active directory: %w", err)
} else if val, ok := statusResultRaw.Value().(int32); val != 0 || !ok {
return fmt.Errorf("invalid result while backing up bitlocker information to active directory: %v", val)
}
}
}
return nil
}
// GetBitLockerConversionStatus returns the Bitlocker conversion status for all local drives.
func GetBitLockerConversionStatus() ([]*so.BitLockerConversionStatus, error) {
comshim.Add(1)
defer comshim.Done()
return getBitLockerConversionStatusInternal("")
}
// GetBitLockerConversionStatusForDrive returns the Bitlocker conversion status for a specific drive.
func GetBitLockerConversionStatusForDrive(driveLetter string) (*so.BitLockerConversionStatus, error) {
comshim.Add(1)
defer comshim.Done()
result, err := getBitLockerConversionStatusInternal(" WHERE DriveLetter = '" + driveLetter + "'")
if err != nil {
return nil, err
}
if len(result) < 1 {
return nil, fmt.Errorf("error getting BitLocker conversion status, drive not found: %s", driveLetter)
} else if len(result) > 1 {
return nil, fmt.Errorf("error getting BitLocker conversion status, too many results: %s", driveLetter)
} else {
return result[0], err
}
}
// GetBitLockerRecoveryInfo returns the Bitlocker device info for all local drives.
func GetBitLockerRecoveryInfo() ([]*so.BitLockerDeviceInfo, error) {
comshim.Add(1)
defer comshim.Done()
return getBitLockerRecoveryInfoInternal("")
}
// GetBitLockerRecoveryInfoForDrive returns the Bitlocker device info for a specific drive.
func GetBitLockerRecoveryInfoForDrive(driveLetter string) (*so.BitLockerDeviceInfo, error) {
comshim.Add(1)
defer comshim.Done()
result, err := getBitLockerRecoveryInfoInternal(" WHERE DriveLetter = '" + driveLetter + "'")
if err != nil {
return nil, err
}
if len(result) < 1 {
return nil, fmt.Errorf("error getting BitLocker Recovery Info, drive not found: %s", driveLetter)
} else if len(result) > 1 {
return nil, fmt.Errorf("error getting BitLocker Recovery Info, too many results: %s", driveLetter)
} else {
return result[0], err
}
}
type wmi struct {
intf *ole.IDispatch
svc *ole.IDispatch
}
func (w *wmi) Connect() error {
unknown, err := oleutil.CreateObject("WbemScripting.SWbemLocator")
if err != nil {
return fmt.Errorf("unable to create initial object, %w", err)
}
defer unknown.Release()
w.intf, err = unknown.QueryInterface(ole.IID_IDispatch)
if err != nil {
return fmt.Errorf("unable to create initial object, %w", err)
}
serviceRaw, err := oleutil.CallMethod(w.intf, "ConnectServer", nil, `\\.\ROOT\CIMV2\Security\MicrosoftVolumeEncryption`)
if err != nil {
return fmt.Errorf("permission denied: %w", err)
}
w.svc = serviceRaw.ToIDispatch()
return nil
}
func (w *wmi) Close() {
w.svc.Release()
w.intf.Release()
}
func getBitLockerConversionStatusInternal(where string) ([]*so.BitLockerConversionStatus, error) {
w := &wmi{}
if err := w.Connect(); err != nil {
return nil, fmt.Errorf("wmi.Connect: %w", err)
}
defer w.Close()
raw, err := oleutil.CallMethod(w.svc, "ExecQuery", "SELECT * FROM Win32_EncryptableVolume"+where)
if err != nil {
return nil, fmt.Errorf("ExecQuery: %w", err)
}
result := raw.ToIDispatch()
defer result.Release()
ret := []*so.BitLockerConversionStatus{}
countVar, err := oleutil.GetProperty(result, "Count")
if err != nil {
return nil, fmt.Errorf("unable to get property Count while processing BitLocker info: %w", err)
}
count := int(countVar.Val)
for i := 0; i < count; i++ {
retData, err := bitlockerConversionStatus(result, i)
if err != nil {
return nil, err
}
ret = append(ret, retData)
}
return ret, nil
}
func getBitLockerRecoveryInfoInternal(where string) ([]*so.BitLockerDeviceInfo, error) {
w := &wmi{}
if err := w.Connect(); err != nil {
return nil, fmt.Errorf("wmi.Connect: %w", err)
}
defer w.Close()
raw, err := oleutil.CallMethod(w.svc, "ExecQuery", "SELECT * FROM Win32_EncryptableVolume"+where)
if err != nil {
return nil, fmt.Errorf("ExecQuery: %w", err)
}
result := raw.ToIDispatch()
defer result.Release()
retBitLocker := []*so.BitLockerDeviceInfo{}
countVar, err := oleutil.GetProperty(result, "Count")
if err != nil {
return nil, fmt.Errorf("unable to get property Count while processing BitLocker info: %w", err)
}
count := int(countVar.Val)
for i := 0; i < count; i++ {
retData, err := bitlockerRecoveryInfo(result, i)
if err != nil {
return nil, err
}
retBitLocker = append(retBitLocker, retData)
}
return retBitLocker, nil
}
func getKeyProtectors(item *ole.IDispatch) ([]string, error) {
kp := []string{}
var keyProtectorResults ole.VARIANT
ole.VariantInit(&keyProtectorResults)
keyIDResultRaw, err := oleutil.CallMethod(item, "GetKeyProtectors", 3, &keyProtectorResults)
if err != nil {
return nil, fmt.Errorf("Unable to get Key Protectors while getting BitLocker info. %s", err.Error())
} else if val, ok := keyIDResultRaw.Value().(int32); val != 0 || !ok {
return nil, fmt.Errorf("Unable to get Key Protectors while getting BitLocker info. Return code %d", val)
}
keyProtectorValues := keyProtectorResults.ToArray().ToValueArray()
for _, keyIDItemRaw := range keyProtectorValues {
keyIDItem, ok := keyIDItemRaw.(string)
if !ok {
return nil, fmt.Errorf("KeyProtectorID wasn't a string...")
}
kp = append(kp, keyIDItem)
}
return kp, nil
}
func bitlockerConversionStatus(result *ole.IDispatch, i int) (*so.BitLockerConversionStatus, error) {
itemRaw, err := oleutil.CallMethod(result, "ItemIndex", i)
if err != nil {
return nil, fmt.Errorf("failed to fetch result row while processing BitLocker info: %w", err)
}
item := itemRaw.ToIDispatch()
defer item.Release()
retData := &so.BitLockerConversionStatus{}
// https://docs.microsoft.com/en-us/windows/win32/secprov/getconversionstatus-win32-encryptablevolume
var conversionStatus ole.VARIANT
ole.VariantInit(&conversionStatus)
var encryptionPercentage ole.VARIANT
ole.VariantInit(&encryptionPercentage)
var encryptionFlags ole.VARIANT
ole.VariantInit(&encryptionFlags)
var wipingStatus ole.VARIANT
ole.VariantInit(&wipingStatus)
var wipingPercentage ole.VARIANT
ole.VariantInit(&wipingPercentage)
statusResultRaw, err := oleutil.CallMethod(
item, "GetConversionStatus",
&conversionStatus,
&encryptionPercentage,
&encryptionFlags,
&wipingStatus,
&wipingPercentage,
0,
)
if err != nil {
return nil, fmt.Errorf("unable to get conversion status while getting BitLocker info: %w", err)
} else if val, ok := statusResultRaw.Value().(uint32); val != 0 || !ok {
// The possible return values of GetConversionStatus are S_OK (0x0) and FVE_E_LOCKED_VOLUME (0x80310000)
// If the return value is not 0, the volume is locked.
return nil, fmt.Errorf("unable to get conversion status while getting BitLocker info; the volume is locked. Return code %d", val)
}
retData.ConversionStatus = conversionStatus.Value().(uint32)
retData.EncryptionPercentage = encryptionPercentage.Value().(uint32)
retData.EncryptionFlags = encryptionFlags.Value().(uint32)
retData.WipingStatus = wipingStatus.Value().(uint32)
retData.WipingPercentage = wipingPercentage.Value().(uint32)
return retData, nil
}
func bitlockerRecoveryInfo(result *ole.IDispatch, i int) (*so.BitLockerDeviceInfo, error) {
itemRaw, err := oleutil.CallMethod(result, "ItemIndex", i)
if err != nil {
return nil, fmt.Errorf("failed to fetch result row while processing BitLocker info. %w", err)
}
item := itemRaw.ToIDispatch()
defer item.Release()
retData := &so.BitLockerDeviceInfo{
RecoveryKeys: []string{},
}
resDeviceID, err := oleutil.GetProperty(item, "DeviceID")
if err != nil {
return nil, fmt.Errorf("Error while getting property DeviceID from BitLocker info. %s", err.Error())
}
retData.DeviceID = resDeviceID.ToString()
resPersistentVolumeID, err := oleutil.GetProperty(item, "PersistentVolumeID")
if err != nil {
return nil, fmt.Errorf("Error while getting property PersistentVolumeID from BitLocker info. %s", err.Error())
}
retData.PersistentVolumeID = resPersistentVolumeID.ToString()
resDriveLetter, err := oleutil.GetProperty(item, "DriveLetter")
if err != nil {
return nil, fmt.Errorf("Error while getting property DriveLetter from BitLocker info. %s", err.Error())
}
retData.DriveLetter = resDriveLetter.ToString()
resProtectionStatus, err := oleutil.GetProperty(item, "ProtectionStatus")
if err != nil {
return nil, fmt.Errorf("Error while getting property ProtectionStatus from BitLocker info. %s", err.Error())
}
var ok bool
retData.ProtectionStatus, ok = resProtectionStatus.Value().(uint32)
if !ok {
protectionStatus, ok := resProtectionStatus.Value().(int32)
if !ok {
return nil, fmt.Errorf("Failed to parse ProtectionStatus from BitLocker info as uint32 or int32")
}
retData.ProtectionStatus = uint32(protectionStatus)
}
resConversionStatus, err := oleutil.GetProperty(item, "ConversionStatus")
if err != nil {
return nil, fmt.Errorf("error while getting property ConversionStatus from BitLocker info: %w", err)
}
ok = false
retData.ConversionStatus, ok = resConversionStatus.Value().(uint32)
if !ok {
conversionStatus, ok := resConversionStatus.Value().(int32)
if !ok {
return nil, fmt.Errorf("Failed to parse ConversionStatus from BitLocker info as uint32 or int32")
}
retData.ConversionStatus = uint32(conversionStatus)
}
keys, err := getKeyProtectors(item)
if err != nil {
return nil, fmt.Errorf("getKeyProtectors: %w", err)
}
for _, k := range keys {
err = func() error {
var recoveryKey ole.VARIANT
ole.VariantInit(&recoveryKey)
recoveryKeyResultRaw, err := oleutil.CallMethod(item, "GetKeyProtectorNumericalPassword", k, &recoveryKey)
if err != nil {
return fmt.Errorf("Unable to get Recovery Key while getting BitLocker info. %s", err.Error())
} else if val, ok := recoveryKeyResultRaw.Value().(int32); val != 0 || !ok {
return fmt.Errorf("Unable to get Recovery Key while getting BitLocker info. Return code %d", val)
}
retData.RecoveryKeys = append(retData.RecoveryKeys, recoveryKey.ToString())
return nil
}()
if err != nil {
return nil, err
}
}
return retData, nil
}