Repository navigation
Expand file tree
/
Copy pathkrb5_describe.js
More file actions
2157 lines (2092 loc) · 90 KB
/
Copy pathkrb5_describe.js
File metadata and controls
2157 lines (2092 loc) · 90 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
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// File: krb5_describe.js
//
// ---------------------------------------------------------------------------
// "Here are these bytes, explained" — the decoder page's whole content, with no
// DOM in it.
//
// The split follows webauthn.js / webauthn_panes.js: every fact about Kerberos
// lives here and is checkable by a node test with no browser, and the page is a
// renderer that knows nothing about the protocol. A pane that disagreed with the
// protocol would then be a rendering bug rather than a protocol bug, which is a
// much cheaper thing to find.
//
// Output is a plain document:
//
// { kind, summary, sections: [ { title, note, rows: [ {name, value, note} ],
// sections: [...] } ], problems: [...] }
//
// Three design points worth stating, because each is a decision the obvious
// implementation gets wrong:
//
// * **Every value is a STRING here, already formatted.** The renderer never
// formats and never interprets. That is what stops a hex dump becoming a
// number somewhere, and it is why the page can put everything through
// textContent — this page renders bytes a stranger pasted in, and every value
// in it is hostile by default.
// * **A failure to decrypt is CONTENT, not an error.** Most of the interesting
// parts of a Kerberos message are encrypted under keys the person reading it
// does not have. "Encrypted under the service's key, which you have not
// supplied" is the most useful sentence on the screen, so it is a row rather
// than an exception.
// * **`problems` is for things that are WRONG, not things that are absent.**
// A missing optional field is normal. A pvno of 4, an etype the KDC should not
// still be offering, a KerberosTime far from now — those are findings, and
// they are what somebody opened this page to be told.
// ---------------------------------------------------------------------------
var prim = require("./krb5_primitives.js");
var asn1 = require("./krb5_asn1.js");
var msgs = require("./krb5_messages.js");
var kcrypto = require("./krb5_crypto.js");
var kpac = require("./krb5_pac.js");
var gss = require("./krb5_gss.js");
var spnego = require("./krb5_spnego.js");
var bunyan = require("bunyan");
var log = bunyan.createLogger({
name: "krb5_describe",
level: (function () {
try {
return require(process.env.CONFIG_FILE).logLevel || "info";
} catch (e) {
// No CONFIG_FILE resolvable here — a node caller rather than a bundle.
return "info";
}
})()
});
// ---------------------------------------------------------------------------
// Getting the bytes out of whatever was pasted.
//
// A capture arrives in more shapes than people expect, and guessing wrong gives
// a parse error that names ASN.1 rather than the paste. Each accepted form is
// reported, so the page can say what it decided.
// ---------------------------------------------------------------------------
function parseInput(text) {
log.debug("Entering parseInput().");
var raw = String(text === null || text === undefined ? "" : text).trim();
if (!raw) {
throw new Error("Nothing to decode — paste a Kerberos message first.");
}
// Wireshark's "Copy as a hex stream", a C array, or a colon-separated dump:
// strip the punctuation that is obviously not data.
var cleaned = raw.replace(/0x/gi, "").replace(/[\s,:;]+/g, "");
var how;
var bytes;
if (/^[0-9a-f]+$/i.test(cleaned) && cleaned.length % 2 === 0 &&
cleaned.length >= 4) {
bytes = prim.fromHex(cleaned);
how = "hex";
} else {
// base64 or base64url. Padding is optional in the wild.
var b64 = raw.replace(/\s+/g, "").replace(/-/g, "+").replace(/_/g, "/");
var pad = b64.length % 4;
if (pad === 1) {
throw new Error("This is not valid base64 (its length cannot be right) " +
"and not hex either.");
}
if (pad) b64 += "====".slice(pad);
var decoded;
try {
decoded = base64ToBytes(b64);
} catch (e) {
throw new Error("Could not read this as hex or as base64: " + e.message);
}
bytes = decoded;
how = /[-_]/.test(raw) ? "base64url" : "base64";
}
// The TCP framing. Kerberos over TCP puts a four-byte big-endian length in
// front of every message, and a capture very often includes it. Left in place
// the ASN.1 parse fails on the first byte, which names the wrong thing
// entirely — so it is detected and stripped, and SAID.
var framing = null;
if (bytes.length > 4 && (bytes[0] & 0x80) === 0) {
var declared = ((bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3]) >>> 0;
if (declared === bytes.length - 4 &&
asn1.peekApplicationNumber(bytes.subarray(4)) !== null) {
framing = "TCP length prefix (" + declared + " bytes) stripped";
bytes = bytes.subarray(4);
}
}
log.debug("Leaving parseInput(). " + how + ", " + bytes.length + " bytes");
return { bytes: bytes, encoding: how, framing: framing };
}
function base64ToBytes(b64) {
if (typeof atob === "function") {
var s = atob(b64);
var out = new Uint8Array(s.length);
for (var i = 0; i < s.length; i++) out[i] = s.charCodeAt(i);
return out;
}
// node
return new Uint8Array(Buffer.from(b64, "base64"));
}
// ---------------------------------------------------------------------------
// Formatting helpers. Everything the renderer receives is already a string.
// ---------------------------------------------------------------------------
function hexOf(bytes, limit) {
var h = prim.toHex(bytes);
var cap = limit || 96;
return h.length > cap * 2 ? h.slice(0, cap * 2) + "… (" +
prim.toBytes(bytes).length + " bytes)" : h;
}
function timeOf(date) {
if (!date) {
return "(absent)";
}
return asn1.formatKerberosTime(date) + " (" + date.toISOString() + ")";
}
function principalOf(p, realm) {
log.debug("Entering principalOf().");
if (!p) {
log.debug("Leaving principalOf().");
return "(absent)";
}
var nameTypeName = null;
Object.keys(msgs.NAME_TYPE).forEach(function (k) {
if (msgs.NAME_TYPE[k] === p.type) nameTypeName = k;
});
log.debug("Leaving principalOf().");
return msgs.principalToString(p, realm) +
" [name-type " + p.type + (nameTypeName ? " NT-" +
nameTypeName.replace(/_/g, "-") : "") + "]";
}
function row(name, value, note) {
return {
name: name,
value: value === undefined || value === null ? "(absent)" : String(value),
note: note || null
};
}
function etypeListOf(ids) {
return (ids || []).map(function (id) {
return id + " " + kcrypto.etypeName(id) + (kcrypto.isSupportedEtype(id) ?
"" : " (not performed here)");
}).join("\n");
}
// ---------------------------------------------------------------------------
// Decryption, when the reader has a key.
//
// The caller supplies candidate keys; each encrypted part is tried with the keys
// whose etype matches, at the key usage that part is defined to use. Trying every
// usage would be worse than useless: it would sometimes succeed with the wrong
// one and present a confident wrong answer.
// ---------------------------------------------------------------------------
async function tryDecrypt(encPart, usage, keys, what) {
log.debug("Entering tryDecrypt().");
var candidates = (keys ||
[]).filter(function (k) { return k.etype === encPart.etype; });
if (!candidates.length) {
var haveOther = (keys || []).length > 0;
log.debug("Leaving tryDecrypt().");
return {
ok: false,
tried: 0,
note: haveOther
? "Encrypted with " + encPart.etypeName + " (etype " + encPart.etype +
"), and none of the keys " +
"supplied is of that type. " + what
: "Encrypted with " + encPart.etypeName + ". " + what
};
}
var e;
try {
e = kcrypto.etypeById(encPart.etype);
} catch (err) {
log.debug("Leaving tryDecrypt().");
return {
ok: false,
tried: 0,
note: "This build cannot decrypt " + encPart.etypeName + ": " +
err.message
};
}
for (var i = 0; i < candidates.length; i++) {
try {
var plain = await e.decrypt(candidates[i].key, usage, encPart.cipher);
log.debug("Leaving tryDecrypt().");
return {
ok: true,
tried: candidates.length,
plain: plain,
usedKey: candidates[i],
usage: usage
};
} catch (err) {
// Wrong key of the right type: keep trying the others. Reported below if
// none works, because "the key you gave is not this key" is a real
// answer.
log.debug("key " + (candidates[i].label || i) + " did not decrypt: " +
err.message);
}
}
// The guidance goes in HERE as well as in the branch above, and that is the
// whole point of this note rather than a tidy-up. Every page that renders a
// message hands the describer whatever keys it happens to hold — a client key
// on the AS page, a session key on the TGS and AP pages — so a ticket's
// enc-part almost always has a key of the RIGHT ETYPE to try and fail with,
// and this is the branch a reader actually sees. Without `what` it said only
// that some unnamed key did not work, which reads as a broken key rather than
// as the wrong one, and left nothing on screen saying which key would work.
log.debug("Leaving tryDecrypt().");
return {
ok: false,
tried: candidates.length,
note: candidates.length + " key(s) of the right type were tried at key " +
"usage " + usage + " (" +
candidates.map(function (k, n) {
return k.label || "an unlabelled key " + (n + 1);
}).join("; ") +
") and none decrypted this, so the key that opens it is not among " +
"them. " + what +
" A key of the right type that does not work is either a different " +
"principal's or a stale kvno."
};
}
// The `decryption` row a failed attempt leaves behind, in one place because
// five callers write it and they must not disagree about what "no" means.
//
// The old value on all of them was "not attempted or not possible", which
// conflates the three states a reader has to tell apart: nothing to try with,
// something tried and failed, and this build cannot do that etype at all. The
// first is an instruction (supply a key), the second is a finding (that key is
// the wrong one), and reading the second as the first sends somebody off to
// find a key they already have.
function decryptionRow(attempt, whose, reported) {
// With the contents shown below from the KDC's own report, this row is
// context rather than a refusal, and it says so: "not opened" alone at the
// end of a pane reads as the dead end it used to be, three lines above the
// answer.
if (reported) {
return row("decryption",
"not opened — the contents are below, on the KDC's word",
attempt.note);
}
return row("decryption",
attempt.tried
? "not opened — " + attempt.tried + " key(s) of the right type tried " +
"and none worked"
: "not opened — no key supplied" + (whose ? " for " + whose : ""),
attempt.note);
}
// ---------------------------------------------------------------------------
// The per-message describers.
// ---------------------------------------------------------------------------
function describeEncryptedData(d, label) {
log.debug("Leaving describeEncryptedData().");
log.debug("Entering describeEncryptedData().");
return {
title: label,
rows: [
row("etype", d.etype + " " + d.etypeName),
row("kvno", d.kvno === null ? "(absent)" : d.kvno,
d.kvno === null ? null : "the key version — a stale one is " +
"KRB_AP_ERR_BADKEYVER"),
row("cipher", hexOf(d.cipher), prim.toBytes(d.cipher).length + " bytes")
]
};
}
// What it takes to open THIS ticket, in one sentence that names the account.
//
// "Supply the service's key" was true and unusable: on a TGT the reader is
// looking at `krbtgt/EXAMPLE.COM` and there is no service in sight, and on a
// service ticket they still have to work out that the account they need is the
// one in `sname` rather than the one they authenticated as. So the sentence
// names the principal and says which key that is on a ticket-granting ticket.
// The word "service" stays in it because `sname` is a service principal
// whatever the ticket is for.
//
// It names NO PANE and no other page. Where a key can be supplied differs per
// page, and a sentence that sends the reader somewhere else is the thing this
// whole change exists to remove — when `reported` is present the contents are
// already on screen and nothing needs supplying at all.
function ticketKeyGuidance(ticket, reported) {
log.debug("Entering ticketKeyGuidance().");
var whose = msgs.principalToString(ticket.sname, ticket.realm);
var isTgt = !!(ticket.sname && ticket.sname.name &&
ticket.sname.name[0] === "krbtgt");
log.debug("Leaving ticketKeyGuidance().");
return "Only the service principal " + whose + "'s own long-term key opens " +
"this ciphertext, at key usage 2" +
(ticket.encPart.kvno === null ? "" : " and kvno " + ticket.encPart.kvno) +
" — " +
(isTgt
? "and on a ticket-granting ticket that is the KDC's own krbtgt key, " +
"which no client ever holds."
: "and a client never holds the key of a service it presents a ticket " +
"to.") +
(reported
? " Which is why the KDC repeats the ticket's contents to the client " +
"in the reply, and those are decrypted and shown below — everything " +
"the ticket says except its authorization-data."
: " Supply that key, its password and salt, or a keytab holding it to " +
"read the session key, the client name and the PAC.");
}
// ---------------------------------------------------------------------------
// The ticket's contents WITHOUT the ticket's key, which is the normal case and
// was being reported as a dead end.
//
// A client cannot decrypt a ticket it holds — that is the point of a ticket —
// but it is not left ignorant of what is inside one, because the KDC tells it:
// `EncKDCRepPart` repeats the ticket's flags, session key, times and `sname`
// into the part of the reply encrypted under the CLIENT's own key, which the
// page has already opened. So the fields a reader wants are available with no
// key, no keytab and nothing to type, and the only honest thing missing is the
// **authorization-data** — the PAC — which the KDC does not repeat.
//
// Two things about this are load-bearing rather than decoration:
//
// * **It is labelled as a statement rather than as a decryption.** The
// values
// come from the KDC's word, not from the ciphertext above: a KDC that put
// different flags in the ticket than it reported would be invisible to any
// client, and a debugger that printed the two indistinguishably would be
// hiding exactly the discrepancy somebody comes here to find. The section
// title, the note and `source` all say where the values came from.
// * **It does not suppress the decryption attempt.** If a key that opens the
// ticket IS available the real `EncTicketPart` is shown instead — actual
// plaintext beats a report of it, and that is also the only way the PAC can
// ever appear.
//
// `reported` is deliberately made of primitives (strings, Dates, a hex string)
// rather than a decoded structure: the callers have the values in different
// shapes — a decrypted `EncKDCRepPart` in `describeKdcRep()`, a stored
// credential-cache entry everywhere else — and normalising at the call site
// keeps one renderer instead of three.
//
// It is reached for EVERY ticket on every page now, not only the one a reply
// just issued: `kerberos_panes.js` hands the whole credential cache to
// `describe()` and `reportedFor()` matches each ticket to its own record. So a
// TGT presented inside a TGS-REQ, and a service ticket presented inside a
// SPNEGO mechToken, read the same as one arriving in a reply — which is the
// point, because those are the two places a reader was previously told to go
// and find a key.
// ---------------------------------------------------------------------------
function describeReportedTicketContents(reported) {
log.debug("Entering describeReportedTicketContents().");
var rows = [
row("flags", (reported.flagNames || []).join(", ") || "(none)"),
row("key", (reported.sessionKey && reported.sessionKey.etypeName
? reported.sessionKey.etypeName + ", " : "") +
((reported.sessionKey && reported.sessionKey.hex) || "(absent)"),
"the SESSION key — a credential in itself, and the one field here the " +
"client needs rather than merely wants: it is what signs the next " +
"request"),
row("crealm", reported.crealm),
row("cname", reported.cname),
row("authtime", timeOf(reported.authtime)),
row("starttime", timeOf(reported.starttime)),
row("endtime", timeOf(reported.endtime)),
row("renew-till", timeOf(reported.renewTill)),
row("srealm", reported.srealm),
row("sname", reported.sname),
row("authorization-data", "(not repeated in the reply)",
"The one field the KDC does not tell the client about, and on Active " +
"Directory it is the PAC — the SIDs and group memberships a Windows " +
"service authorizes on. It exists only inside the ciphertext above, so " +
"reading it needs that service's own key; nothing a client holds will " +
"do.")
];
log.debug("Leaving describeReportedTicketContents().");
return {
title: "EncTicketPart — as the KDC reported it",
note: reported.source + " These are the ticket's contents on the KDC's " +
"word rather than out of the ciphertext above, which is the most a " +
"client can have: the two agree unless the KDC is lying, and only " +
"something holding " + (reported.sname || "the service") + "'s key can " +
"tell the difference.",
rows: rows
};
}
// ---------------------------------------------------------------------------
// WHICH report belongs to THIS ticket, out of what the caller knows.
//
// `reported` arrives in two shapes and both are legitimate:
//
// * a SINGLE record — the KDC reply's own account of the ticket it has just
// issued (describeKdcRep), or a page's stored copy of one for a ticket it
// is showing on its own (the bare-Ticket path in describe()). It is about
// the ticket in hand and needs no matching.
// * a LIST — what a PAGE knows about every ticket the workflow holds. A
// message routinely carries a ticket the caller was not thinking of: the
// TGT inside a TGS-REQ's PA-TGS-REQ, the service ticket inside an AP-REQ
// inside a SPNEGO mechToken. So a list has to be matched against the
// ticket rather than assumed to be about it.
//
// **The match is on the ticket's own DER and on nothing else.** Two tickets
// for the same principal are not the same ticket — a re-issued one has a
// different session key and different times — so matching by `sname` would
// print one ticket's contents under another's ciphertext, which is precisely
// the mistake this whole report exists not to make. A ticket goes on the wire
// byte-for-byte and is stored byte-for-byte, so the comparison is exact
// wherever the workflow has a record at all, and where it has none the ticket
// is described as unopened rather than approximately.
// ---------------------------------------------------------------------------
function reportedFor(reported, ticket) {
log.debug("Entering reportedFor().");
if (!reported) {
log.debug("Leaving reportedFor(). Nothing known.");
return null;
}
if (!Array.isArray(reported)) {
log.debug("Leaving reportedFor(). A single record.");
return reported;
}
var hex = null;
try {
hex = prim.toHex(prim.toBytes(ticket.raw));
} catch (e) {
// A ticket this reader built rather than read may carry no raw bytes.
// Nothing can be matched then, which is a miss and not an error.
log.warn("this ticket carries no raw bytes to match on: " + e.message);
hex = null;
}
for (var i = 0; hex && i < reported.length; i++) {
if (reported[i] && reported[i].ticketHex === hex) {
log.debug("Leaving reportedFor(). Matched record " + i + ".");
return reported[i];
}
}
log.debug("Leaving reportedFor(). No record of this ticket.");
return null;
}
async function describeTicket(ticket, keys, problems, known) {
log.debug("Entering describeTicket().");
var reported = reportedFor(known, ticket);
var whose = msgs.principalToString(ticket.sname, ticket.realm);
var section = {
title: "Ticket",
note: "Encrypted under the SERVICE principal " + whose + "'s own " +
"long-term key, so its holder cannot read it" +
(reported
? " — the contents below are the KDC's own account of what is in it."
: ". Supply that key, its password and salt, or a keytab holding " +
"it to see inside."),
rows: [
row("tkt-vno", ticket.tktVno),
row("realm", ticket.realm),
row("sname", principalOf(ticket.sname, ticket.realm))
],
sections: [describeEncryptedData(ticket.encPart, "Ticket enc-part " +
"(EncTicketPart)")]
};
if (ticket.tktVno !== 5) {
problems.push("The ticket's tkt-vno is " + ticket.tktVno + ", not 5.");
}
var attempt = await tryDecrypt(ticket.encPart,
kcrypto.KEY_USAGE.KDC_REP_TICKET, keys,
ticketKeyGuidance(ticket, reported));
if (attempt.ok) {
try {
var part = msgs.readEncTicketPart(attempt.plain);
section.sections.push(await describeEncTicketPart(part, attempt.usedKey,
problems, keys));
} catch (e) {
section.sections.push({
title: "EncTicketPart",
rows: [row("decrypted, but", e.message)]
});
}
} else {
section.sections[0].rows.push(decryptionRow(attempt, whose, reported));
// The contents anyway, from the KDC's own report of them. Pushed as a
// SIBLING of the enc-part rather than inside it, because it is not what
// came out of that ciphertext and must not read as though it were.
if (reported) {
section.sections.push(describeReportedTicketContents(reported));
}
}
log.debug("Leaving describeTicket().");
return section;
}
async function describeEncTicketPart(p, usedKey, problems, keys) {
log.debug("Entering describeEncTicketPart().");
var rows = [
row("flags", msgs.ticketFlagNames(p.flags).join(", ") || "(none)",
"bits " + p.flags.join(", ")),
row("key", p.key.etypeName + ", " + hexOf(p.key.key), "the SESSION key — " +
"a credential in itself"),
row("crealm", p.crealm),
row("cname", principalOf(p.cname, p.crealm)),
row("authtime", timeOf(p.authtime)),
row("starttime", timeOf(p.starttime)),
row("endtime", timeOf(p.endtime)),
row("renew-till", timeOf(p.renewTill))
];
if (p.caddr) {
rows.push(row("caddr", p.caddr.map(function (a) {
return "type " + a.type + " " + prim.toHex(a.address);
}).join(", "), "an address-restricted ticket; AD issues addressless ones"));
}
var pacSections = [];
if (p.authorizationData) {
rows.push(row("authorization-data", p.authorizationData.map(function (ad) {
return kpac.adTypeName(ad.type) + " (" + prim.toBytes(ad.data).length +
" bytes)";
}).join(", "), "the top-level elements only; the PAC is nested inside " +
"AD-IF-RELEVANT"));
var found = kpac.findPacs(p.authorizationData);
if (!found.length) {
rows.push(row("PAC", "none",
"no AD-WIN2K-PAC in here. A ticket from Active Directory carries one " +
"unless the account " +
"has USER_NO_AUTH_DATA_REQUIRED set or the client asked for none — " +
"and a service that " +
"authorizes on groups has nothing to read without it"));
} else if (found.length > 1) {
problems.push("This ticket carries " + found.length + " PACs. A ticket " +
"has one; the extra " +
"ones are a place to hide a different set of groups.");
}
// The key that opened this ticket IS the service's long-term key by
// definition, so it is exactly the key the server signature is made with —
// which is why the PAC's signatures can be checked at all here without
// asking for anything more.
var pool = (keys || []).slice();
if (usedKey && pool.indexOf(usedKey) === -1) pool.push(usedKey);
for (var i = 0; i < found.length; i++) {
// usedKey is passed as the ASSERTED service key, not merely thrown into
// the pool: a server signature that fails against the key which just
// decrypted this ticket is a real finding, while the KDC signature
// failing against a pool of unlabelled keys is only ever "you do not have
// the krbtgt key".
pacSections.push(await describePac(found[i], pool, problems, usedKey));
}
}
if (p.flags.indexOf(msgs.TICKET_FLAG.OK_AS_DELEGATE) !== -1) {
rows.push(row("note", "ok-as-delegate is set",
"the KDC is telling the client this service may be trusted with " +
"delegated credentials"));
}
log.debug("Leaving describeEncTicketPart().");
return {
title: "EncTicketPart (decrypted)",
note: usedKey ? "Decrypted with " + (usedKey.label || "a supplied key") +
"." : null,
rows: rows,
sections: pacSections
};
}
// ---------------------------------------------------------------------------
// The PAC.
//
// Presented as its own nest of sections rather than a row of hex, because this is the
// structure that decides what the ticket's holder can DO — a service authorizes on the
// groups in here, not on the ticket's cname. See krb5_pac.js's header for the wire
// format and for why the four signatures are not interchangeable.
//
// The rule from this file's header applies throughout: `problems` is for what is
// WRONG. An undecoded buffer is not a problem, an absent one usually is not either,
// and a group list a real service would ignore very much is.
// ---------------------------------------------------------------------------
async function describePac(found, keys, problems, serviceKey) {
log.debug("Entering describePac(). bytes=" + found.bytes.length);
var parsed;
try {
parsed = kpac.parsePac(found.bytes);
} catch (e) {
// A PAC that will not parse at all is content, not an exception: the reader
// wants to know that, and to see how big the thing was.
return {
title: "PAC (does not parse)",
note: "Found at " + found.path + ", " + found.bytes.length + " bytes.",
rows: [row("error", e.message)]
};
}
parsed.problems.forEach(function (p) { problems.push("PAC: " + p); });
var section = {
title: "PAC (Privilege Attribute Certificate)",
note: "Found at " + found.path + ". " + found.bytes.length + " bytes in " +
parsed.cBuffers +
" buffer(s). This is what a Windows service reads to decide what the " +
"holder may do — " +
"everything from here down is little-endian C structures and NDR, not " +
"DER.",
rows: [
row("buffers", parsed.buffers.map(function (b) {
return b.type + " " + b.typeName + " — " + b.size +
" bytes at offset " + b.offset;
}).join("\n")),
row("PACTYPE Version", parsed.version, parsed.version === 0 ? null :
"[MS-PAC] requires 0")
],
sections: []
};
var logon = kpac.bufferOfType(parsed, kpac.TYPE.LOGON_INFO);
if (logon &&
logon.parsed) section.sections.push(describeLogonInfo(logon.parsed,
problems));
else if (logon) {
section.sections.push({
title: "Logon information (KERB_VALIDATION_INFO)",
rows: [row("does not parse", logon.error || "(no reason recorded)")]
});
}
var client = kpac.bufferOfType(parsed, kpac.TYPE.CLIENT_INFO);
if (client && client.parsed) {
section.sections.push({
title: "Client name and ticket information",
note: "Used to check the PAC belongs to this ticket's client rather " +
"than to another one.",
rows: [
row("name", client.parsed.name),
row("ClientId", client.parsed.clientId.text,
"the INITIAL TGT's authentication time, which is the same across " +
"every service " +
"ticket derived from it — not this ticket's authtime")
]
});
}
var upn = kpac.bufferOfType(parsed, kpac.TYPE.UPN_DNS_INFO);
if (upn && upn.parsed) {
var u = upn.parsed;
section.sections.push({
title: "UPN and DNS information",
rows: [
row("UPN", u.upn),
row("DNS domain name", u.dnsDomainName),
row("SAM name", u.samName, u.extended ? null : "only present when " +
"the S flag is set"),
row("SID", u.sid ? u.sid.text : null),
row("flags", u.flagNames.join("\n") || "(none set)")
]
});
}
var attrs = kpac.bufferOfType(parsed, kpac.TYPE.ATTRIBUTES_INFO);
if (attrs && attrs.parsed) {
section.sections.push({
title: "PAC attributes",
rows: [
row("flags", attrs.parsed.flagNames.join(", ") || "(none set)",
attrs.parsed.flagNames.indexOf("PAC_WAS_GIVEN_IMPLICITLY") !== -1
? "the client neither asked for nor declined a PAC" : null),
row("FlagsLength", attrs.parsed.flagsLength + " bits")
]
});
}
var requestor = kpac.bufferOfType(parsed, kpac.TYPE.REQUESTOR_SID);
if (requestor && requestor.parsed) {
section.sections.push({
title: "PAC requestor",
note: "The SID of the account that ASKED for this ticket. In a " +
"delegation flow that is " +
"not the account the ticket is for, which is the whole point of the " +
"buffer.",
rows: [row("SID", requestor.parsed.sid.text +
(requestor.parsed.name ? " (" + requestor.parsed.name + ")" : ""))]
});
}
// The two claims buffers ([MS-PAC] 2.11), decoded since 2026-10-06. One
// row per claim, its id, type and values — and the compression, because a
// set that arrived compressed and was decompressed here is a fact about the
// KDC that wrote it.
[kpac.TYPE.CLIENT_CLAIMS, kpac.TYPE.DEVICE_CLAIMS].forEach(function (t) {
var buffer = kpac.bufferOfType(parsed, t);
if (!buffer) {
return;
}
if (!buffer.parsed) {
section.sections.push({
title: buffer.typeName,
rows: [row("does not parse", buffer.error || "(no reason recorded)")]
});
return;
}
var c = buffer.parsed;
var rows = c.empty
? [row("claims", "(an empty buffer: no claims)")]
: [row("compression", c.compressionName, c.compressionFormat ?
"decompressed here: " + c.claimsSetSize + " bytes to " +
c.uncompressedClaimsSetSize : null)].concat(
c.claims.map(function (claim) {
return row(claim.id, claim.typeName + ": " +
claim.values.join(", "), "source " +
(claim.sourceType === kpac.CLAIMS_SOURCE_TYPE.AD ? "AD" :
claim.sourceType));
}));
section.sections.push({
title: buffer.typeName,
note: t === kpac.TYPE.CLIENT_CLAIMS
? "The client's claims — what a service doing claims-based access " +
"control (Dynamic Access Control) authorizes on, beside the SIDs."
: "The claims of the DEVICE the client authenticated from, present " +
"only with compound identity (FAST armor naming a computer).",
rows: rows
});
});
// Anything present that this codec does not decode, listed rather than
// dropped.
var undecoded = parsed.buffers.filter(function (b) {
return b.parsed === null && !b.error && !kpac.isSignatureBuffer(b.type);
});
if (undecoded.length) {
section.sections.push({
title: "Buffers not decoded here",
note: "Present in the PAC and not read by this codec. Listed rather " +
"than dropped, because " +
"'present but not decoded' is a different fact from 'absent'.",
rows: undecoded.map(function (b) {
return row(b.typeName, b.size + " bytes", hexOf(b.bytes, 32));
})
});
}
section.sections.push(await describePacSignatures(parsed, keys, problems,
serviceKey));
log.debug("Leaving describePac().");
return section;
}
function describeLogonInfo(info, problems) {
log.debug("Entering describeLogonInfo().");
var rows = [
row("account", info.effectiveName, info.fullName ? "full name: " +
info.fullName : null),
row("account SID", info.userSid,
"assembled from LogonDomainId + UserId (" + info.userId + ") — a PAC " +
"never carries it whole"),
row("primary group SID", info.primaryGroupSid, "RID " +
info.primaryGroupId +
(kpac.ridName(info.primaryGroupId) ? ", " +
kpac.ridName(info.primaryGroupId) : "")),
row("logon domain", info.logonDomainName +
(info.logonDomainId ? " (" + info.logonDomainId.text + ")" : "")),
row("logon server", info.logonServer, "the DC that issued the initial TGT"),
row("UserAccountControl", info.userAccountControlNames.join("\n") ||
"(none set)",
"[MS-SAMR]'s USER_ACCOUNT codes, not the LDAP userAccountControl bits"),
row("UserFlags", info.userFlagNames.join("\n") || "(none set)"),
row("logon count", info.logonCount),
row("bad password count", info.badPasswordCount),
row("logon time", info.logonTime.text),
row("logoff time", info.logoffTime.text),
row("kickoff time", info.kickOffTime.text),
row("password last set", info.passwordLastSet.text),
row("password must change", info.passwordMustChange.text),
row("groups (" + info.groups.length + ")", info.groups.length
? info.groups.map(function (g) {
return (info.logonDomainId ? info.logonDomainId.text + "-" : "RID ") +
g.relativeId +
(g.name ? " (" + g.name + ")" : "") + " [" +
g.attributeNames.join(", ") + "]";
}).join("\n")
: "(none)",
"groups in the ACCOUNT's domain, given as RIDs — the SID is the domain " +
"SID plus the RID")
];
if (info.extraSids.length) {
rows.push(row("extra SIDs (" + info.extraSids.length + ")",
info.extraSids.map(function (e) {
return e.text + (e.name ? " (" + e.name + ")" : "") + " [" +
e.attributeNames.join(", ") + "]";
}).join("\n"),
"SIDs from outside the account's domain, and the well-known ones that " +
"record HOW the " +
"identity was established"));
}
if (info.resourceGroups.length) {
rows.push(row("resource groups (" + info.resourceGroups.length + ")",
info.resourceGroups.map(function (g) {
return (info.resourceGroupDomainSid ?
info.resourceGroupDomainSid.text + "-" : "RID ") +
g.relativeId + (g.name ? " (" + g.name + ")" : "") + " [" +
g.attributeNames.join(", ") + "]";
}).join("\n"),
"domain-local groups in the RESOURCE's domain, which is a different " +
"domain SID from the " +
"account's"));
}
if (info.userSessionKey &&
!prim.toBytes(info.userSessionKey).every(function (b) { return b === 0; })) {
rows.push(row("UserSessionKey", hexOf(info.userSessionKey),
"[MS-PAC] requires this to be zero for Kerberos — it is an NTLM field"));
problems.push("The PAC's UserSessionKey is not zero. [MS-PAC] section " +
"2.5 requires zero for " +
"anything other than NTLM.");
}
// Each of these parses fine and changes how a real service behaves, which is
// the definition of a finding here rather than a note.
info.notes.forEach(function (n) { problems.push("PAC logon information: " +
n); });
log.debug("Leaving describeLogonInfo().");
return {
title: "Logon information (KERB_VALIDATION_INFO)",
note: "NDR-encoded ([MS-RPCE] section 2.2.6), which is why this one " +
"buffer starts with " +
"01 10 08 00 cc cc cc cc. These groups are what a Windows service " +
"authorizes on.",
rows: rows
};
}
async function describePacSignatures(parsed, keys, problems, serviceKey) {
log.debug("Entering describePacSignatures().");
var results = await kpac.verifySignaturesWithAnyKey(parsed, keys || [],
{ serverKey: serviceKey || null });
var rows = results.map(function (r) {
var state = r.verified === true ? "verified" : r.verified === false ?
"DOES NOT VERIFY"
: "not checked";
return row(r.name, state + " — " + r.signatureTypeName, r.note);
});
if (!results.length) {
rows.push(row("signatures", "none present",
"a PAC inside a ticket always carries at least the server and KDC " +
"signatures"));
}
// A signature that failed against a key we KNOW is the right one is a
// finding. One that no unlabelled key in the pool happened to verify is not —
// the reader has simply not supplied the krbtgt key, which on a service
// ticket they cannot have, and reporting that as tampering would cry wolf on
// every paste.
//
// Keyed off `roleAsserted` rather than off the wording of the note: matching
// prose is how this check silently stopped firing once the note was reworded.
results.forEach(function (r) {
if (r.verified === false && r.roleAsserted) {
problems.push("The PAC's " + r.name + " does not verify against the " +
r.role +
" — the very key that decrypted this ticket. Either the PAC has been " +
"altered since it " +
"was signed, or it was not signed for this service.");
}
});
log.debug("Leaving describePacSignatures().");
return {
title: "PAC signatures",
note: "Four signatures over four DIFFERENT things, with two different " +
"keys. A service holds " +
"only its own key, so it can check the server signature and nothing " +
"else — and altering " +
"the PAC's contents leaves the KDC signature intact, because that one " +
"covers only the " +
"server signature's bytes. That is why the extended KDC signature " +
"exists.",
rows: rows
};
}
async function describeKdcReq(req, input, keys, problems, known) {
log.debug("Entering describeKdcReq().");
var isTgs = req.msgType === msgs.MSG_TYPE.TGS_REQ;
var body = req.reqBody;
var doc = {
kind: isTgs ? "TGS-REQ" : "AS-REQ",
summary: (isTgs ? "A ticket-granting request" : "An " +
"authentication-service request") +
" for " + msgs.principalToString(body.sname || { name: ["(no sname)"] },
body.realm) +
(body.cname ? " by " + msgs.principalToString(body.cname) : ""),
sections: []
};
doc.sections.push({
title: "Message",
rows: [
row("pvno", req.pvno),
row("msg-type", req.msgType + " (" + doc.kind + ")")
]
});
var padataRows = [];
req.padata.forEach(function (pa) {
padataRows.push(row(pa.typeName + " (" + pa.type + ")",
prim.toBytes(pa.value).length + " bytes"));
});
doc.sections.push({
title: "Pre-authentication (padata)",
note: req.padata.length ? null
: (isTgs
? "A TGS-REQ with no PA-TGS-REQ cannot be answered — the TGT " +
"travels in the padata."
: "None. An AS-REQ without PA-ENC-TIMESTAMP is what a KDC answers " +
"with " +
"KDC_ERR_PREAUTH_REQUIRED, and that answer is where the salt " +
"comes from."),
rows: padataRows.length ? padataRows : [row("padata", "(none)")]
});
if (isTgs &&
!req.padata.some(function (p) { return p.type === msgs.PA_TYPE.TGS_REQ; })) {
problems.push("This TGS-REQ carries no PA-TGS-REQ, so it has no TGT and " +
"no KDC can answer it.");
}
// The padata worth expanding.
//
// A `for` loop rather than a forEach because two of these entries are now
// OPENED rather than merely measured, and decryption is async:
// PA-ENC-TIMESTAMP under the client's own key, and the AP-REQ inside
// PA-TGS-REQ — which carries a whole ticket of its own and is the one
// structure in this protocol that is routinely three envelopes deep.
for (var pi = 0; pi < req.padata.length; pi++) {
var pa = req.padata[pi];
if (pa.type === msgs.PA_TYPE.ENC_TIMESTAMP) {
try {
var enc = msgs.readEncryptedData(asn1.readTlv(pa.value, 0));
var stampSection = describeEncryptedData(enc, "PA-ENC-TIMESTAMP " +
"(encrypted with the client's key)");
doc.sections.push(stampSection);
// Key usage 1, and only 1. A reader who has the client's key — which on
// the AS page is the page that just derived it — can see the timestamp
// the KDC is about to compare against its own clock, and that is the
// whole content of a pre-authentication failure.
var stampAttempt = await tryDecrypt(enc,
kcrypto.KEY_USAGE.AS_REQ_PA_ENC_TIMESTAMP, keys,
"Supply the client's key, or its password and salt, to read the " +
"timestamp inside. Unlike a ticket's key this is one a client HAS — " +
"whatever built this field derived it from the password — so \"not " +
"opened\" here is a key that does not match rather than a key " +
"nobody could have.");
if (stampAttempt.ok) {
try {
var stamp = msgs.readPaEncTsEnc(stampAttempt.plain);
doc.sections.push({
title: "PA-ENC-TS-ENC (decrypted)",
note: "Decrypted with " + (stampAttempt.usedKey.label ||
"a supplied key") + " at key usage 1.",
rows: [
row("patimestamp", timeOf(stamp.patimestamp),
"compared against the KDC's own clock — five minutes on " +
"Active Directory, and KRB_AP_ERR_SKEW outside it"),
row("pausec", stamp.pausec)
]
});
} catch (e) {
doc.sections.push({
title: "PA-ENC-TS-ENC",
rows: [row("decrypted, but does not parse", e.message)]
});
}
} else {
stampSection.rows.push(decryptionRow(stampAttempt,
"the client's key"));
}
} catch (e) {
problems.push("PA-ENC-TIMESTAMP does not decode as EncryptedData: " +
e.message);
}
}
if (pa.type === msgs.PA_TYPE.TGS_REQ) {