1# SPDX-License-Identifier: GPL-2.0-or-later
2# This file is part of Scapy
3# See https://scapy.net/ for more information
4# Copyright (C) Gabriel Potter
5
6# scapy.contrib.description = DCE/RPC
7# scapy.contrib.status = loads
8
9"""
10DCE/RPC
11Distributed Computing Environment / Remote Procedure Calls
12
13Based on [C706] - aka DCE/RPC 1.1
14https://pubs.opengroup.org/onlinepubs/9629399/toc.pdf
15
16And on [MS-RPCE]
17https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-rpce/290c38b1-92fe-4229-91e6-4fc376610c15
18
19.. note::
20 Please read the documentation over
21 `DCE/RPC <https://scapy.readthedocs.io/en/latest/layers/dcerpc.html>`_
22"""
23
24from functools import partial
25
26import collections
27import struct
28from enum import IntEnum
29from uuid import UUID
30from scapy.base_classes import Packet_metaclass
31
32from scapy.config import conf
33from scapy.compat import bytes_encode, plain_str
34from scapy.error import log_runtime
35from scapy.layers.dns import DNSStrField
36from scapy.layers.ntlm import (
37 NTLM_Header,
38 NTLMSSP_MESSAGE_SIGNATURE,
39)
40from scapy.packet import (
41 Packet,
42 Raw,
43 bind_bottom_up,
44 bind_layers,
45 bind_top_down,
46 NoPayload,
47)
48from scapy.fields import (
49 _FieldContainer,
50 BitEnumField,
51 BitField,
52 ByteEnumField,
53 ByteField,
54 ConditionalField,
55 EnumField,
56 Field,
57 FieldLenField,
58 FieldListField,
59 FlagsField,
60 IntField,
61 LEIntEnumField,
62 LEIntField,
63 LELongField,
64 LEShortEnumField,
65 LEShortField,
66 LenField,
67 MultipleTypeField,
68 PacketField,
69 PacketLenField,
70 PacketListField,
71 PadField,
72 ReversePadField,
73 ShortEnumField,
74 ShortField,
75 SignedByteField,
76 StrField,
77 StrFixedLenField,
78 StrLenField,
79 StrLenFieldUtf16,
80 StrNullField,
81 StrNullFieldUtf16,
82 TrailerField,
83 UUIDEnumField,
84 UUIDField,
85 XByteField,
86 XLEIntField,
87 XLELongField,
88 XLEShortField,
89 XShortField,
90 XStrFixedLenField,
91)
92from scapy.sessions import DefaultSession
93from scapy.supersocket import StreamSocket
94
95from scapy.layers.kerberos import (
96 KRB_InnerToken,
97 Kerberos,
98)
99from scapy.layers.gssapi import (
100 GSS_S_COMPLETE,
101 GSSAPI_BLOB_SIGNATURE,
102 GSSAPI_BLOB,
103 SSP,
104)
105from scapy.layers.inet import TCP
106
107from scapy.contrib.rtps.common_types import (
108 EField,
109 EPacket,
110 EPacketField,
111 EPacketListField,
112)
113
114# Typing imports
115from typing import (
116 Optional,
117)
118
119# the alignment of auth_pad
120# This is 4 in [C706] 13.2.6.1 but was updated to 16 in [MS-RPCE] 2.2.2.11
121_COMMON_AUTH_PAD = 16
122# the alignment of the NDR Type 1 serialization private header
123# ([MS-RPCE] sect 2.2.6.2)
124_TYPE1_S_PAD = 8
125
126# DCE/RPC Packet
127DCE_RPC_TYPE = {
128 0: "request",
129 1: "ping",
130 2: "response",
131 3: "fault",
132 4: "working",
133 5: "no_call",
134 6: "reject",
135 7: "acknowledge",
136 8: "connectionless_cancel",
137 9: "frag_ack",
138 10: "cancel_ack",
139 11: "bind",
140 12: "bind_ack",
141 13: "bind_nak",
142 14: "alter_context",
143 15: "alter_context_resp",
144 16: "auth3",
145 17: "shutdown",
146 18: "co_cancel",
147 19: "orphaned",
148}
149_DCE_RPC_4_FLAGS1 = [
150 "reserved_01",
151 "last_frag",
152 "frag",
153 "no_frag_ack",
154 "maybe",
155 "idempotent",
156 "broadcast",
157 "reserved_7",
158]
159_DCE_RPC_4_FLAGS2 = [
160 "reserved_0",
161 "cancel_pending",
162 "reserved_2",
163 "reserved_3",
164 "reserved_4",
165 "reserved_5",
166 "reserved_6",
167 "reserved_7",
168]
169DCE_RPC_TRANSFER_SYNTAXES = {
170 UUID("00000000-0000-0000-0000-000000000000"): "NULL",
171 UUID("6cb71c2c-9812-4540-0300-000000000000"): "Bind Time Feature Negotiation",
172 UUID("8a885d04-1ceb-11c9-9fe8-08002b104860"): "NDR 2.0",
173 UUID("71710533-beba-4937-8319-b5dbef9ccc36"): "NDR64",
174}
175DCE_RPC_INTERFACES_NAMES = {}
176DCE_RPC_INTERFACES_NAMES_rev = {}
177
178
179class DCERPC_Transport(IntEnum):
180 NCACN_IP_TCP = 1
181 NCACN_NP = 2
182 # TODO: add more.. if people use them?
183
184
185def _dce_rpc_endianess(pkt):
186 """
187 Determine the right endianness sign for a given DCE/RPC packet
188 """
189 if pkt.endian == 0: # big endian
190 return ">"
191 elif pkt.endian == 1: # little endian
192 return "<"
193 else:
194 return "!"
195
196
197class _EField(EField):
198 def __init__(self, fld):
199 super(_EField, self).__init__(fld, endianness_from=_dce_rpc_endianess)
200
201
202class DceRpc(Packet):
203 """DCE/RPC packet"""
204
205 @classmethod
206 def dispatch_hook(cls, _pkt=None, *args, **kargs):
207 if _pkt and len(_pkt) >= 1:
208 ver = ord(_pkt[0:1])
209 if ver == 4:
210 return DceRpc4
211 elif ver == 5:
212 return DceRpc5
213 return DceRpc5
214
215
216bind_bottom_up(TCP, DceRpc, sport=135)
217bind_layers(TCP, DceRpc, dport=135)
218
219
220class _DceRpcPayload(Packet):
221 @property
222 def endianness(self):
223 if not self.underlayer:
224 return "!"
225 return _dce_rpc_endianess(self.underlayer)
226
227
228# sect 12.5
229
230_drep = [
231 BitEnumField("endian", 1, 4, ["big", "little"]),
232 BitEnumField("encoding", 0, 4, ["ASCII", "EBCDIC"]),
233 ByteEnumField("float", 0, ["IEEE", "VAX", "CRAY", "IBM"]),
234 ByteField("reserved1", 0),
235]
236
237
238class DceRpc4(DceRpc):
239 """
240 DCE/RPC v4 'connection-less' packet
241 """
242
243 name = "DCE/RPC v4"
244 fields_desc = (
245 [
246 ByteEnumField(
247 "rpc_vers", 4, {4: "4 (connection-less)", 5: "5 (connection-oriented)"}
248 ),
249 ByteEnumField("ptype", 0, DCE_RPC_TYPE),
250 FlagsField("flags1", 0, 8, _DCE_RPC_4_FLAGS1),
251 FlagsField("flags2", 0, 8, _DCE_RPC_4_FLAGS2),
252 ]
253 + _drep
254 + [
255 XByteField("serial_hi", 0),
256 _EField(UUIDField("object", None)),
257 _EField(UUIDField("if_id", None)),
258 _EField(UUIDField("act_id", None)),
259 _EField(IntField("server_boot", 0)),
260 _EField(IntField("if_vers", 1)),
261 _EField(IntField("seqnum", 0)),
262 _EField(ShortField("opnum", 0)),
263 _EField(XShortField("ihint", 0xFFFF)),
264 _EField(XShortField("ahint", 0xFFFF)),
265 _EField(LenField("len", None, fmt="H")),
266 _EField(ShortField("fragnum", 0)),
267 ByteEnumField("auth_proto", 0, ["none", "OSF DCE Private Key"]),
268 XByteField("serial_lo", 0),
269 ]
270 )
271
272
273# Exceptionally, we define those 3 here.
274
275
276class NL_AUTH_MESSAGE(Packet):
277 # [MS-NRPC] sect 2.2.1.3.1
278 name = "NL_AUTH_MESSAGE"
279 fields_desc = [
280 LEIntEnumField(
281 "MessageType",
282 0x00000000,
283 {
284 0x00000000: "Request",
285 0x00000001: "Response",
286 },
287 ),
288 FlagsField(
289 "Flags",
290 0,
291 -32,
292 [
293 "NETBIOS_DOMAIN_NAME",
294 "NETBIOS_COMPUTER_NAME",
295 "DNS_DOMAIN_NAME",
296 "DNS_HOST_NAME",
297 "NETBIOS_COMPUTER_NAME_UTF8",
298 ],
299 ),
300 ConditionalField(
301 StrNullField("NetbiosDomainName", ""),
302 lambda pkt: pkt.Flags.NETBIOS_DOMAIN_NAME,
303 ),
304 ConditionalField(
305 StrNullField("NetbiosComputerName", ""),
306 lambda pkt: pkt.Flags.NETBIOS_COMPUTER_NAME,
307 ),
308 ConditionalField(
309 DNSStrField("DnsDomainName", ""),
310 lambda pkt: pkt.Flags.DNS_DOMAIN_NAME,
311 ),
312 ConditionalField(
313 DNSStrField("DnsHostName", ""),
314 lambda pkt: pkt.Flags.DNS_HOST_NAME,
315 ),
316 ConditionalField(
317 # What the fuck? Why are they doing this
318 # The spec is just wrong
319 DNSStrField("NetbiosComputerNameUtf8", ""),
320 lambda pkt: pkt.Flags.NETBIOS_COMPUTER_NAME_UTF8,
321 ),
322 ]
323
324
325class NL_AUTH_SIGNATURE(Packet):
326 # [MS-NRPC] sect 2.2.1.3.2/2.2.1.3.3
327 name = "NL_AUTH_(SHA2_)SIGNATURE"
328 fields_desc = [
329 LEShortEnumField(
330 "SignatureAlgorithm",
331 0x0077,
332 {
333 0x0077: "HMAC-MD5",
334 0x0013: "HMAC-SHA256",
335 },
336 ),
337 LEShortEnumField(
338 "SealAlgorithm",
339 0xFFFF,
340 {
341 0xFFFF: "Unencrypted",
342 0x007A: "RC4",
343 0x00A1: "AES-128",
344 },
345 ),
346 XLEShortField("Pad", 0xFFFF),
347 ShortField("Flags", 0),
348 XStrFixedLenField("SequenceNumber", b"", length=8),
349 XStrFixedLenField("Checksum", b"", length=8),
350 ConditionalField(
351 XStrFixedLenField("Confounder", b"", length=8),
352 lambda pkt: pkt.SealAlgorithm != 0xFFFF,
353 ),
354 MultipleTypeField(
355 [
356 (
357 StrFixedLenField("Reserved2", b"", length=24),
358 lambda pkt: pkt.SignatureAlgorithm == 0x0013,
359 ),
360 ],
361 StrField("Reserved2", b""),
362 ),
363 ]
364
365
366# [MS-RPCE] sect 2.2.1.1.7
367# https://learn.microsoft.com/en-us/windows/win32/rpc/authentication-service-constants
368# rpcdce.h
369
370
371class RPC_C_AUTHN(IntEnum):
372 NONE = 0x00
373 DCE_PRIVATE = 0x01
374 DCE_PUBLIC = 0x02
375 DEC_PUBLIC = 0x04
376 GSS_NEGOTIATE = 0x09
377 WINNT = 0x0A
378 GSS_SCHANNEL = 0x0E
379 GSS_KERBEROS = 0x10
380 DPA = 0x11
381 MSN = 0x12
382 KERNEL = 0x14
383 DIGEST = 0x15
384 NEGO_EXTENDED = 0x1E
385 PKU2U = 0x1F
386 LIVE_SSP = 0x20
387 LIVEXP_SSP = 0x23
388 CLOUD_AP = 0x24
389 NETLOGON = 0x44
390 MSONLINE = 0x52
391 MQ = 0x64
392 DEFAULT = 0xFFFFFFFF
393
394
395class RPC_C_AUTHN_LEVEL(IntEnum):
396 DEFAULT = 0x0
397 NONE = 0x1
398 CONNECT = 0x2
399 CALL = 0x3
400 PKT = 0x4
401 PKT_INTEGRITY = 0x5
402 PKT_PRIVACY = 0x6
403
404
405DCE_C_AUTHN_LEVEL = RPC_C_AUTHN_LEVEL # C706 name
406
407
408# C706 sect 13.2.6.1
409
410
411class CommonAuthVerifier(Packet):
412 name = "Common Authentication Verifier"
413 fields_desc = [
414 ByteEnumField(
415 "auth_type",
416 0,
417 RPC_C_AUTHN,
418 ),
419 ByteEnumField("auth_level", 0, RPC_C_AUTHN_LEVEL),
420 ByteField("auth_pad_length", None),
421 ByteField("auth_reserved", 0),
422 XLEIntField("auth_context_id", 0),
423 MultipleTypeField(
424 [
425 # SPNEGO
426 (
427 PacketLenField(
428 "auth_value",
429 GSSAPI_BLOB(),
430 GSSAPI_BLOB,
431 length_from=lambda pkt: pkt.parent.auth_len,
432 ),
433 lambda pkt: pkt.auth_type == 0x09 and pkt.parent and
434 # Bind/Alter
435 pkt.parent.ptype in [11, 12, 13, 14, 15, 16],
436 ),
437 (
438 PacketLenField(
439 "auth_value",
440 GSSAPI_BLOB_SIGNATURE(),
441 GSSAPI_BLOB_SIGNATURE,
442 length_from=lambda pkt: pkt.parent.auth_len,
443 ),
444 lambda pkt: pkt.auth_type == 0x09
445 and pkt.parent
446 and (
447 # Other
448 not pkt.parent
449 or pkt.parent.ptype not in [11, 12, 13, 14, 15, 16]
450 ),
451 ),
452 # Kerberos
453 (
454 PacketLenField(
455 "auth_value",
456 Kerberos(),
457 Kerberos,
458 length_from=lambda pkt: pkt.parent.auth_len,
459 ),
460 lambda pkt: pkt.auth_type == 0x10 and pkt.parent and
461 # Bind/Alter
462 pkt.parent.ptype in [11, 12, 13, 14, 15, 16],
463 ),
464 (
465 PacketLenField(
466 "auth_value",
467 KRB_InnerToken(),
468 KRB_InnerToken,
469 length_from=lambda pkt: pkt.parent.auth_len,
470 ),
471 lambda pkt: pkt.auth_type == 0x10
472 and pkt.parent
473 and (
474 # Other
475 not pkt.parent
476 or pkt.parent.ptype not in [11, 12, 13, 14, 15, 16]
477 ),
478 ),
479 # NTLM
480 (
481 PacketLenField(
482 "auth_value",
483 NTLM_Header(),
484 NTLM_Header,
485 length_from=lambda pkt: pkt.parent.auth_len,
486 ),
487 lambda pkt: pkt.auth_type in [0x0A, 0xFF] and pkt.parent and
488 # Bind/Alter
489 pkt.parent.ptype in [11, 12, 13, 14, 15, 16],
490 ),
491 (
492 PacketLenField(
493 "auth_value",
494 NTLMSSP_MESSAGE_SIGNATURE(),
495 NTLMSSP_MESSAGE_SIGNATURE,
496 length_from=lambda pkt: pkt.parent.auth_len,
497 ),
498 lambda pkt: pkt.auth_type in [0x0A, 0xFF]
499 and pkt.parent
500 and (
501 # Other
502 not pkt.parent
503 or pkt.parent.ptype not in [11, 12, 13, 14, 15, 16]
504 ),
505 ),
506 # NetLogon
507 (
508 PacketLenField(
509 "auth_value",
510 NL_AUTH_MESSAGE(),
511 NL_AUTH_MESSAGE,
512 length_from=lambda pkt: pkt.parent.auth_len,
513 ),
514 lambda pkt: pkt.auth_type == 0x44 and pkt.parent and
515 # Bind/Alter
516 pkt.parent.ptype in [11, 12, 13, 14, 15],
517 ),
518 (
519 PacketLenField(
520 "auth_value",
521 NL_AUTH_SIGNATURE(),
522 NL_AUTH_SIGNATURE,
523 length_from=lambda pkt: pkt.parent.auth_len,
524 ),
525 lambda pkt: pkt.auth_type == 0x44
526 and (
527 # Other
528 not pkt.parent
529 or pkt.parent.ptype not in [11, 12, 13, 14, 15]
530 ),
531 ),
532 ],
533 PacketLenField(
534 "auth_value",
535 None,
536 conf.raw_layer,
537 length_from=lambda pkt: pkt.parent and pkt.parent.auth_len or 0,
538 ),
539 ),
540 ]
541
542 def is_protected(self):
543 if not self.auth_value:
544 return False
545 if self.parent and self.parent.ptype in [11, 12, 13, 14, 15, 16]:
546 return False
547 return True
548
549 def is_ssp(self):
550 if not self.auth_value:
551 return False
552 if self.parent and self.parent.ptype not in [11, 12, 13, 14, 15, 16]:
553 return False
554 return True
555
556 def default_payload_class(self, pkt):
557 return conf.padding_layer
558
559
560# [MS-RPCE] sect 2.2.2.13 - Verification Trailer
561_SECTRAILER_MAGIC = b"\x8a\xe3\x13\x71\x02\xf4\x36\x71"
562
563
564class DceRpcSecVTCommand(Packet):
565 name = "Verification trailer command"
566 fields_desc = [
567 BitField("SEC_VT_MUST_PROCESS_COMMAND", 0, 1, tot_size=-2),
568 BitField("SEC_VT_COMMAND_END", 0, 1),
569 BitEnumField(
570 "Command",
571 0,
572 -14,
573 {
574 0x0001: "SEC_VT_COMMAND_BITMASK_1",
575 0x0002: "SEC_VT_COMMAND_PCONTEXT",
576 0x0003: "SEC_VT_COMMAND_HEADER2",
577 },
578 end_tot_size=-2,
579 ),
580 LEShortField("Length", None),
581 ]
582
583 def guess_payload_class(self, payload):
584 if self.Command == 0x0001:
585 return DceRpcSecVTBitmask
586 elif self.Command == 0x0002:
587 return DceRpcSecVTPcontext
588 elif self.Command == 0x0003:
589 return DceRpcSecVTHeader2
590 return conf.raw_payload
591
592
593# [MS-RPCE] sect 2.2.2.13.2
594
595
596class DceRpcSecVTBitmask(Packet):
597 name = "rpc_sec_vt_bitmask"
598 fields_desc = [
599 LEIntField("bits", 1),
600 ]
601
602 def default_payload_class(self, pkt):
603 return conf.padding_layer
604
605
606# [MS-RPCE] sect 2.2.2.13.4
607
608
609class DceRpcSecVTPcontext(Packet):
610 name = "rpc_sec_vt_pcontext"
611 fields_desc = [
612 UUIDEnumField(
613 "InterfaceId",
614 None,
615 (
616 DCE_RPC_INTERFACES_NAMES.get,
617 lambda x: DCE_RPC_INTERFACES_NAMES_rev.get(x.lower()),
618 ),
619 uuid_fmt=UUIDField.FORMAT_LE,
620 ),
621 LEIntField("Version", 0),
622 UUIDEnumField(
623 "TransferSyntax",
624 None,
625 DCE_RPC_TRANSFER_SYNTAXES,
626 uuid_fmt=UUIDField.FORMAT_LE,
627 ),
628 LEIntField("TransferVersion", 0),
629 ]
630
631 def default_payload_class(self, pkt):
632 return conf.padding_layer
633
634
635# [MS-RPCE] sect 2.2.2.13.3
636
637
638class DceRpcSecVTHeader2(Packet):
639 name = "rpc_sec_vt_header2"
640 fields_desc = [
641 ByteField("PTYPE", 0),
642 ByteField("Reserved1", 0),
643 LEShortField("Reserved2", 0),
644 LEIntField("drep", 0),
645 LEIntField("call_id", 0),
646 LEShortField("p_cont_id", 0),
647 LEShortField("opnum", 0),
648 ]
649
650 def default_payload_class(self, pkt):
651 return conf.padding_layer
652
653
654class DceRpcSecVT(Packet):
655 name = "Verification trailer"
656 fields_desc = [
657 XStrFixedLenField("rpc_sec_verification_trailer", _SECTRAILER_MAGIC, length=8),
658 PacketListField("commands", [], DceRpcSecVTCommand),
659 ]
660
661
662class _VerifTrailerField(PacketField):
663 def getfield(
664 self,
665 pkt,
666 s,
667 ):
668 if _SECTRAILER_MAGIC in s:
669 # a bit ugly
670 ind = s.index(_SECTRAILER_MAGIC)
671 sectrailer_bytes, remain = bytes(s[:-ind]), bytes(s[-ind:])
672 vt_trailer = self.m2i(pkt, sectrailer_bytes)
673 if not isinstance(vt_trailer.payload, NoPayload):
674 # bad parse
675 return s, None
676 return remain, vt_trailer
677 return s, None
678
679
680# sect 12.6.3
681
682
683_DCE_RPC_5_FLAGS = {
684 0x01: "PFC_FIRST_FRAG",
685 0x02: "PFC_LAST_FRAG",
686 0x04: "PFC_PENDING_CANCEL",
687 0x08: "PFC_RESERVED_1",
688 0x10: "PFC_CONC_MPX",
689 0x20: "PFC_DID_NOT_EXECUTE",
690 0x40: "PFC_MAYBE",
691 0x80: "PFC_OBJECT_UUID",
692}
693
694# [MS-RPCE] sect 2.2.2.3
695
696_DCE_RPC_5_FLAGS_2 = _DCE_RPC_5_FLAGS.copy()
697_DCE_RPC_5_FLAGS_2[0x04] = "PFC_SUPPORT_HEADER_SIGN"
698
699
700_DCE_RPC_ERROR_CODES = {
701 # Appendix N
702 0x1C010001: "nca_s_comm_failure",
703 0x1C010002: "nca_s_op_rng_error",
704 0x1C010003: "nca_s_unk_if",
705 0x1C010006: "nca_s_wrong_boot_time",
706 0x1C010009: "nca_s_you_crashed",
707 0x1C01000B: "nca_s_proto_error",
708 0x1C010013: "nca_s_out_args_too_big",
709 0x1C010014: "nca_s_server_too_busy",
710 0x1C010015: "nca_s_fault_string_too_long",
711 0x1C010017: "nca_s_unsupported_type",
712 0x1C000001: "nca_s_fault_int_div_by_zero",
713 0x1C000002: "nca_s_fault_addr_error",
714 0x1C000003: "nca_s_fault_fp_div_zero",
715 0x1C000004: "nca_s_fault_fp_underflow",
716 0x1C000005: "nca_s_fault_fp_overflow",
717 0x1C000006: "nca_s_fault_invalid_tag",
718 0x1C000007: "nca_s_fault_invalid_bound",
719 0x1C000008: "nca_s_rpc_version_mismatch",
720 0x1C000009: "nca_s_unspec_reject",
721 0x1C00000A: "nca_s_bad_actid",
722 0x1C00000B: "nca_s_who_are_you_failed",
723 0x1C00000C: "nca_s_manager_not_entered",
724 0x1C00000D: "nca_s_fault_cancel",
725 0x1C00000E: "nca_s_fault_ill_inst",
726 0x1C00000F: "nca_s_fault_fp_error",
727 0x1C000010: "nca_s_fault_int_overflow",
728 0x1C000012: "nca_s_fault_unspec",
729 0x1C000013: "nca_s_fault_remote_comm_failure",
730 0x1C000014: "nca_s_fault_pipe_empty",
731 0x1C000015: "nca_s_fault_pipe_closed",
732 0x1C000016: "nca_s_fault_pipe_order",
733 0x1C000017: "nca_s_fault_pipe_discipline",
734 0x1C000018: "nca_s_fault_pipe_comm_error",
735 0x1C000019: "nca_s_fault_pipe_memory",
736 0x1C00001A: "nca_s_fault_context_mismatch",
737 0x1C00001B: "nca_s_fault_remote_no_memory",
738 0x1C00001C: "nca_s_invalid_pres_context_id",
739 0x1C00001D: "nca_s_unsupported_authn_level",
740 0x1C00001F: "nca_s_invalid_checksum",
741 0x1C000020: "nca_s_invalid_crc",
742 0x1C000021: "nca_s_fault_user_defined",
743 0x1C000022: "nca_s_fault_tx_open_failed",
744 0x1C000023: "nca_s_fault_codeset_conv_error",
745 0x1C000024: "nca_s_fault_object_not_found",
746 0x1C000025: "nca_s_fault_no_client_stub",
747 # [MS-ERREF]
748 0x000006D3: "RPC_S_UNKNOWN_AUTHN_SERVICE",
749 0x000006F7: "RPC_X_BAD_STUB_DATA",
750 # [MS-RPCE]
751 0x000006D8: "EPT_S_CANT_PERFORM_OP",
752}
753
754_DCE_RPC_REJECTION_REASONS = {
755 0: "REASON_NOT_SPECIFIED",
756 1: "TEMPORARY_CONGESTION",
757 2: "LOCAL_LIMIT_EXCEEDED",
758 3: "CALLED_PADDR_UNKNOWN",
759 4: "PROTOCOL_VERSION_NOT_SUPPORTED",
760 5: "DEFAULT_CONTEXT_NOT_SUPPORTED",
761 6: "USER_DATA_NOT_READABLE",
762 7: "NO_PSAP_AVAILABLE",
763 8: "AUTHENTICATION_TYPE_NOT_RECOGNIZED",
764 9: "INVALID_CHECKSUM",
765}
766
767
768class DceRpc5(DceRpc):
769 """
770 DCE/RPC v5 'connection-oriented' packet
771 """
772
773 name = "DCE/RPC v5"
774 fields_desc = (
775 [
776 ByteEnumField(
777 "rpc_vers", 5, {4: "4 (connection-less)", 5: "5 (connection-oriented)"}
778 ),
779 ByteField("rpc_vers_minor", 0),
780 ByteEnumField("ptype", 0, DCE_RPC_TYPE),
781 MultipleTypeField(
782 # [MS-RPCE] sect 2.2.2.3
783 [
784 (
785 FlagsField("pfc_flags", 0x3, 8, _DCE_RPC_5_FLAGS_2),
786 lambda pkt: pkt.ptype in [11, 12, 13, 14, 15, 16],
787 )
788 ],
789 FlagsField("pfc_flags", 0x3, 8, _DCE_RPC_5_FLAGS),
790 ),
791 ]
792 + _drep
793 + [
794 ByteField("reserved2", 0),
795 _EField(ShortField("frag_len", None)),
796 _EField(
797 FieldLenField(
798 "auth_len",
799 None,
800 fmt="H",
801 length_of="auth_verifier",
802 adjust=lambda pkt, x: 0 if not x else (x - 8),
803 )
804 ),
805 _EField(IntField("call_id", None)),
806 # Now let's proceed with trailer fields, i.e. at the end of the PACKET
807 # (below all payloads, etc.). Have a look at Figure 3 in sect 2.2.2.13
808 # of [MS-RPCE] but note the following:
809 # - auth_verifier includes sec_trailer + the authentication token
810 # - auth_padding is the authentication padding
811 # - vt_trailer is the verification trailer
812 ConditionalField(
813 TrailerField(
814 PacketLenField(
815 "auth_verifier",
816 None,
817 CommonAuthVerifier,
818 length_from=lambda pkt: pkt.auth_len + 8,
819 )
820 ),
821 lambda pkt: pkt.auth_len != 0,
822 ),
823 ConditionalField(
824 TrailerField(
825 StrLenField(
826 "auth_padding",
827 None,
828 length_from=lambda pkt: pkt.auth_verifier.auth_pad_length,
829 )
830 ),
831 lambda pkt: pkt.auth_len != 0,
832 ),
833 TrailerField(
834 _VerifTrailerField("vt_trailer", None, DceRpcSecVT),
835 ),
836 ]
837 )
838
839 def do_dissect(self, s):
840 # Overload do_dissect to only include the current layer in dissection.
841 # This allows to support TrailerFields, even in the case where multiple DceRpc5
842 # packets are concatenated
843 frag_len = self.get_field("frag_len").getfield(self, s[8:10])[1]
844 s, remain = s[:frag_len], s[frag_len:]
845 return super(DceRpc5, self).do_dissect(s) + remain
846
847 def extract_padding(self, s):
848 # Now, take any data that doesn't fit in the current fragment and make it
849 # padding. The caller is responsible for looking for eventual padding and
850 # creating the next fragment, etc.
851 pay_len = self.frag_len - len(self.original) + len(s)
852 return s[:pay_len], s[pay_len:]
853
854 def post_build(self, pkt, pay):
855 if (
856 self.auth_verifier
857 and self.auth_padding is None
858 and self.auth_verifier.auth_pad_length is None
859 ):
860 # Compute auth_len and add padding
861 auth_len = self.get_field("auth_len").getfield(self, pkt[10:12])[1] + 8
862 auth_verifier, pay = pay[-auth_len:], pay[:-auth_len]
863 pdu_len = len(pay)
864 if self.payload:
865 pdu_len -= len(self.payload.self_build())
866 padlen = (-pdu_len) % _COMMON_AUTH_PAD
867 auth_verifier = (
868 auth_verifier[:2] + struct.pack("B", padlen) + auth_verifier[3:]
869 )
870 pay = pay + (padlen * b"\x00") + auth_verifier
871 if self.frag_len is None:
872 # Compute frag_len
873 length = len(pkt) + len(pay)
874 pkt = (
875 pkt[:8]
876 + self.get_field("frag_len").addfield(self, b"", length)
877 + pkt[10:]
878 )
879 return pkt + pay
880
881 def answers(self, pkt):
882 return isinstance(pkt, DceRpc5) and pkt[DceRpc5].call_id == self.call_id
883
884 @classmethod
885 def tcp_reassemble(cls, data, _, session):
886 if data[0:1] != b"\x05":
887 return
888 endian = struct.unpack("!B", data[4:5])[0] >> 4
889 if endian not in [0, 1]:
890 return
891 length = struct.unpack(("<" if endian else ">") + "H", data[8:10])[0]
892 if len(data) >= length:
893 if conf.dcerpc_session_enable:
894 # If DCE/RPC sessions are enabled, use them !
895 if "dcerpcsess" not in session:
896 session["dcerpcsess"] = dcerpcsess = DceRpcSession()
897 else:
898 dcerpcsess = session["dcerpcsess"]
899 return dcerpcsess.process(DceRpc5(data))
900 return DceRpc5(data)
901
902
903# sec 12.6.3.1
904
905
906class DceRpc5AbstractSyntax(EPacket):
907 name = "Presentation Syntax (p_syntax_id_t)"
908 fields_desc = [
909 _EField(
910 UUIDEnumField(
911 "if_uuid",
912 None,
913 (
914 # Those are dynamic
915 DCE_RPC_INTERFACES_NAMES.get,
916 lambda x: DCE_RPC_INTERFACES_NAMES_rev.get(x.lower()),
917 ),
918 )
919 ),
920 _EField(IntField("if_version", 3)),
921 ]
922
923
924class DceRpc5TransferSyntax(EPacket):
925 name = "Presentation Transfer Syntax (p_syntax_id_t)"
926 fields_desc = [
927 _EField(
928 UUIDEnumField(
929 "if_uuid",
930 None,
931 DCE_RPC_TRANSFER_SYNTAXES,
932 )
933 ),
934 _EField(IntField("if_version", 3)),
935 ]
936
937
938class DceRpc5Context(EPacket):
939 name = "Presentation Context (p_cont_elem_t)"
940 fields_desc = [
941 _EField(ShortField("cont_id", 0)),
942 FieldLenField("n_transfer_syn", None, count_of="transfer_syntaxes", fmt="B"),
943 ByteField("reserved", 0),
944 EPacketField("abstract_syntax", None, DceRpc5AbstractSyntax),
945 EPacketListField(
946 "transfer_syntaxes",
947 None,
948 DceRpc5TransferSyntax,
949 count_from=lambda pkt: pkt.n_transfer_syn,
950 endianness_from=_dce_rpc_endianess,
951 ),
952 ]
953
954
955class DceRpc5Result(EPacket):
956 name = "Context negotiation Result"
957 fields_desc = [
958 _EField(
959 ShortEnumField(
960 "result", 0, ["acceptance", "user_rejection", "provider_rejection"]
961 )
962 ),
963 _EField(
964 ShortEnumField(
965 "reason",
966 0,
967 _DCE_RPC_REJECTION_REASONS,
968 )
969 ),
970 EPacketField("transfer_syntax", None, DceRpc5TransferSyntax),
971 ]
972
973
974class DceRpc5PortAny(EPacket):
975 name = "Port Any (port_any_t)"
976 fields_desc = [
977 _EField(FieldLenField("length", None, length_of="port_spec", fmt="H")),
978 _EField(StrLenField("port_spec", b"", length_from=lambda pkt: pkt.length)),
979 ]
980
981
982# sec 12.6.4.3
983
984
985class DceRpc5Bind(_DceRpcPayload):
986 name = "DCE/RPC v5 - Bind"
987 fields_desc = [
988 _EField(ShortField("max_xmit_frag", 5840)),
989 _EField(ShortField("max_recv_frag", 8192)),
990 _EField(IntField("assoc_group_id", 0)),
991 # p_cont_list_t
992 _EField(
993 FieldLenField("n_context_elem", None, count_of="context_elem", fmt="B")
994 ),
995 StrFixedLenField("reserved", 0, length=3),
996 EPacketListField(
997 "context_elem",
998 [],
999 DceRpc5Context,
1000 endianness_from=_dce_rpc_endianess,
1001 count_from=lambda pkt: pkt.n_context_elem,
1002 ),
1003 ]
1004
1005
1006bind_layers(DceRpc5, DceRpc5Bind, ptype=11)
1007
1008# sec 12.6.4.4
1009
1010
1011class DceRpc5BindAck(_DceRpcPayload):
1012 name = "DCE/RPC v5 - Bind Ack"
1013 fields_desc = [
1014 _EField(ShortField("max_xmit_frag", 5840)),
1015 _EField(ShortField("max_recv_frag", 8192)),
1016 _EField(IntField("assoc_group_id", 0)),
1017 PadField(
1018 EPacketField("sec_addr", None, DceRpc5PortAny),
1019 align=4,
1020 ),
1021 # p_result_list_t
1022 _EField(FieldLenField("n_results", None, count_of="results", fmt="B")),
1023 StrFixedLenField("reserved", 0, length=3),
1024 EPacketListField(
1025 "results",
1026 [],
1027 DceRpc5Result,
1028 endianness_from=_dce_rpc_endianess,
1029 count_from=lambda pkt: pkt.n_results,
1030 ),
1031 ]
1032
1033
1034bind_layers(DceRpc5, DceRpc5BindAck, ptype=12)
1035
1036# sec 12.6.4.5
1037
1038
1039class DceRpc5Version(EPacket):
1040 name = "version_t"
1041 fields_desc = [
1042 ByteField("major", 0),
1043 ByteField("minor", 0),
1044 ]
1045
1046
1047class DceRpc5BindNak(_DceRpcPayload):
1048 name = "DCE/RPC v5 - Bind Nak"
1049 fields_desc = [
1050 _EField(
1051 ShortEnumField("provider_reject_reason", 0, _DCE_RPC_REJECTION_REASONS)
1052 ),
1053 # p_rt_versions_supported_t
1054 _EField(FieldLenField("n_protocols", None, count_of="protocols", fmt="B")),
1055 EPacketListField(
1056 "protocols",
1057 [],
1058 DceRpc5Version,
1059 count_from=lambda pkt: pkt.n_protocols,
1060 endianness_from=_dce_rpc_endianess,
1061 ),
1062 # [MS-RPCE] sect 2.2.2.9
1063 ConditionalField(
1064 ReversePadField(
1065 _EField(
1066 UUIDEnumField(
1067 "signature",
1068 None,
1069 {
1070 UUID(
1071 "90740320-fad0-11d3-82d7-009027b130ab"
1072 ): "Extended Error",
1073 },
1074 )
1075 ),
1076 align=8,
1077 ),
1078 lambda pkt: pkt.fields.get("signature", None)
1079 or (
1080 pkt.underlayer
1081 and pkt.underlayer.frag_len >= 24 + pkt.n_protocols * 2 + 16
1082 ),
1083 ),
1084 ]
1085
1086
1087bind_layers(DceRpc5, DceRpc5BindNak, ptype=13)
1088
1089
1090# sec 12.6.4.1
1091
1092
1093class DceRpc5AlterContext(_DceRpcPayload):
1094 name = "DCE/RPC v5 - AlterContext"
1095 fields_desc = DceRpc5Bind.fields_desc
1096
1097
1098bind_layers(DceRpc5, DceRpc5AlterContext, ptype=14)
1099
1100
1101# sec 12.6.4.2
1102
1103
1104class DceRpc5AlterContextResp(_DceRpcPayload):
1105 name = "DCE/RPC v5 - AlterContextResp"
1106 fields_desc = DceRpc5BindAck.fields_desc
1107
1108
1109bind_layers(DceRpc5, DceRpc5AlterContextResp, ptype=15)
1110
1111# [MS-RPCE] sect 2.2.2.10 - rpc_auth_3
1112
1113
1114class DceRpc5Auth3(Packet):
1115 name = "DCE/RPC v5 - Auth3"
1116 fields_desc = [StrFixedLenField("pad", b"", length=4)]
1117
1118
1119bind_layers(DceRpc5, DceRpc5Auth3, ptype=16)
1120
1121# sec 12.6.4.7
1122
1123
1124class DceRpc5Fault(_DceRpcPayload):
1125 name = "DCE/RPC v5 - Fault"
1126 fields_desc = [
1127 _EField(IntField("alloc_hint", 0)),
1128 _EField(ShortField("cont_id", 0)),
1129 ByteField("cancel_count", 0),
1130 FlagsField("reserved", 0, -8, {0x1: "RPC extended error"}),
1131 _EField(LEIntEnumField("status", 0, _DCE_RPC_ERROR_CODES)),
1132 IntField("reserved2", 0),
1133 ]
1134
1135
1136bind_layers(DceRpc5, DceRpc5Fault, ptype=3)
1137
1138
1139# sec 12.6.4.9
1140
1141
1142class DceRpc5Request(_DceRpcPayload):
1143 name = "DCE/RPC v5 - Request"
1144 fields_desc = [
1145 _EField(IntField("alloc_hint", 0)),
1146 _EField(ShortField("cont_id", 0)),
1147 _EField(ShortField("opnum", 0)),
1148 ConditionalField(
1149 PadField(
1150 _EField(UUIDField("object", None)),
1151 align=8,
1152 ),
1153 lambda pkt: pkt.underlayer and pkt.underlayer.pfc_flags.PFC_OBJECT_UUID,
1154 ),
1155 ]
1156
1157
1158bind_layers(DceRpc5, DceRpc5Request, ptype=0)
1159
1160# sec 12.6.4.10
1161
1162
1163class DceRpc5Response(_DceRpcPayload):
1164 name = "DCE/RPC v5 - Response"
1165 fields_desc = [
1166 _EField(IntField("alloc_hint", 0)),
1167 _EField(ShortField("cont_id", 0)),
1168 ByteField("cancel_count", 0),
1169 ByteField("reserved", 0),
1170 ]
1171
1172
1173bind_layers(DceRpc5, DceRpc5Response, ptype=2)
1174
1175# --- API
1176
1177DceRpcOp = collections.namedtuple("DceRpcOp", ["request", "response"])
1178DCE_RPC_INTERFACES = {}
1179
1180
1181class DceRpcInterface:
1182 def __init__(self, name, uuid, version_tuple, if_version, opnums):
1183 self.name = name
1184 self.uuid = uuid
1185 self.major_version, self.minor_version = version_tuple
1186 self.if_version = if_version
1187 self.opnums = opnums
1188
1189 def __repr__(self):
1190 return "<DCE/RPC Interface %s v%s.%s>" % (
1191 self.name,
1192 self.major_version,
1193 self.minor_version,
1194 )
1195
1196
1197def register_dcerpc_interface(name, uuid, version, opnums):
1198 """
1199 Register a DCE/RPC interface
1200 """
1201 version_tuple = tuple(map(int, version.split(".")))
1202 assert len(version_tuple) == 2, "Version should be in format 'X.X' !"
1203 if_version = (version_tuple[1] << 16) + version_tuple[0]
1204 if (uuid, if_version) in DCE_RPC_INTERFACES:
1205 # Interface is already registered.
1206 interface = DCE_RPC_INTERFACES[(uuid, if_version)]
1207 if interface.name == name:
1208 if interface.if_version == if_version and set(opnums) - set(
1209 interface.opnums
1210 ):
1211 # Interface is an extension of a previous interface
1212 interface.opnums.update(opnums)
1213 return
1214 elif interface.if_version != if_version:
1215 # Interface has a different version
1216 pass
1217 else:
1218 log_runtime.warning(
1219 "This interface is already registered: %s. Skip" % interface
1220 )
1221 return
1222 else:
1223 raise ValueError(
1224 "An interface with the same UUID is already registered: %s" % interface
1225 )
1226 DCE_RPC_INTERFACES_NAMES[uuid] = name
1227 DCE_RPC_INTERFACES_NAMES_rev[name.lower()] = uuid
1228 DCE_RPC_INTERFACES[(uuid, if_version)] = DceRpcInterface(
1229 name,
1230 uuid,
1231 version_tuple,
1232 if_version,
1233 opnums,
1234 )
1235 # bind for build
1236 for opnum, operations in opnums.items():
1237 bind_top_down(DceRpc5Request, operations.request, opnum=opnum)
1238
1239
1240def find_dcerpc_interface(name):
1241 """
1242 Find an interface object through the name in the IDL
1243 """
1244 try:
1245 return next(x for x in DCE_RPC_INTERFACES.values() if x.name == name)
1246 except StopIteration:
1247 raise AttributeError("Unknown interface !")
1248
1249
1250COM_INTERFACES = {}
1251
1252
1253class ComInterface:
1254 def __init__(self, name, uuid, opnums):
1255 self.name = name
1256 self.uuid = uuid
1257 self.opnums = opnums
1258
1259 def __repr__(self):
1260 return "<COM Interface %s>" % (self.name,)
1261
1262
1263def register_com_interface(name, uuid, opnums):
1264 """
1265 Register a COM interface
1266 """
1267 COM_INTERFACES[uuid] = ComInterface(
1268 name,
1269 uuid,
1270 opnums,
1271 )
1272
1273
1274# --- NDR fields - [C706] chap 14
1275
1276
1277def _set_ctx_on(f, obj):
1278 if isinstance(f, _NDRPacket):
1279 f.ndr64 = obj.ndr64
1280 f.ndrendian = obj.ndrendian
1281 if isinstance(f, list):
1282 for x in f:
1283 if isinstance(x, _NDRPacket):
1284 x.ndr64 = obj.ndr64
1285 x.ndrendian = obj.ndrendian
1286
1287
1288def _e(ndrendian):
1289 return {"big": ">", "little": "<"}[ndrendian]
1290
1291
1292class _NDRPacket(Packet):
1293 __slots__ = ["ndr64", "ndrendian", "deferred_pointers", "request_packet"]
1294
1295 def __init__(self, *args, **kwargs):
1296 self.ndr64 = kwargs.pop("ndr64", False)
1297 self.ndrendian = kwargs.pop("ndrendian", "little")
1298 # request_packet is used in the session, so that a response packet
1299 # can resolve union arms if the case parameter is in the request.
1300 self.request_packet = kwargs.pop("request_packet", None)
1301 self.deferred_pointers = []
1302 super(_NDRPacket, self).__init__(*args, **kwargs)
1303
1304 def do_dissect(self, s):
1305 _up = self.parent or self.underlayer
1306 if _up and isinstance(_up, _NDRPacket):
1307 self.ndr64 = _up.ndr64
1308 self.ndrendian = _up.ndrendian
1309 else:
1310 # See comment above NDRConstructedType
1311 return NDRConstructedType([]).read_deferred_pointers(
1312 self, super(_NDRPacket, self).do_dissect(s)
1313 )
1314 return super(_NDRPacket, self).do_dissect(s)
1315
1316 def post_dissect(self, s):
1317 if self.deferred_pointers:
1318 # Can't trust the cache if there were deferred pointers
1319 self.raw_packet_cache = None
1320 return s
1321
1322 def do_build(self):
1323 _up = self.parent or self.underlayer
1324 for f in self.fields.values():
1325 _set_ctx_on(f, self)
1326 if not _up or not isinstance(_up, _NDRPacket):
1327 # See comment above NDRConstructedType
1328 return NDRConstructedType([]).add_deferred_pointers(
1329 self, super(_NDRPacket, self).do_build()
1330 )
1331 return super(_NDRPacket, self).do_build()
1332
1333 def default_payload_class(self, pkt):
1334 return conf.padding_layer
1335
1336 def clone_with(self, *args, **kwargs):
1337 pkt = super(_NDRPacket, self).clone_with(*args, **kwargs)
1338 # We need to copy deferred_pointers to not break pointer deferral
1339 # on build.
1340 pkt.deferred_pointers = self.deferred_pointers
1341 pkt.ndr64 = self.ndr64
1342 pkt.ndrendian = self.ndrendian
1343 return pkt
1344
1345 def copy(self):
1346 pkt = super(_NDRPacket, self).copy()
1347 pkt.deferred_pointers = self.deferred_pointers
1348 pkt.ndr64 = self.ndr64
1349 pkt.ndrendian = self.ndrendian
1350 return pkt
1351
1352 def show2(self, dump=False, indent=3, lvl="", label_lvl=""):
1353 return self.__class__(
1354 bytes(self), ndr64=self.ndr64, ndrendian=self.ndrendian
1355 ).show(dump, indent, lvl, label_lvl)
1356
1357 def getfield_and_val(self, attr):
1358 try:
1359 return Packet.getfield_and_val(self, attr)
1360 except ValueError:
1361 if self.request_packet:
1362 # Try to resolve the field from the request on failure
1363 try:
1364 return self.request_packet.getfield_and_val(attr)
1365 except AttributeError:
1366 pass
1367 raise
1368
1369 def valueof(self, request):
1370 """
1371 Util to get the value of a NDRField, ignoring arrays, pointers, etc.
1372 """
1373 val = self
1374 for ndr_field in request.split("."):
1375 fld, fval = val.getfield_and_val(ndr_field)
1376 val = fld.valueof(val, fval)
1377 return val
1378
1379
1380class _NDRAlign:
1381 def padlen(self, flen, pkt):
1382 return -flen % self._align[pkt.ndr64]
1383
1384 def original_length(self, pkt):
1385 # Find the length of the NDR frag to be able to pad properly
1386 while pkt:
1387 par = pkt.parent or pkt.underlayer
1388 if par and isinstance(par, _NDRPacket):
1389 pkt = par
1390 else:
1391 break
1392 return len(pkt.original)
1393
1394
1395class NDRAlign(_NDRAlign, ReversePadField):
1396 """
1397 ReversePadField modified to fit NDR.
1398
1399 - If no align size is specified, use the one from the inner field
1400 - Size is calculated from the beginning of the NDR stream
1401 """
1402
1403 def __init__(self, fld, align, padwith=None):
1404 super(NDRAlign, self).__init__(fld, align=align, padwith=padwith)
1405
1406
1407class _VirtualField(Field):
1408 # Hold a value but doesn't show up when building/dissecting
1409 def addfield(self, pkt, s, x):
1410 return s
1411
1412 def getfield(self, pkt, s):
1413 return s, None
1414
1415
1416class _NDRPacketMetaclass(Packet_metaclass):
1417 def __new__(cls, name, bases, dct):
1418 newcls = super(_NDRPacketMetaclass, cls).__new__(cls, name, bases, dct)
1419 conformants = dct.get("DEPORTED_CONFORMANTS", [])
1420 if conformants:
1421 amount = len(conformants)
1422 if amount == 1:
1423 newcls.fields_desc.insert(
1424 0,
1425 _VirtualField("max_count", None),
1426 )
1427 else:
1428 newcls.fields_desc.insert(
1429 0,
1430 FieldListField(
1431 "max_counts",
1432 [],
1433 _VirtualField("", 0),
1434 count_from=lambda _: amount,
1435 ),
1436 )
1437 return newcls # type: ignore
1438
1439
1440class NDRPacket(_NDRPacket, metaclass=_NDRPacketMetaclass):
1441 """
1442 A NDR Packet. Handles pointer size & endianness
1443 """
1444
1445 __slots__ = ["_align"]
1446
1447 # NDR64 pad structures
1448 # [MS-RPCE] 2.2.5.3.4.1
1449 ALIGNMENT = (1, 1)
1450 # [C706] sect 14.3.7 - Conformants max_count can be added to the beginning
1451 DEPORTED_CONFORMANTS = []
1452
1453
1454# Primitive types
1455
1456
1457class _NDRValueOf:
1458 def valueof(self, pkt, x):
1459 return x
1460
1461
1462class _NDRLenField(_NDRValueOf, Field):
1463 """
1464 Field similar to FieldLenField that takes size_of and adjust as arguments,
1465 and take the value of a size on build.
1466 """
1467
1468 __slots__ = ["size_of", "adjust"]
1469
1470 def __init__(self, *args, **kwargs):
1471 self.size_of = kwargs.pop("size_of", None)
1472 self.adjust = kwargs.pop("adjust", lambda _, x: x)
1473 super(_NDRLenField, self).__init__(*args, **kwargs)
1474
1475 def i2m(self, pkt, x):
1476 if x is None and pkt is not None and self.size_of is not None:
1477 fld, fval = pkt.getfield_and_val(self.size_of)
1478 f = fld.i2len(pkt, fval)
1479 x = self.adjust(pkt, f)
1480 elif x is None:
1481 x = 0
1482 return x
1483
1484
1485class NDRByteField(_NDRLenField, ByteField):
1486 pass
1487
1488
1489class NDRSignedByteField(_NDRLenField, SignedByteField):
1490 pass
1491
1492
1493class _NDRField(_NDRLenField):
1494 FMT = ""
1495 ALIGN = (0, 0)
1496
1497 def getfield(self, pkt, s):
1498 return NDRAlign(
1499 Field("", 0, fmt=_e(pkt.ndrendian) + self.FMT), align=self.ALIGN
1500 ).getfield(pkt, s)
1501
1502 def addfield(self, pkt, s, val):
1503 return NDRAlign(
1504 Field("", 0, fmt=_e(pkt.ndrendian) + self.FMT), align=self.ALIGN
1505 ).addfield(pkt, s, self.i2m(pkt, val))
1506
1507
1508class NDRShortField(_NDRField):
1509 FMT = "H"
1510 ALIGN = (2, 2)
1511
1512
1513class NDRSignedShortField(_NDRField):
1514 FMT = "h"
1515 ALIGN = (2, 2)
1516
1517
1518class NDRIntField(_NDRField):
1519 FMT = "I"
1520 ALIGN = (4, 4)
1521
1522
1523class NDRSignedIntField(_NDRField):
1524 FMT = "i"
1525 ALIGN = (4, 4)
1526
1527
1528class NDRLongField(_NDRField):
1529 FMT = "Q"
1530 ALIGN = (8, 8)
1531
1532
1533class NDRSignedLongField(_NDRField):
1534 FMT = "q"
1535 ALIGN = (8, 8)
1536
1537
1538class NDRIEEEFloatField(_NDRField):
1539 FMT = "f"
1540 ALIGN = (4, 4)
1541
1542
1543class NDRIEEEDoubleField(_NDRField):
1544 FMT = "d"
1545 ALIGN = (8, 8)
1546
1547
1548# Enum types
1549
1550
1551class _NDREnumField(_NDRValueOf, EnumField):
1552 # [MS-RPCE] sect 2.2.5.2 - Enums are 4 octets in NDR64
1553 FMTS = ["H", "I"]
1554
1555 def getfield(self, pkt, s):
1556 fmt = _e(pkt.ndrendian) + self.FMTS[pkt.ndr64]
1557 return NDRAlign(Field("", 0, fmt=fmt), align=(2, 4)).getfield(pkt, s)
1558
1559 def addfield(self, pkt, s, val):
1560 fmt = _e(pkt.ndrendian) + self.FMTS[pkt.ndr64]
1561 return NDRAlign(Field("", 0, fmt=fmt), align=(2, 4)).addfield(
1562 pkt, s, self.i2m(pkt, val)
1563 )
1564
1565
1566class NDRInt3264EnumField(NDRAlign):
1567 def __init__(self, *args, **kwargs):
1568 super(NDRInt3264EnumField, self).__init__(
1569 _NDREnumField(*args, **kwargs), align=(2, 4)
1570 )
1571
1572
1573class NDRIntEnumField(_NDRValueOf, NDRAlign):
1574 # v1_enum are always 4-octets, even in NDR32
1575 def __init__(self, *args, **kwargs):
1576 super(NDRIntEnumField, self).__init__(
1577 LEIntEnumField(*args, **kwargs), align=(4, 4)
1578 )
1579
1580
1581# Special types
1582
1583
1584class NDRInt3264Field(_NDRLenField):
1585 FMTS = ["I", "Q"]
1586
1587 def getfield(self, pkt, s):
1588 fmt = _e(pkt.ndrendian) + self.FMTS[pkt.ndr64]
1589 return NDRAlign(Field("", 0, fmt=fmt), align=(4, 8)).getfield(pkt, s)
1590
1591 def addfield(self, pkt, s, val):
1592 fmt = _e(pkt.ndrendian) + self.FMTS[pkt.ndr64]
1593 return NDRAlign(Field("", 0, fmt=fmt), align=(4, 8)).addfield(
1594 pkt, s, self.i2m(pkt, val)
1595 )
1596
1597
1598class NDRSignedInt3264Field(NDRInt3264Field):
1599 FMTS = ["i", "q"]
1600
1601
1602# Pointer types
1603
1604
1605class NDRPointer(_NDRPacket):
1606 fields_desc = [
1607 MultipleTypeField(
1608 [(XLELongField("referent_id", 1), lambda pkt: pkt and pkt.ndr64)],
1609 XLEIntField("referent_id", 1),
1610 ),
1611 PacketField("value", None, conf.raw_layer),
1612 ]
1613
1614
1615class NDRFullPointerField(_FieldContainer):
1616 """
1617 A NDR Full/Unique pointer field encapsulation.
1618
1619 :param deferred: This pointer is deferred. This means that it's representation
1620 will not appear after the pointer.
1621 See [C706] 14.3.12.3 - Algorithm for Deferral of Referents
1622 """
1623
1624 EMBEDDED = False
1625
1626 def __init__(self, fld, deferred=False, fmt="I"):
1627 self.fld = fld
1628 self.default = None
1629 self.deferred = deferred
1630
1631 def getfield(self, pkt, s):
1632 fmt = _e(pkt.ndrendian) + ["I", "Q"][pkt.ndr64]
1633 remain, referent_id = NDRAlign(Field("", 0, fmt=fmt), align=(4, 8)).getfield(
1634 pkt, s
1635 )
1636 if not self.EMBEDDED and referent_id == 0:
1637 return remain, None
1638 if self.deferred:
1639 # deferred
1640 ptr = NDRPointer(
1641 ndr64=pkt.ndr64, ndrendian=pkt.ndrendian, referent_id=referent_id
1642 )
1643 pkt.deferred_pointers.append((ptr, partial(self.fld.getfield, pkt)))
1644 return remain, ptr
1645 remain, val = self.fld.getfield(pkt, remain)
1646 return remain, NDRPointer(
1647 ndr64=pkt.ndr64, ndrendian=pkt.ndrendian, referent_id=referent_id, value=val
1648 )
1649
1650 def addfield(self, pkt, s, val):
1651 if val is not None and not isinstance(val, NDRPointer):
1652 raise ValueError(
1653 "Expected NDRPointer in %s. You are using it wrong!" % self.name
1654 )
1655 fmt = _e(pkt.ndrendian) + ["I", "Q"][pkt.ndr64]
1656 fld = NDRAlign(Field("", 0, fmt=fmt), align=(4, 8))
1657 if not self.EMBEDDED and val is None:
1658 return fld.addfield(pkt, s, 0)
1659 else:
1660 _set_ctx_on(val.value, pkt)
1661 s = fld.addfield(pkt, s, val.referent_id)
1662 if self.deferred:
1663 # deferred
1664 pkt.deferred_pointers.append(
1665 ((lambda s: self.fld.addfield(pkt, s, val.value)), val)
1666 )
1667 return s
1668 return self.fld.addfield(pkt, s, val.value)
1669
1670 def any2i(self, pkt, x):
1671 # User-friendly helper
1672 if x is not None and not isinstance(x, NDRPointer):
1673 return NDRPointer(
1674 referent_id=0x20000,
1675 value=self.fld.any2i(pkt, x),
1676 )
1677 return x
1678
1679 # Can't use i2repr = Field.i2repr and so on on PY2 :/
1680 def i2repr(self, pkt, val):
1681 return repr(val)
1682
1683 def i2h(self, pkt, x):
1684 return x
1685
1686 def h2i(self, pkt, x):
1687 return x
1688
1689 # def i2count(self, pkt, x):
1690 # return 1
1691
1692 def i2len(self, pkt, x):
1693 if x is None:
1694 return 0
1695 return self.fld.i2len(pkt, x.value)
1696
1697 def valueof(self, pkt, x):
1698 if x is None:
1699 return x
1700 return self.fld.valueof(pkt, x.value)
1701
1702
1703class NDRRefEmbPointerField(NDRFullPointerField):
1704 """
1705 A NDR Embedded Reference pointer
1706 """
1707
1708 EMBEDDED = True
1709
1710
1711# Constructed types
1712
1713
1714# Note: this is utterly complex and will drive you crazy
1715
1716# If you have a NDRPacket that contains a deferred pointer on the top level
1717# (only happens in non DCE/RPC structures, such as in MS-PAC, where you have an NDR
1718# structure encapsulated in a non-NDR structure), there will be left-over deferred
1719# pointers when exiting dissection/build (deferred pointers are only computed when
1720# reaching a field that extends NDRConstructedType, which is normal: if you follow
1721# the DCE/RPC spec, pointers are never deferred in root structures)
1722# Therefore there is a special case forcing the build/dissection of any leftover
1723# pointers in NDRPacket, if Scapy detects that they won't be handled by any parent.
1724
1725# Implementation notes: I chose to set 'handles_deferred' inside the FIELD, rather
1726# than inside the PACKET. This is faster to compute because whether a constructed type
1727# should handle deferral or not is computed only once when loading, therefore Scapy
1728# knows in advance whether to handle deferred pointers or not. But it is technically
1729# incorrect: with this approach, a structure (packet) cannot be used in 2 code paths
1730# that have different pointer managements. I mean by that that if there was a
1731# structure that was directly embedded in a RPC request without a pointer but also
1732# embedded with a pointer in another RPC request, it would break.
1733# Fortunately this isn't the case: structures are never reused for 2 purposes.
1734# (or at least I never seen that... <i hope this works>)
1735
1736
1737class NDRConstructedType(object):
1738 def __init__(self, fields):
1739 self.handles_deferred = False
1740 self.ndr_fields = fields
1741 self.rec_check_deferral()
1742
1743 def rec_check_deferral(self):
1744 # We iterate through the fields within this constructed type.
1745 # If we have a pointer, mark this field as handling deferrance
1746 # and make all sub-constructed types not.
1747 for f in self.ndr_fields:
1748 if isinstance(f, NDRFullPointerField) and f.deferred:
1749 self.handles_deferred = True
1750 if isinstance(f, NDRConstructedType):
1751 f.rec_check_deferral()
1752 if f.handles_deferred:
1753 self.handles_deferred = True
1754 f.handles_deferred = False
1755
1756 def getfield(self, pkt, s):
1757 s, fval = super(NDRConstructedType, self).getfield(pkt, s)
1758 if isinstance(fval, _NDRPacket):
1759 # If a sub-packet we just dissected has deferred pointers,
1760 # pass it to parent packet to propagate.
1761 pkt.deferred_pointers.extend(fval.deferred_pointers)
1762 del fval.deferred_pointers[:]
1763 if self.handles_deferred:
1764 # This field handles deferral !
1765 s = self.read_deferred_pointers(pkt, s)
1766 return s, fval
1767
1768 def read_deferred_pointers(self, pkt, s):
1769 # Now read content of the pointers that were deferred
1770 q = collections.deque()
1771 q.extend(pkt.deferred_pointers)
1772 del pkt.deferred_pointers[:]
1773 while q:
1774 # Recursively resolve pointers that were deferred
1775 ptr, getfld = q.popleft()
1776 s, val = getfld(s)
1777 ptr.value = val
1778 if isinstance(val, _NDRPacket):
1779 # Pointer resolves to a packet.. that may have deferred pointers?
1780 q.extend(val.deferred_pointers)
1781 del val.deferred_pointers[:]
1782 return s
1783
1784 def addfield(self, pkt, s, val):
1785 s = super(NDRConstructedType, self).addfield(pkt, s, val)
1786 if isinstance(val, _NDRPacket):
1787 # If a sub-packet we just dissected has deferred pointers,
1788 # pass it to parent packet to propagate.
1789 pkt.deferred_pointers.extend(val.deferred_pointers)
1790 del val.deferred_pointers[:]
1791 if self.handles_deferred:
1792 # This field handles deferral !
1793 s = self.add_deferred_pointers(pkt, s)
1794 return s
1795
1796 def add_deferred_pointers(self, pkt, s):
1797 # Now add content of pointers that were deferred
1798 q = collections.deque()
1799 q.extend(pkt.deferred_pointers)
1800 del pkt.deferred_pointers[:]
1801 while q:
1802 addfld, fval = q.popleft()
1803 s = addfld(s)
1804 if isinstance(fval, NDRPointer) and isinstance(fval.value, _NDRPacket):
1805 q.extend(fval.value.deferred_pointers)
1806 del fval.value.deferred_pointers[:]
1807 return s
1808
1809
1810class _NDRPacketField(_NDRValueOf, PacketField):
1811 def m2i(self, pkt, m):
1812 return self.cls(m, ndr64=pkt.ndr64, ndrendian=pkt.ndrendian, _parent=pkt)
1813
1814
1815# class _NDRPacketPadField(PadField):
1816# def padlen(self, flen, pkt):
1817# if pkt.ndr64:
1818# return -flen % self._align[1]
1819# else:
1820# return 0
1821
1822
1823class NDRPacketField(NDRConstructedType, NDRAlign):
1824 def __init__(self, name, default, pkt_cls, **kwargs):
1825 self.DEPORTED_CONFORMANTS = pkt_cls.DEPORTED_CONFORMANTS
1826 self.fld = _NDRPacketField(name, default, pkt_cls=pkt_cls, **kwargs)
1827 NDRAlign.__init__(
1828 self,
1829 # There is supposed to be padding after a struct in NDR64?
1830 # _NDRPacketPadField(fld, align=pkt_cls.ALIGNMENT),
1831 self.fld,
1832 align=pkt_cls.ALIGNMENT,
1833 )
1834 NDRConstructedType.__init__(self, pkt_cls.fields_desc)
1835
1836 def getfield(self, pkt, x):
1837 # Handle deformed conformants max_count here
1838 if self.DEPORTED_CONFORMANTS:
1839 # C706 14.3.2: "In other words, the size information precedes the
1840 # structure and is aligned independently of the structure alignment."
1841 fld = NDRInt3264Field("", 0)
1842 max_counts = []
1843 for _ in self.DEPORTED_CONFORMANTS:
1844 x, max_count = fld.getfield(pkt, x)
1845 max_counts.append(max_count)
1846 res, val = super(NDRPacketField, self).getfield(pkt, x)
1847 if len(max_counts) == 1:
1848 val.max_count = max_counts[0]
1849 else:
1850 val.max_counts = max_counts
1851 return res, val
1852 return super(NDRPacketField, self).getfield(pkt, x)
1853
1854 def addfield(self, pkt, s, x):
1855 # Handle deformed conformants max_count here
1856 if self.DEPORTED_CONFORMANTS:
1857 mcfld = NDRInt3264Field("", 0)
1858 if len(self.DEPORTED_CONFORMANTS) == 1:
1859 max_counts = [x.max_count]
1860 else:
1861 max_counts = x.max_counts
1862 for fldname, max_count in zip(self.DEPORTED_CONFORMANTS, max_counts):
1863 if max_count is None:
1864 fld, val = x.getfield_and_val(fldname)
1865 max_count = fld.i2len(x, val)
1866 s = mcfld.addfield(pkt, s, max_count)
1867 return super(NDRPacketField, self).addfield(pkt, s, x)
1868 return super(NDRPacketField, self).addfield(pkt, s, x)
1869
1870
1871# Array types
1872
1873
1874class _NDRPacketListField(NDRConstructedType, PacketListField):
1875 """
1876 A PacketListField for NDR that can optionally pack the packets into NDRPointers
1877 """
1878
1879 islist = 1
1880 holds_packets = 1
1881
1882 __slots__ = ["ptr_pack", "fld"]
1883
1884 def __init__(self, name, default, pkt_cls, **kwargs):
1885 self.ptr_pack = kwargs.pop("ptr_pack", False)
1886 if self.ptr_pack:
1887 self.fld = NDRFullPointerField(
1888 NDRPacketField("", None, pkt_cls), deferred=True
1889 )
1890 else:
1891 self.fld = NDRPacketField("", None, pkt_cls)
1892 PacketListField.__init__(self, name, default, pkt_cls=pkt_cls, **kwargs)
1893 NDRConstructedType.__init__(self, [self.fld])
1894
1895 def m2i(self, pkt, s):
1896 remain, val = self.fld.getfield(pkt, s)
1897 # A mistake here would be to use / instead of add_payload. It adds a copy
1898 # which breaks pointer defferal. Same applies elsewhere
1899 val.add_payload(conf.padding_layer(remain))
1900 return val
1901
1902 def any2i(self, pkt, x):
1903 # User-friendly helper
1904 if isinstance(x, list):
1905 x = [self.fld.any2i(pkt, y) for y in x]
1906 return super(_NDRPacketListField, self).any2i(pkt, x)
1907
1908 def i2m(self, pkt, val):
1909 return self.fld.addfield(pkt, b"", val)
1910
1911 def i2len(self, pkt, x):
1912 return len(x)
1913
1914 def valueof(self, pkt, x):
1915 return [self.fld.valueof(pkt, y) for y in x]
1916
1917
1918class NDRFieldListField(NDRConstructedType, FieldListField):
1919 """
1920 A FieldListField for NDR
1921 """
1922
1923 islist = 1
1924
1925 def __init__(self, *args, **kwargs):
1926 kwargs.pop("ptr_pack", None) # TODO: unimplemented
1927 if "length_is" in kwargs:
1928 kwargs["count_from"] = kwargs.pop("length_is")
1929 elif "size_is" in kwargs:
1930 kwargs["count_from"] = kwargs.pop("size_is")
1931 FieldListField.__init__(self, *args, **kwargs)
1932 NDRConstructedType.__init__(self, [self.field])
1933
1934 def i2len(self, pkt, x):
1935 return len(x)
1936
1937 def valueof(self, pkt, x):
1938 return [self.field.valueof(pkt, y) for y in x]
1939
1940
1941class NDRVaryingArray(_NDRPacket):
1942 fields_desc = [
1943 MultipleTypeField(
1944 [(LELongField("offset", 0), lambda pkt: pkt and pkt.ndr64)],
1945 LEIntField("offset", 0),
1946 ),
1947 MultipleTypeField(
1948 [
1949 (
1950 LELongField("actual_count", None),
1951 lambda pkt: pkt and pkt.ndr64,
1952 )
1953 ],
1954 LEIntField("actual_count", None),
1955 ),
1956 PacketField("value", None, conf.raw_layer),
1957 ]
1958
1959
1960class _NDRVarField(object):
1961 """
1962 NDR Varying Array / String field
1963 """
1964
1965 LENGTH_FROM = False
1966 COUNT_FROM = False
1967
1968 def __init__(self, *args, **kwargs):
1969 # size is either from the length_is, if specified, or the "actual_count"
1970 self.from_actual = "length_is" not in kwargs
1971 length_is = kwargs.pop("length_is", lambda pkt: pkt.actual_count)
1972 if self.LENGTH_FROM:
1973 kwargs["length_from"] = length_is
1974 elif self.COUNT_FROM:
1975 kwargs["count_from"] = length_is
1976 super(_NDRVarField, self).__init__(*args, **kwargs)
1977
1978 def getfield(self, pkt, s):
1979 fmt = _e(pkt.ndrendian) + ["I", "Q"][pkt.ndr64]
1980 remain, offset = NDRAlign(Field("", 0, fmt=fmt), align=(4, 8)).getfield(pkt, s)
1981 remain, actual_count = NDRAlign(Field("", 0, fmt=fmt), align=(4, 8)).getfield(
1982 pkt, remain
1983 )
1984 final = NDRVaryingArray(
1985 ndr64=pkt.ndr64,
1986 ndrendian=pkt.ndrendian,
1987 offset=offset,
1988 actual_count=actual_count,
1989 )
1990 if self.from_actual:
1991 remain, val = super(_NDRVarField, self).getfield(final, remain)
1992 else:
1993 remain, val = super(_NDRVarField, self).getfield(pkt, remain)
1994 final.value = super(_NDRVarField, self).i2h(pkt, val)
1995 return remain, final
1996
1997 def addfield(self, pkt, s, val):
1998 if not isinstance(val, NDRVaryingArray):
1999 raise ValueError(
2000 "Expected NDRVaryingArray in %s. You are using it wrong!" % self.name
2001 )
2002 fmt = _e(pkt.ndrendian) + ["I", "Q"][pkt.ndr64]
2003 _set_ctx_on(val.value, pkt)
2004 s = NDRAlign(Field("", 0, fmt=fmt), align=(4, 8)).addfield(pkt, s, val.offset)
2005 s = NDRAlign(Field("", 0, fmt=fmt), align=(4, 8)).addfield(
2006 pkt,
2007 s,
2008 val.actual_count is None
2009 and super(_NDRVarField, self).i2len(pkt, val.value)
2010 or val.actual_count,
2011 )
2012 return super(_NDRVarField, self).addfield(
2013 pkt, s, super(_NDRVarField, self).h2i(pkt, val.value)
2014 )
2015
2016 def i2len(self, pkt, x):
2017 return super(_NDRVarField, self).i2len(pkt, x.value)
2018
2019 def any2i(self, pkt, x):
2020 # User-friendly helper
2021 if not isinstance(x, NDRVaryingArray):
2022 return NDRVaryingArray(
2023 value=super(_NDRVarField, self).any2i(pkt, x),
2024 )
2025 return x
2026
2027 # Can't use i2repr = Field.i2repr and so on on PY2 :/
2028 def i2repr(self, pkt, val):
2029 return repr(val)
2030
2031 def i2h(self, pkt, x):
2032 return x
2033
2034 def h2i(self, pkt, x):
2035 return x
2036
2037 def valueof(self, pkt, x):
2038 return super(_NDRVarField, self).valueof(pkt, x.value)
2039
2040
2041class NDRConformantArray(_NDRPacket):
2042 fields_desc = [
2043 MultipleTypeField(
2044 [(LELongField("max_count", None), lambda pkt: pkt and pkt.ndr64)],
2045 LEIntField("max_count", None),
2046 ),
2047 MultipleTypeField(
2048 [
2049 (
2050 PacketListField(
2051 "value",
2052 [],
2053 conf.raw_layer,
2054 count_from=lambda pkt: pkt.max_count,
2055 ),
2056 (
2057 lambda pkt: pkt.fields.get("value", None)
2058 and isinstance(pkt.fields["value"][0], Packet),
2059 lambda _, val: val and isinstance(val[0], Packet),
2060 ),
2061 )
2062 ],
2063 FieldListField(
2064 "value", [], LEIntField("", 0), count_from=lambda pkt: pkt.max_count
2065 ),
2066 ),
2067 ]
2068
2069
2070class NDRConformantString(_NDRPacket):
2071 fields_desc = [
2072 MultipleTypeField(
2073 [(LELongField("max_count", None), lambda pkt: pkt and pkt.ndr64)],
2074 LEIntField("max_count", None),
2075 ),
2076 StrField("value", ""),
2077 ]
2078
2079
2080class _NDRConfField(object):
2081 """
2082 NDR Conformant Array / String field
2083 """
2084
2085 CONFORMANT_STRING = False
2086 LENGTH_FROM = False
2087 COUNT_FROM = False
2088
2089 def __init__(self, *args, **kwargs):
2090 self.conformant_in_struct = kwargs.pop("conformant_in_struct", False)
2091 # size_is/max_is end up here, and is what defines a conformant field.
2092 if "size_is" in kwargs:
2093 size_is = kwargs.pop("size_is")
2094 if self.LENGTH_FROM:
2095 kwargs["length_from"] = size_is
2096 elif self.COUNT_FROM:
2097 kwargs["count_from"] = size_is
2098 super(_NDRConfField, self).__init__(*args, **kwargs)
2099
2100 def getfield(self, pkt, s):
2101 # [C706] - 14.3.7 Structures Containing Arrays
2102 fmt = _e(pkt.ndrendian) + ["I", "Q"][pkt.ndr64]
2103 if self.conformant_in_struct:
2104 return super(_NDRConfField, self).getfield(pkt, s)
2105 remain, max_count = NDRAlign(Field("", 0, fmt=fmt), align=(4, 8)).getfield(
2106 pkt, s
2107 )
2108 remain, val = super(_NDRConfField, self).getfield(pkt, remain)
2109 return remain, (
2110 NDRConformantString if self.CONFORMANT_STRING else NDRConformantArray
2111 )(ndr64=pkt.ndr64, ndrendian=pkt.ndrendian, max_count=max_count, value=val)
2112
2113 def addfield(self, pkt, s, val):
2114 if self.conformant_in_struct:
2115 return super(_NDRConfField, self).addfield(pkt, s, val)
2116 if self.CONFORMANT_STRING and not isinstance(val, NDRConformantString):
2117 raise ValueError(
2118 "Expected NDRConformantString in %s. You are using it wrong!"
2119 % self.name
2120 )
2121 elif not self.CONFORMANT_STRING and not isinstance(val, NDRConformantArray):
2122 raise ValueError(
2123 "Expected NDRConformantArray in %s. You are using it wrong!" % self.name
2124 )
2125 fmt = _e(pkt.ndrendian) + ["I", "Q"][pkt.ndr64]
2126 _set_ctx_on(val.value, pkt)
2127 if val.value and isinstance(val.value[0], NDRVaryingArray):
2128 value = val.value[0]
2129 else:
2130 value = val.value
2131 s = NDRAlign(Field("", 0, fmt=fmt), align=(4, 8)).addfield(
2132 pkt,
2133 s,
2134 val.max_count is None
2135 and super(_NDRConfField, self).i2len(pkt, value)
2136 or val.max_count,
2137 )
2138 return super(_NDRConfField, self).addfield(pkt, s, value)
2139
2140 def _subval(self, x):
2141 if self.conformant_in_struct:
2142 value = x
2143 elif (
2144 not self.CONFORMANT_STRING
2145 and x.value
2146 and isinstance(x.value[0], NDRVaryingArray)
2147 ):
2148 value = x.value[0]
2149 else:
2150 value = x.value
2151 return value
2152
2153 def i2len(self, pkt, x):
2154 return super(_NDRConfField, self).i2len(pkt, self._subval(x))
2155
2156 def any2i(self, pkt, x):
2157 # User-friendly helper
2158 if self.conformant_in_struct:
2159 return x
2160 if self.CONFORMANT_STRING and not isinstance(x, NDRConformantString):
2161 return NDRConformantString(
2162 value=super(_NDRConfField, self).any2i(pkt, x),
2163 )
2164 elif not isinstance(x, NDRConformantArray):
2165 return NDRConformantArray(
2166 value=super(_NDRConfField, self).any2i(pkt, x),
2167 )
2168 return x
2169
2170 # Can't use i2repr = Field.i2repr and so on on PY2 :/
2171 def i2repr(self, pkt, val):
2172 return repr(val)
2173
2174 def i2h(self, pkt, x):
2175 return x
2176
2177 def h2i(self, pkt, x):
2178 return x
2179
2180 def valueof(self, pkt, x):
2181 return super(_NDRConfField, self).valueof(pkt, self._subval(x))
2182
2183
2184class NDRVarPacketListField(_NDRVarField, _NDRPacketListField):
2185 """
2186 NDR Varying PacketListField. Unused
2187 """
2188
2189 COUNT_FROM = True
2190
2191
2192class NDRConfPacketListField(_NDRConfField, _NDRPacketListField):
2193 """
2194 NDR Conformant PacketListField
2195 """
2196
2197 COUNT_FROM = True
2198
2199
2200class NDRConfVarPacketListField(_NDRConfField, _NDRVarField, _NDRPacketListField):
2201 """
2202 NDR Conformant Varying PacketListField
2203 """
2204
2205 COUNT_FROM = True
2206
2207
2208class NDRConfFieldListField(_NDRConfField, NDRFieldListField):
2209 """
2210 NDR Conformant FieldListField
2211 """
2212
2213 COUNT_FROM = True
2214
2215
2216class NDRConfVarFieldListField(_NDRConfField, _NDRVarField, NDRFieldListField):
2217 """
2218 NDR Conformant Varying FieldListField
2219 """
2220
2221 COUNT_FROM = True
2222
2223
2224# NDR String fields
2225
2226
2227class _NDRUtf16(Field):
2228 def h2i(self, pkt, x):
2229 encoding = {"big": "utf-16be", "little": "utf-16le"}[pkt.ndrendian]
2230 return plain_str(x).encode(encoding)
2231
2232 def i2h(self, pkt, x):
2233 encoding = {"big": "utf-16be", "little": "utf-16le"}[pkt.ndrendian]
2234 return bytes_encode(x).decode(encoding, errors="replace")
2235
2236
2237class NDRConfStrLenField(_NDRConfField, _NDRValueOf, StrLenField):
2238 """
2239 NDR Conformant StrLenField.
2240
2241 This is not a "string" per NDR, but an a conformant byte array
2242 (e.g. tower_octet_string)
2243 """
2244
2245 CONFORMANT_STRING = True
2246 LENGTH_FROM = True
2247
2248
2249class NDRConfStrLenFieldUtf16(_NDRConfField, _NDRValueOf, StrLenFieldUtf16, _NDRUtf16):
2250 """
2251 NDR Conformant StrLenField.
2252
2253 See NDRConfLenStrField for comment.
2254 """
2255
2256 CONFORMANT_STRING = True
2257 ON_WIRE_SIZE_UTF16 = False
2258 LENGTH_FROM = True
2259
2260
2261class NDRVarStrLenField(_NDRVarField, StrLenField):
2262 """
2263 NDR Varying StrLenField
2264 """
2265
2266 LENGTH_FROM = True
2267
2268
2269class NDRVarStrLenFieldUtf16(_NDRVarField, _NDRValueOf, StrLenFieldUtf16, _NDRUtf16):
2270 """
2271 NDR Varying StrLenField
2272 """
2273
2274 ON_WIRE_SIZE_UTF16 = False
2275 LENGTH_FROM = True
2276
2277
2278class NDRConfVarStrLenField(_NDRConfField, _NDRVarField, _NDRValueOf, StrLenField):
2279 """
2280 NDR Conformant Varying StrLenField
2281 """
2282
2283 LENGTH_FROM = True
2284
2285
2286class NDRConfVarStrLenFieldUtf16(
2287 _NDRConfField, _NDRVarField, _NDRValueOf, StrLenFieldUtf16, _NDRUtf16
2288):
2289 """
2290 NDR Conformant Varying StrLenField
2291 """
2292
2293 ON_WIRE_SIZE_UTF16 = False
2294 LENGTH_FROM = True
2295
2296
2297class NDRConfVarStrNullField(_NDRConfField, _NDRVarField, _NDRValueOf, StrNullField):
2298 """
2299 NDR Conformant Varying StrNullField
2300 """
2301
2302 NULLFIELD = True
2303
2304
2305class NDRConfVarStrNullFieldUtf16(
2306 _NDRConfField, _NDRVarField, _NDRValueOf, StrNullFieldUtf16, _NDRUtf16
2307):
2308 """
2309 NDR Conformant Varying StrNullFieldUtf16
2310 """
2311
2312 ON_WIRE_SIZE_UTF16 = False
2313 NULLFIELD = True
2314
2315
2316# Union type
2317
2318
2319class NDRUnion(_NDRPacket):
2320 fields_desc = [
2321 IntField("tag", 0),
2322 PacketField("value", None, conf.raw_layer),
2323 ]
2324
2325
2326class _NDRUnionField(MultipleTypeField):
2327 __slots__ = ["switch_fmt", "align"]
2328
2329 def __init__(self, flds, dflt, align, switch_fmt):
2330 self.switch_fmt = switch_fmt
2331 self.align = align
2332 super(_NDRUnionField, self).__init__(flds, dflt)
2333
2334 def getfield(self, pkt, s):
2335 fmt = _e(pkt.ndrendian) + self.switch_fmt[pkt.ndr64]
2336 remain, tag = NDRAlign(Field("", 0, fmt=fmt), align=self.align).getfield(pkt, s)
2337 fld, _ = super(_NDRUnionField, self)._find_fld_pkt_val(pkt, NDRUnion(tag=tag))
2338 remain, val = fld.getfield(pkt, remain)
2339 return remain, NDRUnion(
2340 tag=tag, value=val, ndr64=pkt.ndr64, ndrendian=pkt.ndrendian, _parent=pkt
2341 )
2342
2343 def addfield(self, pkt, s, val):
2344 fmt = _e(pkt.ndrendian) + self.switch_fmt[pkt.ndr64]
2345 if not isinstance(val, NDRUnion):
2346 raise ValueError(
2347 "Expected NDRUnion in %s. You are using it wrong!" % self.name
2348 )
2349 _set_ctx_on(val.value, pkt)
2350 # First, align the whole tag+union against the align param
2351 s = NDRAlign(Field("", 0, fmt=fmt), align=self.align).addfield(pkt, s, val.tag)
2352 # Then, compute the subfield with its own alignment
2353 return super(_NDRUnionField, self).addfield(pkt, s, val)
2354
2355 def _find_fld_pkt_val(self, pkt, val):
2356 fld, val = super(_NDRUnionField, self)._find_fld_pkt_val(pkt, val)
2357 return fld, val.value
2358
2359 # Can't use i2repr = Field.i2repr and so on on PY2 :/
2360 def i2repr(self, pkt, val):
2361 return repr(val)
2362
2363 def i2h(self, pkt, x):
2364 return x
2365
2366 def h2i(self, pkt, x):
2367 return x
2368
2369 def valueof(self, pkt, x):
2370 fld, val = self._find_fld_pkt_val(pkt, x)
2371 return fld.valueof(pkt, x.value)
2372
2373
2374class NDRUnionField(NDRConstructedType, _NDRUnionField):
2375 def __init__(self, flds, dflt, align, switch_fmt):
2376 _NDRUnionField.__init__(self, flds, dflt, align=align, switch_fmt=switch_fmt)
2377 NDRConstructedType.__init__(self, [x[0] for x in flds] + [dflt])
2378
2379 def any2i(self, pkt, x):
2380 # User-friendly helper
2381 if x:
2382 if not isinstance(x, NDRUnion):
2383 raise ValueError("Invalid value for %s; should be NDRUnion" % self.name)
2384 else:
2385 x.value = _NDRUnionField.any2i(self, pkt, x)
2386 return x
2387
2388
2389# Misc
2390
2391
2392class NDRRecursiveField(Field):
2393 """
2394 A special Field that is used for pointer recursion
2395 """
2396
2397 def __init__(self, name, fmt="I"):
2398 super(NDRRecursiveField, self).__init__(name, None, fmt=fmt)
2399
2400 def getfield(self, pkt, s):
2401 return NDRFullPointerField(
2402 NDRPacketField("", None, pkt.__class__), deferred=True
2403 ).getfield(pkt, s)
2404
2405 def addfield(self, pkt, s, val):
2406 return NDRFullPointerField(
2407 NDRPacketField("", None, pkt.__class__), deferred=True
2408 ).addfield(pkt, s, val)
2409
2410
2411# The very few NDR-specific structures
2412
2413
2414class NDRContextHandle(NDRPacket):
2415 ALIGNMENT = (4, 4)
2416 fields_desc = [
2417 LEIntField("attributes", 0),
2418 StrFixedLenField("uuid", b"", length=16),
2419 ]
2420
2421 def guess_payload_class(self, payload):
2422 return conf.padding_layer
2423
2424
2425# --- Type Serialization Version 1 - [MSRPCE] sect 2.2.6
2426
2427
2428def _get_ndrtype1_endian(pkt):
2429 if pkt.underlayer is None:
2430 return "<"
2431 return {0x00: ">", 0x10: "<"}.get(pkt.underlayer.Endianness, "<")
2432
2433
2434class NDRSerialization1Header(Packet):
2435 fields_desc = [
2436 ByteField("Version", 1),
2437 ByteEnumField("Endianness", 0x10, {0x00: "big", 0x10: "little"}),
2438 LEShortField("CommonHeaderLength", 8),
2439 XLEIntField("Filler", 0xCCCCCCCC),
2440 ]
2441
2442
2443class NDRSerialization1PrivateHeader(Packet):
2444 fields_desc = [
2445 EField(
2446 LEIntField("ObjectBufferLength", 0), endianness_from=_get_ndrtype1_endian
2447 ),
2448 XLEIntField("Filler", 0),
2449 ]
2450
2451
2452def ndr_deserialize1(b, cls, ndr64=False):
2453 """
2454 Deserialize Type Serialization Version 1 according to [MS-RPCE] sect 2.2.6
2455 """
2456 if issubclass(cls, NDRPacket):
2457 # We use an intermediary class for two reasons:
2458 # - it properly sets deferred pointers
2459 # - it uses NDRPacketField which handles deported conformant fields
2460 class _cls(NDRPacket):
2461 fields_desc = [
2462 NDRFullPointerField(NDRPacketField("pkt", None, cls)),
2463 ]
2464
2465 hdr = NDRSerialization1Header(b[:8]) / NDRSerialization1PrivateHeader(b[8:16])
2466 endian = {0x00: "big", 0x10: "little"}[hdr.Endianness]
2467 padlen = (-hdr.ObjectBufferLength) % _TYPE1_S_PAD
2468 # padlen should be 0 (pad included in length), but some implementations
2469 # implement apparently misread the spec
2470 return (
2471 hdr
2472 / _cls(
2473 b[16 : 20 + hdr.ObjectBufferLength],
2474 ndr64=ndr64,
2475 ndrendian=endian,
2476 ).pkt
2477 / conf.padding_layer(b[20 + padlen + hdr.ObjectBufferLength :])
2478 )
2479 return NDRSerialization1Header(b[:8]) / cls(b[8:])
2480
2481
2482def ndr_serialize1(pkt):
2483 """
2484 Serialize Type Serialization Version 1
2485 """
2486 pkt = pkt.copy()
2487 endian = getattr(pkt, "ndrendian", "little")
2488 if not isinstance(pkt, NDRSerialization1Header):
2489 if not isinstance(pkt, NDRPacket):
2490 return bytes(NDRSerialization1Header(Endianness=endian) / pkt)
2491 if isinstance(pkt, NDRPointer):
2492 cls = pkt.value.__class__
2493 else:
2494 cls = pkt.__class__
2495 val = pkt
2496 pkt_len = len(pkt)
2497 # ObjectBufferLength:
2498 # > It MUST include the padding length and exclude the header itself
2499 pkt = NDRSerialization1Header(
2500 Endianness=endian
2501 ) / NDRSerialization1PrivateHeader(
2502 ObjectBufferLength=pkt_len + (-pkt_len) % _TYPE1_S_PAD
2503 )
2504 else:
2505 cls = pkt.value.__class__
2506 val = pkt.payload.payload
2507 pkt.payload.remove_payload()
2508
2509 # See above about why we need an intermediary class
2510 class _cls(NDRPacket):
2511 fields_desc = [
2512 NDRFullPointerField(NDRPacketField("pkt", None, cls)),
2513 ]
2514
2515 ret = bytes(pkt / _cls(pkt=val))
2516 return ret + (-len(ret) % _TYPE1_S_PAD) * b"\x00"
2517
2518
2519class _NDRSerializeType1:
2520 def __init__(self, *args, **kwargs):
2521 super(_NDRSerializeType1, self).__init__(*args, **kwargs)
2522
2523 def i2m(self, pkt, val):
2524 return ndr_serialize1(val)
2525
2526 def m2i(self, pkt, s):
2527 return ndr_deserialize1(s, self.cls, ndr64=False)
2528
2529 def i2len(self, pkt, val):
2530 return len(self.i2m(pkt, val))
2531
2532
2533class NDRSerializeType1PacketField(_NDRSerializeType1, PacketField):
2534 __slots__ = ["ptr"]
2535
2536
2537class NDRSerializeType1PacketLenField(_NDRSerializeType1, PacketLenField):
2538 __slots__ = ["ptr"]
2539
2540
2541class NDRSerializeType1PacketListField(_NDRSerializeType1, PacketListField):
2542 __slots__ = ["ptr"]
2543
2544
2545# --- DCE/RPC session
2546
2547
2548class DceRpcSession(DefaultSession):
2549 """
2550 A DCE/RPC session within a TCP socket.
2551 """
2552
2553 def __init__(self, *args, **kwargs):
2554 self.rpc_bind_interface = None
2555 self.ndr64 = False
2556 self.ndrendian = "little"
2557 self.support_header_signing = kwargs.pop("support_header_signing", True)
2558 self.header_sign = conf.dcerpc_force_header_signing
2559 self.ssp = kwargs.pop("ssp", None)
2560 self.sspcontext = kwargs.pop("sspcontext", None)
2561 self.auth_level = kwargs.pop("auth_level", None)
2562 self.auth_context_id = kwargs.pop("auth_context_id", 0)
2563 self.map_callid_opnum = {}
2564 self.frags = collections.defaultdict(lambda: b"")
2565 self.sniffsspcontexts = {} # Unfinished contexts for passive
2566 if conf.dcerpc_session_enable and conf.winssps_passive:
2567 for ssp in conf.winssps_passive:
2568 self.sniffsspcontexts[ssp] = None
2569 super(DceRpcSession, self).__init__(*args, **kwargs)
2570
2571 def _up_pkt(self, pkt):
2572 """
2573 Common function to handle the DCE/RPC session: what interfaces are bind,
2574 opnums, etc.
2575 """
2576 opnum = None
2577 opts = {}
2578 if DceRpc5Bind in pkt or DceRpc5AlterContext in pkt:
2579 # bind => get which RPC interface
2580 for ctx in pkt.context_elem:
2581 if_uuid = ctx.abstract_syntax.if_uuid
2582 if_version = ctx.abstract_syntax.if_version
2583 try:
2584 self.rpc_bind_interface = DCE_RPC_INTERFACES[(if_uuid, if_version)]
2585 except KeyError:
2586 self.rpc_bind_interface = None
2587 log_runtime.warning(
2588 "Unknown RPC interface %s. Try loading the IDL" % if_uuid
2589 )
2590 elif DceRpc5BindAck in pkt or DceRpc5AlterContextResp in pkt:
2591 # bind ack => is it NDR64
2592 for res in pkt.results:
2593 if res.result == 0: # Accepted
2594 self.ndrendian = {0: "big", 1: "little"}[pkt[DceRpc5].endian]
2595 if res.transfer_syntax.sprintf("%if_uuid%") == "NDR64":
2596 self.ndr64 = True
2597 elif DceRpc5Request in pkt:
2598 # request => match opnum with callID
2599 opnum = pkt.opnum
2600 self.map_callid_opnum[pkt.call_id] = opnum, pkt[DceRpc5Request].payload
2601 elif DceRpc5Response in pkt:
2602 # response => get opnum from table
2603 try:
2604 opnum, opts["request_packet"] = self.map_callid_opnum[pkt.call_id]
2605 del self.map_callid_opnum[pkt.call_id]
2606 except KeyError:
2607 log_runtime.info("Unknown call_id %s in DCE/RPC session" % pkt.call_id)
2608 # Bind / Alter request/response specific
2609 if (
2610 DceRpc5Bind in pkt
2611 or DceRpc5AlterContext in pkt
2612 or DceRpc5BindAck in pkt
2613 or DceRpc5AlterContextResp in pkt
2614 ):
2615 # Detect if "Header Signing" is in use
2616 if pkt.pfc_flags & 0x04: # PFC_SUPPORT_HEADER_SIGN
2617 self.header_sign = True
2618 return opnum, opts
2619
2620 # [C706] sect 12.6.2 - Fragmentation and Reassembly
2621 # Since the connection-oriented transport guarantees sequentiality, the receiver
2622 # will always receive the fragments in order.
2623
2624 def _defragment(self, pkt):
2625 """
2626 Function to defragment DCE/RPC packets.
2627 """
2628 uid = pkt.call_id
2629 if pkt.pfc_flags.PFC_FIRST_FRAG and pkt.pfc_flags.PFC_LAST_FRAG:
2630 # Not fragmented
2631 return pkt
2632 if pkt.pfc_flags.PFC_FIRST_FRAG or uid in self.frags:
2633 # Packet is fragmented
2634 self.frags[uid] += pkt[DceRpc5].payload.payload.original
2635 if pkt.pfc_flags.PFC_LAST_FRAG:
2636 pkt[DceRpc5].payload.remove_payload()
2637 pkt[DceRpc5].payload /= self.frags[uid]
2638 return pkt
2639 else:
2640 # Not fragmented
2641 return pkt
2642
2643 def _fragment(self, pkt):
2644 """
2645 Function to fragment DCE/RPC packets.
2646 """
2647 # unimplemented
2648 pass
2649
2650 # [MS-RPCE] sect 3.3.1.5.2.2
2651
2652 # The PDU header, PDU body, and sec_trailer MUST be passed in the input message, in
2653 # this order, to GSS_WrapEx, GSS_UnwrapEx, GSS_GetMICEx, and GSS_VerifyMICEx. For
2654 # integrity protection the sign flag for that PDU segment MUST be set to TRUE, else
2655 # it MUST be set to FALSE. For confidentiality protection, the conf_req_flag for
2656 # that PDU segment MUST be set to TRUE, else it MUST be set to FALSE.
2657
2658 # If the authentication level is RPC_C_AUTHN_LEVEL_PKT_PRIVACY, the PDU body will
2659 # be encrypted.
2660 # The PDU body from the output message of GSS_UnwrapEx represents the plain text
2661 # version of the PDU body. The PDU header and sec_trailer output from the output
2662 # message SHOULD be ignored.
2663 # Similarly the signature output SHOULD be ignored.
2664
2665 def in_pkt(self, pkt):
2666 # Defragment
2667 pkt = self._defragment(pkt)
2668 if not pkt:
2669 return
2670 # Get opnum and options
2671 opnum, opts = self._up_pkt(pkt)
2672 # Check for encrypted payloads
2673 body = None
2674 if conf.raw_layer in pkt:
2675 body = bytes(pkt[conf.raw_layer])
2676 # If we are doing passive sniffing
2677 if conf.dcerpc_session_enable and conf.winssps_passive:
2678 # We have Windows SSPs, and no current context
2679 if pkt.auth_verifier and pkt.auth_verifier.is_ssp():
2680 # This is a bind/alter/auth3 req/resp
2681 for ssp in self.sniffsspcontexts:
2682 self.sniffsspcontexts[ssp], status = ssp.GSS_Passive(
2683 self.sniffsspcontexts[ssp],
2684 pkt.auth_verifier.auth_value,
2685 )
2686 if status == GSS_S_COMPLETE:
2687 self.auth_level = DCE_C_AUTHN_LEVEL(
2688 int(pkt.auth_verifier.auth_level)
2689 )
2690 self.ssp = ssp
2691 self.sspcontext = self.sniffsspcontexts[ssp]
2692 self.sniffsspcontexts[ssp] = None
2693 elif (
2694 self.sspcontext
2695 and pkt.auth_verifier
2696 and pkt.auth_verifier.is_protected()
2697 and body
2698 ):
2699 # This is a request/response
2700 self.ssp.GSS_Passive_set_Direction(
2701 self.sspcontext,
2702 IsAcceptor=DceRpc5Response in pkt,
2703 )
2704 if pkt.auth_verifier and pkt.auth_verifier.is_protected() and body:
2705 if self.sspcontext is None:
2706 return pkt
2707 if self.auth_level in (
2708 RPC_C_AUTHN_LEVEL.PKT_INTEGRITY,
2709 RPC_C_AUTHN_LEVEL.PKT_PRIVACY,
2710 ):
2711 # note: 'vt_trailer' is included in the pdu body
2712 # [MS-RPCE] sect 2.2.2.13
2713 # "The data structures MUST only appear in a request PDU, and they
2714 # SHOULD be placed in the PDU immediately after the stub data but
2715 # before the authentication padding octets. Therefore, for security
2716 # purposes, the verification trailer is considered part of the PDU
2717 # body."
2718 if pkt.vt_trailer:
2719 body += bytes(pkt.vt_trailer)
2720 # Account for padding when computing checksum/encryption
2721 if pkt.auth_padding:
2722 body += pkt.auth_padding
2723
2724 # Build pdu_header and sec_trailer
2725 pdu_header = pkt.copy()
2726 sec_trailer = pdu_header.auth_verifier
2727 # sec_trailer: include the sec_trailer but not the Authentication token
2728 authval_len = len(sec_trailer.auth_value)
2729 # Discard everything out of the header
2730 pdu_header.auth_padding = None
2731 pdu_header.auth_verifier = None
2732 pdu_header.payload.payload = NoPayload()
2733 pdu_header.vt_trailer = None
2734
2735 # [MS-RPCE] sect 2.2.2.12
2736 if self.auth_level == RPC_C_AUTHN_LEVEL.PKT_PRIVACY:
2737 _msgs = self.ssp.GSS_UnwrapEx(
2738 self.sspcontext,
2739 [
2740 # "PDU header"
2741 SSP.WRAP_MSG(
2742 conf_req_flag=False,
2743 sign=self.header_sign,
2744 data=bytes(pdu_header),
2745 ),
2746 # "PDU body"
2747 SSP.WRAP_MSG(
2748 conf_req_flag=True,
2749 sign=True,
2750 data=body,
2751 ),
2752 # "sec_trailer"
2753 SSP.WRAP_MSG(
2754 conf_req_flag=False,
2755 sign=self.header_sign,
2756 data=bytes(sec_trailer)[:-authval_len],
2757 ),
2758 ],
2759 pkt.auth_verifier.auth_value,
2760 )
2761 body = _msgs[1].data # PDU body
2762 elif self.auth_level == RPC_C_AUTHN_LEVEL.PKT_INTEGRITY:
2763 self.ssp.GSS_VerifyMICEx(
2764 self.sspcontext,
2765 [
2766 # "PDU header"
2767 SSP.MIC_MSG(
2768 sign=self.header_sign,
2769 data=bytes(pdu_header),
2770 ),
2771 # "PDU body"
2772 SSP.MIC_MSG(
2773 sign=True,
2774 data=body,
2775 ),
2776 # "sec_trailer"
2777 SSP.MIC_MSG(
2778 sign=self.header_sign,
2779 data=bytes(sec_trailer)[:-authval_len],
2780 ),
2781 ],
2782 pkt.auth_verifier.auth_value,
2783 )
2784 # Put padding back into the header
2785 if pkt.auth_padding:
2786 padlen = len(pkt.auth_padding)
2787 body, pkt.auth_padding = body[:-padlen], body[-padlen:]
2788 # Put back vt_trailer into the header
2789 if pkt.vt_trailer:
2790 vtlen = len(pkt.vt_trailer)
2791 body, pkt.vt_trailer = body[:-vtlen], body[-vtlen:]
2792 # Try to parse the payload
2793 if opnum is not None and self.rpc_bind_interface:
2794 # use opnum to parse the payload
2795 is_response = DceRpc5Response in pkt
2796 try:
2797 cls = self.rpc_bind_interface.opnums[opnum][is_response]
2798 except KeyError:
2799 log_runtime.warning(
2800 "Unknown opnum %s for interface %s"
2801 % (opnum, self.rpc_bind_interface)
2802 )
2803 pkt[conf.raw_layer].load = body
2804 return pkt
2805 if body:
2806 # Dissect payload using class
2807 payload = cls(body, ndr64=self.ndr64, ndrendian=self.ndrendian, **opts)
2808 pkt[conf.raw_layer].underlayer.remove_payload()
2809 pkt /= payload
2810 elif not cls.fields_desc:
2811 # Request class has no payload
2812 pkt /= cls(ndr64=self.ndr64, ndrendian=self.ndrendian, **opts)
2813 elif body:
2814 pkt[conf.raw_layer].load = body
2815 return pkt
2816
2817 def out_pkt(self, pkt):
2818 assert DceRpc5 in pkt
2819 self._up_pkt(pkt)
2820 if pkt.auth_verifier is not None:
2821 # Verifier already set
2822 return [pkt]
2823 if self.sspcontext and isinstance(
2824 pkt.payload, (DceRpc5Request, DceRpc5Response)
2825 ):
2826 body = bytes(pkt.payload.payload)
2827 signature = None
2828 if self.auth_level in (
2829 RPC_C_AUTHN_LEVEL.PKT_INTEGRITY,
2830 RPC_C_AUTHN_LEVEL.PKT_PRIVACY,
2831 ):
2832 # Account for padding when computing checksum/encryption
2833 if pkt.auth_padding is None:
2834 padlen = (-len(body)) % _COMMON_AUTH_PAD # authdata padding
2835 pkt.auth_padding = b"\x00" * padlen
2836 else:
2837 padlen = len(pkt.auth_padding)
2838 # Remember that vt_trailer is included in the PDU
2839 if pkt.vt_trailer:
2840 body += bytes(pkt.vt_trailer)
2841 # Remember that padding IS SIGNED & ENCRYPTED
2842 body += pkt.auth_padding
2843 # Add the auth_verifier
2844 pkt.auth_verifier = CommonAuthVerifier(
2845 auth_type=self.ssp.auth_type,
2846 auth_level=self.auth_level,
2847 auth_context_id=self.auth_context_id,
2848 auth_pad_length=padlen,
2849 # Note: auth_value should have the correct length because when
2850 # using PFC_SUPPORT_HEADER_SIGN, auth_len (and frag_len) is
2851 # included in the token.. but this creates a dependency loop as
2852 # you'd need to know the token length to compute the token.
2853 # Windows solves this by setting the 'Maximum Signature Length'
2854 # (or something similar) beforehand, instead of the real length.
2855 # See `gensec_sig_size` in samba.
2856 auth_value=b"\x00"
2857 * self.ssp.MaximumSignatureLength(self.sspcontext),
2858 )
2859 # Build pdu_header and sec_trailer
2860 pdu_header = pkt.copy()
2861 pdu_header.auth_len = len(pdu_header.auth_verifier) - 8
2862 pdu_header.frag_len = len(pdu_header)
2863 sec_trailer = pdu_header.auth_verifier
2864 # sec_trailer: include the sec_trailer but not the Authentication token
2865 authval_len = len(sec_trailer.auth_value)
2866 # sec_trailer.auth_value = None
2867 # Discard everything out of the header
2868 pdu_header.auth_padding = None
2869 pdu_header.auth_verifier = None
2870 pdu_header.payload.payload = NoPayload()
2871 pdu_header.vt_trailer = None
2872 signature = None
2873 # [MS-RPCE] sect 2.2.2.12
2874 if self.auth_level == RPC_C_AUTHN_LEVEL.PKT_PRIVACY:
2875 _msgs, signature = self.ssp.GSS_WrapEx(
2876 self.sspcontext,
2877 [
2878 # "PDU header"
2879 SSP.WRAP_MSG(
2880 conf_req_flag=False,
2881 sign=self.header_sign,
2882 data=bytes(pdu_header),
2883 ),
2884 # "PDU body"
2885 SSP.WRAP_MSG(
2886 conf_req_flag=True,
2887 sign=True,
2888 data=body,
2889 ),
2890 # "sec_trailer"
2891 SSP.WRAP_MSG(
2892 conf_req_flag=False,
2893 sign=self.header_sign,
2894 data=bytes(sec_trailer)[:-authval_len],
2895 ),
2896 ],
2897 )
2898 s = _msgs[1].data # PDU body
2899 elif self.auth_level == RPC_C_AUTHN_LEVEL.PKT_INTEGRITY:
2900 signature = self.ssp.GSS_GetMICEx(
2901 self.sspcontext,
2902 [
2903 # "PDU header"
2904 SSP.MIC_MSG(
2905 sign=self.header_sign,
2906 data=bytes(pdu_header),
2907 ),
2908 # "PDU body"
2909 SSP.MIC_MSG(
2910 sign=True,
2911 data=body,
2912 ),
2913 # "sec_trailer"
2914 SSP.MIC_MSG(
2915 sign=self.header_sign,
2916 data=bytes(sec_trailer)[:-authval_len],
2917 ),
2918 ],
2919 pkt.auth_verifier.auth_value,
2920 )
2921 s = body
2922 else:
2923 raise ValueError("Impossible")
2924 # Put padding back in the header
2925 if padlen:
2926 s, pkt.auth_padding = s[:-padlen], s[-padlen:]
2927 # Put back vt_trailer into the header
2928 if pkt.vt_trailer:
2929 vtlen = len(pkt.vt_trailer)
2930 s, pkt.vt_trailer = s[:-vtlen], s[-vtlen:]
2931 else:
2932 s = body
2933
2934 # now inject the encrypted payload into the packet
2935 pkt.payload.payload = conf.raw_layer(load=s)
2936 # and the auth_value
2937 if signature:
2938 pkt.auth_verifier.auth_value = signature
2939 else:
2940 pkt.auth_verifier = None
2941 return [pkt]
2942
2943 def process(self, pkt: Packet) -> Optional[Packet]:
2944 pkt = super(DceRpcSession, self).process(pkt)
2945 if pkt is not None and DceRpc5 in pkt:
2946 return self.in_pkt(pkt)
2947 return pkt
2948
2949
2950class DceRpcSocket(StreamSocket):
2951 """
2952 A Wrapper around StreamSocket that uses a DceRpcSession
2953 """
2954
2955 def __init__(self, *args, **kwargs):
2956 self.session = DceRpcSession(
2957 ssp=kwargs.pop("ssp", None),
2958 auth_level=kwargs.pop("auth_level", None),
2959 auth_context_id=kwargs.pop("auth_context_id", None),
2960 support_header_signing=kwargs.pop("support_header_signing", True),
2961 )
2962 super(DceRpcSocket, self).__init__(*args, **kwargs)
2963
2964 def send(self, x, **kwargs):
2965 for pkt in self.session.out_pkt(x):
2966 return super(DceRpcSocket, self).send(pkt, **kwargs)
2967
2968 def recv(self, x=None):
2969 pkt = super(DceRpcSocket, self).recv(x)
2970 if pkt is not None:
2971 return self.session.in_pkt(pkt)
2972
2973
2974# --- TODO cleanup below
2975
2976# Heuristically way to find the payload class
2977#
2978# To add a possible payload to a DCE/RPC packet, one must first create the
2979# packet class, then instead of binding layers using bind_layers, he must
2980# call DceRpcPayload.register_possible_payload() with the payload class as
2981# parameter.
2982#
2983# To be able to decide if the payload class is capable of handling the rest of
2984# the dissection, the classmethod can_handle() should be implemented in the
2985# payload class. This method is given the rest of the string to dissect as
2986# first argument, and the DceRpc packet instance as second argument. Based on
2987# this information, the method must return True if the class is capable of
2988# handling the dissection, False otherwise
2989
2990
2991class DceRpc4Payload(Packet):
2992 """Dummy class which use the dispatch_hook to find the payload class"""
2993
2994 _payload_class = []
2995
2996 @classmethod
2997 def dispatch_hook(cls, _pkt, _underlayer=None, *args, **kargs):
2998 """dispatch_hook to choose among different registered payloads"""
2999 for klass in cls._payload_class:
3000 if hasattr(klass, "can_handle") and klass.can_handle(_pkt, _underlayer):
3001 return klass
3002 print("DCE/RPC payload class not found or undefined (using Raw)")
3003 return Raw
3004
3005 @classmethod
3006 def register_possible_payload(cls, pay):
3007 """Method to call from possible DCE/RPC endpoint to register it as
3008 possible payload"""
3009 cls._payload_class.append(pay)
3010
3011
3012bind_layers(DceRpc4, DceRpc4Payload)