-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathentry.go
More file actions
819 lines (681 loc) · 20.3 KB
/
entry.go
File metadata and controls
819 lines (681 loc) · 20.3 KB
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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
package keycred
import (
"bytes"
"crypto/rsa"
"crypto/sha256"
"crypto/x509"
"encoding/base64"
"encoding/binary"
"encoding/hex"
"encoding/json"
"fmt"
"math"
"strconv"
"strings"
"time"
"github.com/google/uuid"
)
const (
TypeKeyID uint8 = 0x01
TypeKeyHash uint8 = 0x02
TypeKeyMaterial uint8 = 0x03
TypeKeyUsage uint8 = 0x04
TypeKeySource uint8 = 0x05
TypeDeviceId uint8 = 0x06
TypeCustomKeyInformation uint8 = 0x07
TypeKeyApproximateLastLogonTimeStamp uint8 = 0x08
TypeKeyCreationTime uint8 = 0x09
)
type KeyCredentialLinkEntry interface {
RawValue() []byte
Type() string
String() string
Bytes() []byte
Entry() *RawEntry
}
type RawEntry struct {
Length uint16
Identifier uint8
Value []byte
}
// Entry returns the raw uninterpreted entry consisting only of length,
// identifier and value.
func (re *RawEntry) Entry() *RawEntry {
return re
}
// Bytes returns the binary representation of the entry.
func (re *RawEntry) Bytes() []byte {
return packBytes(binary.LittleEndian, re.Length, re.Identifier, re.Value)
}
// String returns a human readable representation of the entry.
func (re *RawEntry) String() string {
return fmt.Sprintf("RawEntry(Length=%d, Identifier=%s, Value=%s)",
re.Length, re.Type(), base64.RawStdEncoding.EncodeToString(re.RawValue()))
}
// RawValue makes the binary value of the entry accessible though an
// KeyCredentialLinkEntry interface.
func (re *RawEntry) RawValue() []byte {
return re.Value
}
// Type returns the human readable name of the entry type.
func (re *RawEntry) Type() string {
switch re.Identifier {
case TypeKeyID:
return "KeyID"
case TypeKeyHash:
return "KeyHash"
case TypeKeyMaterial:
return "KeyMaterial"
case TypeKeyUsage:
return "KeyUsage"
case TypeKeySource:
return "KeySource"
case TypeDeviceId:
return "DeviceID"
case TypeCustomKeyInformation:
return "CustomInformation"
case TypeKeyApproximateLastLogonTimeStamp:
return "KeyApproximateLastLogonTimeStamp"
case TypeKeyCreationTime:
return "KeyCreationTime"
default:
return fmt.Sprintf("Unknown Type (0x%x)", re.Identifier)
}
}
// UnknownEntry represents an entry whose identifier is not known and which
// therefore cannot be interpreted.
type UnknownEntry struct {
*RawEntry
}
func (ue *UnknownEntry) String() string {
return fmt.Sprintf("UnknownEntry: Identifier=%d, Length=%d, Value=%s",
ue.Identifier, ue.Length, base64.RawStdEncoding.EncodeToString(ue.RawValue()))
}
type KeyIDEntry struct {
*RawEntry
}
func (keyIDEntry *KeyIDEntry) KeyID() string {
return hex.EncodeToString(keyIDEntry.RawValue())
}
func (keyIDEntry *KeyIDEntry) String() string {
return "KeyID: " + keyIDEntry.KeyID()
}
func (keyIDEntry *KeyIDEntry) Matches(material KeyCredentialLinkEntry) bool {
jwkme, ok := material.(*JSONWebKeyMaterialEntry)
if ok {
return bytes.Equal(keyIDEntry.RawValue(), jwkme.JSON.KeyID)
}
materialID, err := NewKeyIDEntry(material, Version2)
if err != nil {
return false
}
return bytes.Equal(keyIDEntry.RawValue(), materialID.RawValue())
}
func (keyIDEntry *KeyIDEntry) MatchesString(keyID string) bool {
rawKeyID, err := hex.DecodeString(keyID)
if err != nil {
return false
}
return bytes.Equal(keyIDEntry.Value, rawKeyID)
}
func NewKeyIDEntry(keyMaterial KeyCredentialLinkEntry, _ Version) (*KeyIDEntry, error) {
switch km := keyMaterial.(type) {
case *JSONWebKeyMaterialEntry:
return &KeyIDEntry{
RawEntry: &RawEntry{
Length: uint16(len(km.JSON.KeyID)),
Identifier: TypeKeyID,
Value: km.JSON.KeyID,
},
}, nil
case *KeyMaterialEntry, *FIDOKeyMaterialEntry:
// According to
// https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-adts/a99409ea-4982-4f72-b7ef-8596013a36c7
// the key ID should be the SHA256 hash of the Value field of the
// KeyMaterial entry, which should be agnostic of the type of key
// material, but for FIDO keys this does not seem to match. We do it
// according to spec anyway, until we find out how the key ID is
// supposed to differ for FIDO keys.
sha256Hash := sha256.New()
sha256Hash.Write(keyMaterial.RawValue())
rawKeyID := sha256Hash.Sum(nil)
keyIDEntry := &KeyIDEntry{
RawEntry: &RawEntry{
Length: uint16(len(rawKeyID)),
Identifier: TypeKeyID,
Value: rawKeyID,
},
}
return keyIDEntry, nil
default:
return nil, fmt.Errorf("%T is not key material", keyMaterial)
}
}
func AsKeyIDEntry(entry *RawEntry, version Version) (*KeyIDEntry, error) {
if len(entry.RawValue()) == 0 {
return nil, fmt.Errorf("no data")
}
return &KeyIDEntry{RawEntry: entry}, nil
}
type KeyHashEntry struct {
*RawEntry
}
func (kh *KeyHashEntry) String() string {
return "KeyHash: " + hex.EncodeToString(kh.RawValue())
}
func (kh *KeyHashEntry) Validate(followingEntries []KeyCredentialLinkEntry) bool {
return bytes.Equal(kh.RawValue(), NewKeyHashEntry(followingEntries).RawValue())
}
func NewKeyHashEntry(followingEntries []KeyCredentialLinkEntry) *KeyHashEntry {
sha256Hash := sha256.New()
for _, entry := range followingEntries {
sha256Hash.Write(entry.Bytes())
}
hash := sha256Hash.Sum(nil)
return &KeyHashEntry{RawEntry: &RawEntry{
Length: uint16(len(hash)),
Identifier: TypeKeyHash,
Value: hash,
}}
}
func AsKeyHashEntry(entry *RawEntry, _ Version) (*KeyHashEntry, error) {
if len(entry.RawValue()) == 0 {
return nil, fmt.Errorf("no data")
}
return &KeyHashEntry{RawEntry: entry}, nil
}
func AsAppropriateKeyMaterialEntry(entry *RawEntry, version Version) (KeyCredentialLinkEntry, error) {
testContent := struct {
AuthData []byte `json:"authData"`
X5C [][]byte `json:"x5c"`
KeyType string `json:"kty"`
KeyID string `json:"kid"`
}{}
rawValue := entry.RawValue()
switch {
case len(rawValue) == 0:
return nil, fmt.Errorf("data is empty")
case rawValue[0] == '{':
err := json.Unmarshal(rawValue, &testContent)
if err != nil {
return nil, fmt.Errorf("key material seems to be JSON encoded but it cannot be decode: %w", err)
}
switch {
case len(testContent.AuthData) > 0 || len(testContent.X5C) > 0:
return AsFIDOKeyMaterialEntry(entry, version)
case testContent.KeyID != "" || testContent.KeyType != "":
return AsJSONWebKeyMaterialEntry(entry, version)
default:
return nil, fmt.Errorf("JSON key material seems to be neither FIDO nor JSON Web Key")
}
default:
return AsKeyMaterialEntry(entry, version)
}
}
const (
KeyTypeRSAPublic = 0x31415352
KeyTypeRSAPrivate = 0x32415352
KeyTypeRSAFullPrivate = 0x33415352
)
type KeyMaterialEntry struct {
*RawEntry
keyType uint32
keySize uint32
key *rsa.PublicKey
isDERFormatted bool
}
func (km *KeyMaterialEntry) KeyType() string {
res := strconv.Itoa(int(km.keySize)) + " Bit "
switch km.keyType {
case KeyTypeRSAPublic:
res += "RSA Public"
case KeyTypeRSAPrivate:
res += "RSA Private"
case KeyTypeRSAFullPrivate:
res += "RSA Full Private"
default:
res += fmt.Sprintf("Unknown (0x%x)", km.keyType)
}
res += " Key"
if km.isDERFormatted {
res += " (DER Formatted)"
}
return res
}
func (km *KeyMaterialEntry) Key() *rsa.PublicKey {
return km.key
}
func (km *KeyMaterialEntry) String() string {
return "KeyMaterial: " + km.KeyType()
}
func (km *KeyMaterialEntry) DetailedString() string {
return km.String() + fmt.Sprintf(" (E=%d, N=0x%x)", km.key.E, km.key.N)
}
type JSONWebKeyMaterialEntry struct {
*RawEntry
JSON struct {
KeyType string `json:"kty"`
Curve string `json:"crv"`
X string `json:"x"`
Y string `json:"y"`
KeyID []byte `json:"kid"`
}
}
func (jwkme *JSONWebKeyMaterialEntry) String() string {
return fmt.Sprintf("JSONWebKeyMaterial: %s", string(jwkme.RawValue()))
}
func AsJSONWebKeyMaterialEntry(entry *RawEntry, _ Version) (*JSONWebKeyMaterialEntry, error) {
jwkme := &JSONWebKeyMaterialEntry{
RawEntry: entry,
}
err := json.Unmarshal(entry.RawValue(), &jwkme.JSON)
if err != nil {
return nil, fmt.Errorf("JSON parse: %w", err)
}
return jwkme, nil
}
type FIDOKeyMaterialEntry struct {
*RawEntry
JSON struct {
Version int `json:"version"`
AuthData []byte `json:"authData"`
X5C [][]byte `json:"x5c"`
DisplayName string `json:"displayName"`
}
DisplayName string
// Certificates holds the certificates from the x5c JSON field. The first
// certificate is expected to be the attestation certificate and the rest
// are the certificate chain which may not consist of actual x509
// certificates. In this case, the corresponding entry in this slice is nil
// and the raw data can be retrieved from the x5c JSON
// field at the same index.
Certificates []*x509.Certificate
// This field is currently not exported because the decoding is not
// implemented completely. The raw binary authenticator data can be accesses
// through JSON.AuthData.
authenticatorData *fidoAuthData
}
func (fkm *FIDOKeyMaterialEntry) String() string {
certStrs := make([]string, 0, len(fkm.Certificates))
for i, cert := range fkm.Certificates {
if cert == nil && i <= len(fkm.JSON.X5C) {
certStrs = append(certStrs, base64.StdEncoding.EncodeToString(fkm.JSON.X5C[i]))
} else {
certStrs = append(certStrs,
fmt.Sprintf("{Subject:%s, Issuer=%s}", cert.Subject.CommonName, cert.Issuer.CommonName))
}
}
var flags []string
if fkm.authenticatorData.Flags&fidoAuthDataFlagUserPresent > 0 {
flags = append(flags, "UserPresent")
}
if fkm.authenticatorData.Flags&fidoAuthDataFlagUserVerified > 0 {
flags = append(flags, "UserVerified")
}
if fkm.authenticatorData.Flags&fidoAuthDataFlagUserAttestedCredentialDataIncluded > 0 {
flags = append(flags, "AttestedCredentialDataIncluded")
}
if fkm.authenticatorData.Flags&fidoAuthDataFlagUserExtensionDataIncluded > 0 {
flags = append(flags, "ExtensionDataIncluded")
}
return fmt.Sprintf(
"FIDOKeyMaterial: Display Name: %s, RP ID Hash: %x, Flags: %s, Signature Count: %d, %s, Certificates: [%s]",
fkm.DisplayName, fkm.authenticatorData.RPIDHash, strings.Join(flags, "|"),
fkm.authenticatorData.SignCount, humanReadableAADGUI(fkm.authenticatorData.attestedCredentialData.AAGUID),
strings.Join(certStrs, ", "))
}
func AsFIDOKeyMaterialEntry(entry *RawEntry, _ Version) (*FIDOKeyMaterialEntry, error) {
kme := &FIDOKeyMaterialEntry{
RawEntry: entry,
}
err := json.Unmarshal(entry.RawValue(), &kme.JSON)
if err != nil {
return nil, fmt.Errorf("JSON parse: %w", err)
}
kme.DisplayName = kme.JSON.DisplayName
for i, certBytes := range kme.JSON.X5C {
cert, err := x509.ParseCertificate(certBytes)
// The first certificate should be the attestation certificate, and the
// following certificates should be the chain. All of them *should* be
// x509 certs but in practice they sometimes seem to be something else,
// parsing errors in the chain will be ignored.
switch {
case err != nil && i == 0:
return nil, fmt.Errorf("parse X5C certificate at index %d: %w", i, err)
case err == nil:
kme.Certificates = append(kme.Certificates, cert)
default:
kme.Certificates = append(kme.Certificates, nil)
}
}
kme.authenticatorData, err = parseFIDOAuthData(kme.JSON.AuthData)
if err != nil {
return nil, fmt.Errorf("parse authenticator data: %w", err)
}
return kme, nil
}
func NewKeyMaterialEntry(key *rsa.PublicKey, derFormatted bool, _ Version) (*KeyMaterialEntry, error) {
keyMaterial, err := MarshalPublicKeyMaterial(key, derFormatted)
if err != nil {
return nil, fmt.Errorf("marshal key material: %w", err)
}
return &KeyMaterialEntry{
RawEntry: &RawEntry{
Length: uint16(len(keyMaterial)),
Identifier: TypeKeyMaterial,
Value: keyMaterial,
},
keyType: KeyTypeRSAPublic,
keySize: uint32(8 * key.Size()),
key: key,
isDERFormatted: derFormatted,
}, nil
}
func AsKeyMaterialEntry(entry *RawEntry, _ Version) (*KeyMaterialEntry, error) {
key, isDer, err := UnmarshalPublicKeyMaterial(entry.RawValue())
if err != nil {
return nil, err
}
return &KeyMaterialEntry{
RawEntry: entry,
keySize: uint32(8 * key.Size()),
keyType: KeyTypeRSAPublic,
key: key,
isDERFormatted: isDer,
}, nil
}
const (
KeyUsageAdminKey uint8 = 0
KeyUsageNGC uint8 = 1
KeyUsageSTK uint8 = 2
KeyUsageBitlockerRecovery uint8 = 3
KeyUsageOther uint8 = 4
KeyUsageFIDO uint8 = 7
KeyUsageFEK uint8 = 8
)
type KeyUsageEntry struct {
*RawEntry
usage int
}
func (ku *KeyUsageEntry) Usage() int {
return ku.usage
}
func (ku *KeyUsageEntry) Is(usage uint8) bool {
return ku.usage == int(usage)
}
func (ku *KeyUsageEntry) UsageString() string {
if ku.usage < 0 {
return string(ku.RawValue())
}
switch ku.RawValue()[0] {
case KeyUsageAdminKey:
return "AdminKey (Pin-Reset Key)"
case KeyUsageNGC:
return "NGC (Next Generation Credential)"
case KeyUsageSTK:
return "STK (Transport Key Attached to a Device Object)"
case KeyUsageBitlockerRecovery:
return "BitlockerRecovery"
case KeyUsageOther:
return "Other"
case KeyUsageFIDO:
return "FIDO (Fast IDentity Online Key)"
case KeyUsageFEK:
return "FEK (File Encryption Key)"
default:
return fmt.Sprintf("Unknown (0x%x)", ku.RawValue()[0])
}
}
func (ku *KeyUsageEntry) String() string {
return "KeyUsage: " + ku.UsageString()
}
func NewKeyUsageEntry(usage uint8) *KeyUsageEntry {
return &KeyUsageEntry{
RawEntry: &RawEntry{
Length: 1,
Identifier: TypeKeyUsage,
Value: []byte{usage},
},
usage: int(usage),
}
}
func NewLegacyKeyUsageEntry(usage string) *KeyUsageEntry {
return &KeyUsageEntry{
RawEntry: &RawEntry{
Length: uint16(len(usage)),
Identifier: TypeKeyUsage,
Value: []byte(usage),
},
usage: -1,
}
}
func AsKeyUsageEntry(entry *RawEntry, _ Version) (*KeyUsageEntry, error) {
ku := &KeyUsageEntry{RawEntry: entry}
switch len(entry.RawValue()) {
case 0:
return nil, fmt.Errorf("no data")
case 1:
ku.usage = int(entry.RawValue()[0])
default:
ku.usage = -1
}
return ku, nil
}
const (
KeySourceAD uint8 = 0
KeySourceEntraID uint8 = 1
)
type KeySourceEntry struct {
*RawEntry
source uint8
}
func (ks *KeySourceEntry) Value() uint8 {
return ks.source
}
func (ks *KeySourceEntry) Source() uint8 {
return ks.source
}
func (ks *KeySourceEntry) SourceString() string {
switch ks.source {
case KeySourceAD:
return "AD"
case KeySourceEntraID:
return "Entra ID"
default:
return fmt.Sprintf("Unknown (0x%x)", ks.source)
}
}
func (ks *KeySourceEntry) String() string {
return "KeySource: " + ks.SourceString()
}
func NewKeySourceEntry(source uint8) *KeySourceEntry {
return &KeySourceEntry{
RawEntry: &RawEntry{
Length: 1,
Identifier: TypeKeySource,
Value: []byte{source},
},
}
}
func AsKeySourceEntry(entry *RawEntry, _ Version) (*KeySourceEntry, error) {
if len(entry.RawValue()) == 0 {
return nil, fmt.Errorf("no data")
}
return &KeySourceEntry{RawEntry: entry, source: entry.RawValue()[0]}, nil
}
type DeviceIDEntry struct {
*RawEntry
guid uuid.UUID
}
func (di *DeviceIDEntry) GUID() uuid.UUID {
return di.guid
}
func (di *DeviceIDEntry) String() string {
return "DeviceID: " + di.guid.String()
}
func NewDeviceIDEntry(guid uuid.UUID) *DeviceIDEntry {
return &DeviceIDEntry{
RawEntry: &RawEntry{
Length: uint16(len(guid)),
Identifier: TypeDeviceId,
Value: guid[:],
},
guid: guid,
}
}
func AsDeviceIDEntry(entry *RawEntry, _ Version) (*DeviceIDEntry, error) {
if len(entry.RawValue()) != 16 {
return nil, fmt.Errorf("got %d bytes instead of 16", len(entry.RawValue()))
}
di := &DeviceIDEntry{RawEntry: entry}
return di, di.guid.UnmarshalBinary(entry.RawValue())
}
type CustomKeyInformationEntry struct {
*RawEntry
Info *CustomKeyInformation
}
func (cki *CustomKeyInformationEntry) String() string {
return "CustomKeyInformation: " + cki.Info.String()
}
func NewCustomKeyInformationEntry(kci *CustomKeyInformation) *CustomKeyInformationEntry {
if kci == nil {
kci = &CustomKeyInformation{Version: 1}
}
kciBytes := kci.Bytes()
return &CustomKeyInformationEntry{
RawEntry: &RawEntry{
Length: uint16(len(kciBytes)),
Identifier: TypeCustomKeyInformation,
Value: kciBytes,
},
Info: kci,
}
}
func AsCustomKeyInformationEntry(entry *RawEntry, _ Version) (*CustomKeyInformationEntry, error) {
info, err := ParseCustomKeyInformation(entry.RawValue(), false)
if err != nil {
return nil, err
}
cki := &CustomKeyInformationEntry{
RawEntry: entry,
Info: info,
}
return cki, nil
}
type KeyApproximateLastLogonTimeStampEntry struct {
*RawEntry
time time.Time
}
func (lastLogon *KeyApproximateLastLogonTimeStampEntry) Time() time.Time {
return lastLogon.time
}
func (lastLogon *KeyApproximateLastLogonTimeStampEntry) String() string {
if lastLogon.time.IsZero() {
return "KeyCreationTime: <empty>"
}
return "KeyApproximateLastLogonTimeStamp: " + lastLogon.time.Format("2006-01-02 15:04:05 MST")
}
func NewKeyApproximateLastLogonTimeStampEntry(t time.Time) *KeyApproximateLastLogonTimeStampEntry {
timestamp := TimeAsFileTimeBytes(t)
return &KeyApproximateLastLogonTimeStampEntry{
RawEntry: &RawEntry{
Length: uint16(len(timestamp)),
Identifier: TypeKeyApproximateLastLogonTimeStamp,
Value: timestamp,
},
time: t,
}
}
func AsKeyApproximateLastLogonTimeStampEntry(
entry *RawEntry, _ Version,
) (*KeyApproximateLastLogonTimeStampEntry, error) {
if len(entry.RawValue()) != 8 {
return nil, fmt.Errorf("got %d bytes instead of 8", len(entry.RawValue()))
}
lastLogon := &KeyApproximateLastLogonTimeStampEntry{
RawEntry: entry,
time: interpretTime(binary.LittleEndian.Uint64(entry.RawValue())),
}
return lastLogon, nil
}
type KeyCreationTimeEntry struct {
*RawEntry
time time.Time
}
func (creationTime *KeyCreationTimeEntry) Time() time.Time {
return creationTime.time
}
func (creationTime *KeyCreationTimeEntry) String() string {
if creationTime.time.IsZero() {
return "KeyCreationTime: <empty>"
}
return "KeyCreationTime: " + creationTime.time.Format("2006-01-02 15:04:05 MST")
}
func NewKeyCreationTimeEntry(t time.Time) *KeyCreationTimeEntry {
timestamp := TimeAsFileTimeBytes(t)
return &KeyCreationTimeEntry{
RawEntry: &RawEntry{
Length: uint16(len(timestamp)),
Identifier: TypeKeyCreationTime,
Value: timestamp,
},
time: t,
}
}
func AsKeyCreationTimeEntry(entry *RawEntry, _ Version) (*KeyCreationTimeEntry, error) {
if len(entry.RawValue()) != 8 {
return nil, fmt.Errorf("got %d bytes instead of 8", len(entry.RawValue()))
}
lastLogon := &KeyCreationTimeEntry{
RawEntry: entry,
time: interpretTime(binary.LittleEndian.Uint64(entry.RawValue())),
}
return lastLogon, nil
}
// UnparsableEntry represents an entry with a known identifier that could not be
// parsed according to the rules for that identifier.
type UnparsableEntry struct {
*RawEntry
parseErr error
}
func (ue *UnparsableEntry) String() string {
return fmt.Sprintf("UnparsableEntry: Identifier=%s, Length=%d, Value=%s, Error=%v",
ue.Type(), ue.Length, base64.RawStdEncoding.EncodeToString(ue.RawValue()), ue.parseErr)
}
func NewUnparsableEntry(entry *RawEntry, err error) *UnparsableEntry {
return &UnparsableEntry{
RawEntry: entry,
parseErr: err,
}
}
func interpretTime(value uint64) time.Time {
if value == 0 {
return time.Time{}
}
fileTime := TimeFromFileTime(value)
// if the year looks plausible as FileTime, interpret it as FileTime
if fileTime.Year() > 1900 {
return fileTime
}
// Interpret the time as C# DateTime instead:
// https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-nrbf/f05212bd-57f4-4c4b-9d98-b84c7c658054
ticks := int64(value) & 0x3FFFFFFFFFFFFFFF // split of timezone flag
seconds := int64(float64(ticks) / math.Pow(10, 7)) // convert from 100ns ticks to seconds
// work around the fact that the maximum time.Duration is way too short for
// this calulation, so we add the maximum duration as often as we need
var (
d = time.Date(1, 1, 1, 0, 0, 0, 0, time.UTC)
maxDuration time.Duration = 1<<63 - 1
maxSeconds = int64(math.Floor(float64(maxDuration) / float64(time.Second)))
)
for seconds > 0 {
if seconds > maxSeconds {
d = d.Add(time.Duration(maxSeconds) * time.Second)
seconds -= maxSeconds
} else {
d = d.Add(time.Duration(seconds) * time.Second)
seconds = 0
}
}
return d
}