/impacket/dcerpc/v5/rpcrt.py

https://github.com/ropnop/impacket_static_binaries · Python · 1687 lines · 1450 code · 119 blank · 118 comment · 163 complexity · af5feeb32fae95e5e2cb56631e6781ff MD5 · raw file

Large files are truncated click here to view the full file

  1. # SECUREAUTH LABS. Copyright 2018 SecureAuth Corporation. All rights reserved.
  2. #
  3. # This software is provided under under a slightly modified version
  4. # of the Apache Software License. See the accompanying LICENSE file
  5. # for more information.
  6. #
  7. # Description:
  8. # Partial C706.pdf + [MS-RPCE] implementation
  9. #
  10. # Best way to learn how to use these calls is to grab the protocol standard
  11. # so you understand what the call does, and then read the test case located
  12. # at https://github.com/SecureAuthCorp/impacket/tree/master/tests/SMB_RPC
  13. #
  14. # ToDo:
  15. # [ ] Take out all the security provider stuff out of here (e.g. RPC_C_AUTHN_WINNT)
  16. # and put it elsewhere. This will make the coder cleaner and easier to add
  17. # more SSP (e.g. NETLOGON)
  18. #
  19. import logging
  20. import socket
  21. import sys
  22. from binascii import unhexlify
  23. from Cryptodome.Cipher import ARC4
  24. from impacket import ntlm, LOG
  25. from impacket.structure import Structure,pack,unpack
  26. from impacket.krb5 import kerberosv5, gssapi
  27. from impacket.uuid import uuidtup_to_bin, generate, stringver_to_bin, bin_to_uuidtup
  28. from impacket.dcerpc.v5.dtypes import UCHAR, ULONG, USHORT
  29. from impacket.dcerpc.v5.ndr import NDRSTRUCT
  30. from impacket import hresult_errors
  31. from threading import Thread
  32. # MS/RPC Constants
  33. MSRPC_REQUEST = 0x00
  34. MSRPC_PING = 0x01
  35. MSRPC_RESPONSE = 0x02
  36. MSRPC_FAULT = 0x03
  37. MSRPC_WORKING = 0x04
  38. MSRPC_NOCALL = 0x05
  39. MSRPC_REJECT = 0x06
  40. MSRPC_ACK = 0x07
  41. MSRPC_CL_CANCEL = 0x08
  42. MSRPC_FACK = 0x09
  43. MSRPC_CANCELACK = 0x0A
  44. MSRPC_BIND = 0x0B
  45. MSRPC_BINDACK = 0x0C
  46. MSRPC_BINDNAK = 0x0D
  47. MSRPC_ALTERCTX = 0x0E
  48. MSRPC_ALTERCTX_R= 0x0F
  49. MSRPC_AUTH3 = 0x10
  50. MSRPC_SHUTDOWN = 0x11
  51. MSRPC_CO_CANCEL = 0x12
  52. MSRPC_ORPHANED = 0x13
  53. MSRPC_RTS = 0x14
  54. # MS/RPC Packet Flags
  55. PFC_FIRST_FRAG = 0x01
  56. PFC_LAST_FRAG = 0x02
  57. # For PDU types bind, bind_ack, alter_context, and
  58. # alter_context_resp, this flag MUST be interpreted as PFC_SUPPORT_HEADER_SIGN
  59. MSRPC_SUPPORT_SIGN = 0x04
  60. #For the
  61. #remaining PDU types, this flag MUST be interpreted as PFC_PENDING_CANCEL.
  62. MSRPC_PENDING_CANCEL= 0x04
  63. PFC_RESERVED_1 = 0x08
  64. PFC_CONC_MPX = 0x10
  65. PFC_DID_NOT_EXECUTE = 0x20
  66. PFC_MAYBE = 0x40
  67. PFC_OBJECT_UUID = 0x80
  68. # Auth Types - Security Providers
  69. RPC_C_AUTHN_NONE = 0x00
  70. RPC_C_AUTHN_GSS_NEGOTIATE = 0x09
  71. RPC_C_AUTHN_WINNT = 0x0A
  72. RPC_C_AUTHN_GSS_SCHANNEL = 0x0E
  73. RPC_C_AUTHN_GSS_KERBEROS = 0x10
  74. RPC_C_AUTHN_NETLOGON = 0x44
  75. RPC_C_AUTHN_DEFAULT = 0xFF
  76. # Auth Levels
  77. RPC_C_AUTHN_LEVEL_NONE = 1
  78. RPC_C_AUTHN_LEVEL_CONNECT = 2
  79. RPC_C_AUTHN_LEVEL_CALL = 3
  80. RPC_C_AUTHN_LEVEL_PKT = 4
  81. RPC_C_AUTHN_LEVEL_PKT_INTEGRITY = 5
  82. RPC_C_AUTHN_LEVEL_PKT_PRIVACY = 6
  83. #Reasons for rejection of a context element, included in bind_ack result reason
  84. rpc_provider_reason = {
  85. 0 : 'reason_not_specified',
  86. 1 : 'abstract_syntax_not_supported',
  87. 2 : 'proposed_transfer_syntaxes_not_supported',
  88. 3 : 'local_limit_exceeded',
  89. 4 : 'protocol_version_not_specified',
  90. 8 : 'authentication_type_not_recognized',
  91. 9 : 'invalid_checksum'
  92. }
  93. MSRPC_CONT_RESULT_ACCEPT = 0
  94. MSRPC_CONT_RESULT_USER_REJECT = 1
  95. MSRPC_CONT_RESULT_PROV_REJECT = 2
  96. #Results of a presentation context negotiation
  97. rpc_cont_def_result = {
  98. 0 : 'acceptance',
  99. 1 : 'user_rejection',
  100. 2 : 'provider_rejection'
  101. }
  102. #status codes, references:
  103. #https://docs.microsoft.com/windows/desktop/Rpc/rpc-return-values
  104. #https://msdn.microsoft.com/library/default.asp?url=/library/en-us/randz/protocol/common_return_values.asp
  105. #winerror.h
  106. #https://www.opengroup.org/onlinepubs/9629399/apdxn.htm
  107. rpc_status_codes = {
  108. 0x00000005 : 'rpc_s_access_denied',
  109. 0x00000008 : 'Authentication type not recognized',
  110. 0x000006D8 : 'rpc_fault_cant_perform',
  111. 0x000006C6 : 'rpc_x_invalid_bound', # the arrays bound are invalid
  112. 0x000006E4 : 'rpc_s_cannot_support: The requested operation is not supported.', # some operation is not supported
  113. 0x000006F7 : 'rpc_x_bad_stub_data', # the stub data is invalid, doesn't match with the IDL definition
  114. 0x1C010001 : 'nca_s_comm_failure', # unable to get response from server:
  115. 0x1C010002 : 'nca_s_op_rng_error', # bad operation number in call
  116. 0x1C010003 : 'nca_s_unk_if', # unknown interface
  117. 0x1C010006 : 'nca_s_wrong_boot_time', # client passed server wrong server boot time
  118. 0x1C010009 : 'nca_s_you_crashed', # a restarted server called back a client
  119. 0x1C01000B : 'nca_s_proto_error', # someone messed up the protocol
  120. 0x1C010013 : 'nca_s_out_args_too_big ', # output args too big
  121. 0x1C010014 : 'nca_s_server_too_busy', # server is too busy to handle call
  122. 0x1C010015 : 'nca_s_fault_string_too_long', # string argument longer than declared max len
  123. 0x1C010017 : 'nca_s_unsupported_type ', # no implementation of generic operation for object
  124. 0x1C000001 : 'nca_s_fault_int_div_by_zero',
  125. 0x1C000002 : 'nca_s_fault_addr_error ',
  126. 0x1C000003 : 'nca_s_fault_fp_div_zero',
  127. 0x1C000004 : 'nca_s_fault_fp_underflow',
  128. 0x1C000005 : 'nca_s_fault_fp_overflow',
  129. 0x1C000006 : 'nca_s_fault_invalid_tag',
  130. 0x1C000007 : 'nca_s_fault_invalid_bound ',
  131. 0x1C000008 : 'nca_s_rpc_version_mismatch',
  132. 0x1C000009 : 'nca_s_unspec_reject ',
  133. 0x1C00000A : 'nca_s_bad_actid',
  134. 0x1C00000B : 'nca_s_who_are_you_failed',
  135. 0x1C00000C : 'nca_s_manager_not_entered ',
  136. 0x1C00000D : 'nca_s_fault_cancel',
  137. 0x1C00000E : 'nca_s_fault_ill_inst',
  138. 0x1C00000F : 'nca_s_fault_fp_error',
  139. 0x1C000010 : 'nca_s_fault_int_overflow',
  140. 0x1C000012 : 'nca_s_fault_unspec',
  141. 0x1C000013 : 'nca_s_fault_remote_comm_failure ',
  142. 0x1C000014 : 'nca_s_fault_pipe_empty ',
  143. 0x1C000015 : 'nca_s_fault_pipe_closed',
  144. 0x1C000016 : 'nca_s_fault_pipe_order ',
  145. 0x1C000017 : 'nca_s_fault_pipe_discipline',
  146. 0x1C000018 : 'nca_s_fault_pipe_comm_error',
  147. 0x1C000019 : 'nca_s_fault_pipe_memory',
  148. 0x1C00001A : 'nca_s_fault_context_mismatch ',
  149. 0x1C00001B : 'nca_s_fault_remote_no_memory ',
  150. 0x1C00001C : 'nca_s_invalid_pres_context_id',
  151. 0x1C00001D : 'nca_s_unsupported_authn_level',
  152. 0x1C00001F : 'nca_s_invalid_checksum ',
  153. 0x1C000020 : 'nca_s_invalid_crc',
  154. 0x1C000021 : 'nca_s_fault_user_defined',
  155. 0x1C000022 : 'nca_s_fault_tx_open_failed',
  156. 0x1C000023 : 'nca_s_fault_codeset_conv_error',
  157. 0x1C000024 : 'nca_s_fault_object_not_found ',
  158. 0x1C000025 : 'nca_s_fault_no_client_stub',
  159. 0x16c9a000 : "rpc_s_mod",
  160. 0x16c9a001 : "rpc_s_op_rng_error",
  161. 0x16c9a002 : "rpc_s_cant_create_socket",
  162. 0x16c9a003 : "rpc_s_cant_bind_socket",
  163. 0x16c9a004 : "rpc_s_not_in_call",
  164. 0x16c9a005 : "rpc_s_no_port",
  165. 0x16c9a006 : "rpc_s_wrong_boot_time",
  166. 0x16c9a007 : "rpc_s_too_many_sockets",
  167. 0x16c9a008 : "rpc_s_illegal_register",
  168. 0x16c9a009 : "rpc_s_cant_recv",
  169. 0x16c9a00a : "rpc_s_bad_pkt",
  170. 0x16c9a00b : "rpc_s_unbound_handle",
  171. 0x16c9a00c : "rpc_s_addr_in_use",
  172. 0x16c9a00d : "rpc_s_in_args_too_big",
  173. 0x16c9a00e : "rpc_s_string_too_long",
  174. 0x16c9a00f : "rpc_s_too_many_objects",
  175. 0x16c9a010 : "rpc_s_binding_has_no_auth",
  176. 0x16c9a011 : "rpc_s_unknown_authn_service",
  177. 0x16c9a012 : "rpc_s_no_memory",
  178. 0x16c9a013 : "rpc_s_cant_nmalloc",
  179. 0x16c9a014 : "rpc_s_call_faulted",
  180. 0x16c9a015 : "rpc_s_call_failed",
  181. 0x16c9a016 : "rpc_s_comm_failure",
  182. 0x16c9a017 : "rpc_s_rpcd_comm_failure",
  183. 0x16c9a018 : "rpc_s_illegal_family_rebind",
  184. 0x16c9a019 : "rpc_s_invalid_handle",
  185. 0x16c9a01a : "rpc_s_coding_error",
  186. 0x16c9a01b : "rpc_s_object_not_found",
  187. 0x16c9a01c : "rpc_s_cthread_not_found",
  188. 0x16c9a01d : "rpc_s_invalid_binding",
  189. 0x16c9a01e : "rpc_s_already_registered",
  190. 0x16c9a01f : "rpc_s_endpoint_not_found",
  191. 0x16c9a020 : "rpc_s_invalid_rpc_protseq",
  192. 0x16c9a021 : "rpc_s_desc_not_registered",
  193. 0x16c9a022 : "rpc_s_already_listening",
  194. 0x16c9a023 : "rpc_s_no_protseqs",
  195. 0x16c9a024 : "rpc_s_no_protseqs_registered",
  196. 0x16c9a025 : "rpc_s_no_bindings",
  197. 0x16c9a026 : "rpc_s_max_descs_exceeded",
  198. 0x16c9a027 : "rpc_s_no_interfaces",
  199. 0x16c9a028 : "rpc_s_invalid_timeout",
  200. 0x16c9a029 : "rpc_s_cant_inq_socket",
  201. 0x16c9a02a : "rpc_s_invalid_naf_id",
  202. 0x16c9a02b : "rpc_s_inval_net_addr",
  203. 0x16c9a02c : "rpc_s_unknown_if",
  204. 0x16c9a02d : "rpc_s_unsupported_type",
  205. 0x16c9a02e : "rpc_s_invalid_call_opt",
  206. 0x16c9a02f : "rpc_s_no_fault",
  207. 0x16c9a030 : "rpc_s_cancel_timeout",
  208. 0x16c9a031 : "rpc_s_call_cancelled",
  209. 0x16c9a032 : "rpc_s_invalid_call_handle",
  210. 0x16c9a033 : "rpc_s_cannot_alloc_assoc",
  211. 0x16c9a034 : "rpc_s_cannot_connect",
  212. 0x16c9a035 : "rpc_s_connection_aborted",
  213. 0x16c9a036 : "rpc_s_connection_closed",
  214. 0x16c9a037 : "rpc_s_cannot_accept",
  215. 0x16c9a038 : "rpc_s_assoc_grp_not_found",
  216. 0x16c9a039 : "rpc_s_stub_interface_error",
  217. 0x16c9a03a : "rpc_s_invalid_object",
  218. 0x16c9a03b : "rpc_s_invalid_type",
  219. 0x16c9a03c : "rpc_s_invalid_if_opnum",
  220. 0x16c9a03d : "rpc_s_different_server_instance",
  221. 0x16c9a03e : "rpc_s_protocol_error",
  222. 0x16c9a03f : "rpc_s_cant_recvmsg",
  223. 0x16c9a040 : "rpc_s_invalid_string_binding",
  224. 0x16c9a041 : "rpc_s_connect_timed_out",
  225. 0x16c9a042 : "rpc_s_connect_rejected",
  226. 0x16c9a043 : "rpc_s_network_unreachable",
  227. 0x16c9a044 : "rpc_s_connect_no_resources",
  228. 0x16c9a045 : "rpc_s_rem_network_shutdown",
  229. 0x16c9a046 : "rpc_s_too_many_rem_connects",
  230. 0x16c9a047 : "rpc_s_no_rem_endpoint",
  231. 0x16c9a048 : "rpc_s_rem_host_down",
  232. 0x16c9a049 : "rpc_s_host_unreachable",
  233. 0x16c9a04a : "rpc_s_access_control_info_inv",
  234. 0x16c9a04b : "rpc_s_loc_connect_aborted",
  235. 0x16c9a04c : "rpc_s_connect_closed_by_rem",
  236. 0x16c9a04d : "rpc_s_rem_host_crashed",
  237. 0x16c9a04e : "rpc_s_invalid_endpoint_format",
  238. 0x16c9a04f : "rpc_s_unknown_status_code",
  239. 0x16c9a050 : "rpc_s_unknown_mgr_type",
  240. 0x16c9a051 : "rpc_s_assoc_creation_failed",
  241. 0x16c9a052 : "rpc_s_assoc_grp_max_exceeded",
  242. 0x16c9a053 : "rpc_s_assoc_grp_alloc_failed",
  243. 0x16c9a054 : "rpc_s_sm_invalid_state",
  244. 0x16c9a055 : "rpc_s_assoc_req_rejected",
  245. 0x16c9a056 : "rpc_s_assoc_shutdown",
  246. 0x16c9a057 : "rpc_s_tsyntaxes_unsupported",
  247. 0x16c9a058 : "rpc_s_context_id_not_found",
  248. 0x16c9a059 : "rpc_s_cant_listen_socket",
  249. 0x16c9a05a : "rpc_s_no_addrs",
  250. 0x16c9a05b : "rpc_s_cant_getpeername",
  251. 0x16c9a05c : "rpc_s_cant_get_if_id",
  252. 0x16c9a05d : "rpc_s_protseq_not_supported",
  253. 0x16c9a05e : "rpc_s_call_orphaned",
  254. 0x16c9a05f : "rpc_s_who_are_you_failed",
  255. 0x16c9a060 : "rpc_s_unknown_reject",
  256. 0x16c9a061 : "rpc_s_type_already_registered",
  257. 0x16c9a062 : "rpc_s_stop_listening_disabled",
  258. 0x16c9a063 : "rpc_s_invalid_arg",
  259. 0x16c9a064 : "rpc_s_not_supported",
  260. 0x16c9a065 : "rpc_s_wrong_kind_of_binding",
  261. 0x16c9a066 : "rpc_s_authn_authz_mismatch",
  262. 0x16c9a067 : "rpc_s_call_queued",
  263. 0x16c9a068 : "rpc_s_cannot_set_nodelay",
  264. 0x16c9a069 : "rpc_s_not_rpc_tower",
  265. 0x16c9a06a : "rpc_s_invalid_rpc_protid",
  266. 0x16c9a06b : "rpc_s_invalid_rpc_floor",
  267. 0x16c9a06c : "rpc_s_call_timeout",
  268. 0x16c9a06d : "rpc_s_mgmt_op_disallowed",
  269. 0x16c9a06e : "rpc_s_manager_not_entered",
  270. 0x16c9a06f : "rpc_s_calls_too_large_for_wk_ep",
  271. 0x16c9a070 : "rpc_s_server_too_busy",
  272. 0x16c9a071 : "rpc_s_prot_version_mismatch",
  273. 0x16c9a072 : "rpc_s_rpc_prot_version_mismatch",
  274. 0x16c9a073 : "rpc_s_ss_no_import_cursor",
  275. 0x16c9a074 : "rpc_s_fault_addr_error",
  276. 0x16c9a075 : "rpc_s_fault_context_mismatch",
  277. 0x16c9a076 : "rpc_s_fault_fp_div_by_zero",
  278. 0x16c9a077 : "rpc_s_fault_fp_error",
  279. 0x16c9a078 : "rpc_s_fault_fp_overflow",
  280. 0x16c9a079 : "rpc_s_fault_fp_underflow",
  281. 0x16c9a07a : "rpc_s_fault_ill_inst",
  282. 0x16c9a07b : "rpc_s_fault_int_div_by_zero",
  283. 0x16c9a07c : "rpc_s_fault_int_overflow",
  284. 0x16c9a07d : "rpc_s_fault_invalid_bound",
  285. 0x16c9a07e : "rpc_s_fault_invalid_tag",
  286. 0x16c9a07f : "rpc_s_fault_pipe_closed",
  287. 0x16c9a080 : "rpc_s_fault_pipe_comm_error",
  288. 0x16c9a081 : "rpc_s_fault_pipe_discipline",
  289. 0x16c9a082 : "rpc_s_fault_pipe_empty",
  290. 0x16c9a083 : "rpc_s_fault_pipe_memory",
  291. 0x16c9a084 : "rpc_s_fault_pipe_order",
  292. 0x16c9a085 : "rpc_s_fault_remote_comm_failure",
  293. 0x16c9a086 : "rpc_s_fault_remote_no_memory",
  294. 0x16c9a087 : "rpc_s_fault_unspec",
  295. 0x16c9a088 : "uuid_s_bad_version",
  296. 0x16c9a089 : "uuid_s_socket_failure",
  297. 0x16c9a08a : "uuid_s_getconf_failure",
  298. 0x16c9a08b : "uuid_s_no_address",
  299. 0x16c9a08c : "uuid_s_overrun",
  300. 0x16c9a08d : "uuid_s_internal_error",
  301. 0x16c9a08e : "uuid_s_coding_error",
  302. 0x16c9a08f : "uuid_s_invalid_string_uuid",
  303. 0x16c9a090 : "uuid_s_no_memory",
  304. 0x16c9a091 : "rpc_s_no_more_entries",
  305. 0x16c9a092 : "rpc_s_unknown_ns_error",
  306. 0x16c9a093 : "rpc_s_name_service_unavailable",
  307. 0x16c9a094 : "rpc_s_incomplete_name",
  308. 0x16c9a095 : "rpc_s_group_not_found",
  309. 0x16c9a096 : "rpc_s_invalid_name_syntax",
  310. 0x16c9a097 : "rpc_s_no_more_members",
  311. 0x16c9a098 : "rpc_s_no_more_interfaces",
  312. 0x16c9a099 : "rpc_s_invalid_name_service",
  313. 0x16c9a09a : "rpc_s_no_name_mapping",
  314. 0x16c9a09b : "rpc_s_profile_not_found",
  315. 0x16c9a09c : "rpc_s_not_found",
  316. 0x16c9a09d : "rpc_s_no_updates",
  317. 0x16c9a09e : "rpc_s_update_failed",
  318. 0x16c9a09f : "rpc_s_no_match_exported",
  319. 0x16c9a0a0 : "rpc_s_entry_not_found",
  320. 0x16c9a0a1 : "rpc_s_invalid_inquiry_context",
  321. 0x16c9a0a2 : "rpc_s_interface_not_found",
  322. 0x16c9a0a3 : "rpc_s_group_member_not_found",
  323. 0x16c9a0a4 : "rpc_s_entry_already_exists",
  324. 0x16c9a0a5 : "rpc_s_nsinit_failure",
  325. 0x16c9a0a6 : "rpc_s_unsupported_name_syntax",
  326. 0x16c9a0a7 : "rpc_s_no_more_elements",
  327. 0x16c9a0a8 : "rpc_s_no_ns_permission",
  328. 0x16c9a0a9 : "rpc_s_invalid_inquiry_type",
  329. 0x16c9a0aa : "rpc_s_profile_element_not_found",
  330. 0x16c9a0ab : "rpc_s_profile_element_replaced",
  331. 0x16c9a0ac : "rpc_s_import_already_done",
  332. 0x16c9a0ad : "rpc_s_database_busy",
  333. 0x16c9a0ae : "rpc_s_invalid_import_context",
  334. 0x16c9a0af : "rpc_s_uuid_set_not_found",
  335. 0x16c9a0b0 : "rpc_s_uuid_member_not_found",
  336. 0x16c9a0b1 : "rpc_s_no_interfaces_exported",
  337. 0x16c9a0b2 : "rpc_s_tower_set_not_found",
  338. 0x16c9a0b3 : "rpc_s_tower_member_not_found",
  339. 0x16c9a0b4 : "rpc_s_obj_uuid_not_found",
  340. 0x16c9a0b5 : "rpc_s_no_more_bindings",
  341. 0x16c9a0b6 : "rpc_s_invalid_priority",
  342. 0x16c9a0b7 : "rpc_s_not_rpc_entry",
  343. 0x16c9a0b8 : "rpc_s_invalid_lookup_context",
  344. 0x16c9a0b9 : "rpc_s_binding_vector_full",
  345. 0x16c9a0ba : "rpc_s_cycle_detected",
  346. 0x16c9a0bb : "rpc_s_nothing_to_export",
  347. 0x16c9a0bc : "rpc_s_nothing_to_unexport",
  348. 0x16c9a0bd : "rpc_s_invalid_vers_option",
  349. 0x16c9a0be : "rpc_s_no_rpc_data",
  350. 0x16c9a0bf : "rpc_s_mbr_picked",
  351. 0x16c9a0c0 : "rpc_s_not_all_objs_unexported",
  352. 0x16c9a0c1 : "rpc_s_no_entry_name",
  353. 0x16c9a0c2 : "rpc_s_priority_group_done",
  354. 0x16c9a0c3 : "rpc_s_partial_results",
  355. 0x16c9a0c4 : "rpc_s_no_env_setup",
  356. 0x16c9a0c5 : "twr_s_unknown_sa",
  357. 0x16c9a0c6 : "twr_s_unknown_tower",
  358. 0x16c9a0c7 : "twr_s_not_implemented",
  359. 0x16c9a0c8 : "rpc_s_max_calls_too_small",
  360. 0x16c9a0c9 : "rpc_s_cthread_create_failed",
  361. 0x16c9a0ca : "rpc_s_cthread_pool_exists",
  362. 0x16c9a0cb : "rpc_s_cthread_no_such_pool",
  363. 0x16c9a0cc : "rpc_s_cthread_invoke_disabled",
  364. 0x16c9a0cd : "ept_s_cant_perform_op",
  365. 0x16c9a0ce : "ept_s_no_memory",
  366. 0x16c9a0cf : "ept_s_database_invalid",
  367. 0x16c9a0d0 : "ept_s_cant_create",
  368. 0x16c9a0d1 : "ept_s_cant_access",
  369. 0x16c9a0d2 : "ept_s_database_already_open",
  370. 0x16c9a0d3 : "ept_s_invalid_entry",
  371. 0x16c9a0d4 : "ept_s_update_failed",
  372. 0x16c9a0d5 : "ept_s_invalid_context",
  373. 0x16c9a0d6 : "ept_s_not_registered",
  374. 0x16c9a0d7 : "ept_s_server_unavailable",
  375. 0x16c9a0d8 : "rpc_s_underspecified_name",
  376. 0x16c9a0d9 : "rpc_s_invalid_ns_handle",
  377. 0x16c9a0da : "rpc_s_unknown_error",
  378. 0x16c9a0db : "rpc_s_ss_char_trans_open_fail",
  379. 0x16c9a0dc : "rpc_s_ss_char_trans_short_file",
  380. 0x16c9a0dd : "rpc_s_ss_context_damaged",
  381. 0x16c9a0de : "rpc_s_ss_in_null_context",
  382. 0x16c9a0df : "rpc_s_socket_failure",
  383. 0x16c9a0e0 : "rpc_s_unsupported_protect_level",
  384. 0x16c9a0e1 : "rpc_s_invalid_checksum",
  385. 0x16c9a0e2 : "rpc_s_invalid_credentials",
  386. 0x16c9a0e3 : "rpc_s_credentials_too_large",
  387. 0x16c9a0e4 : "rpc_s_call_id_not_found",
  388. 0x16c9a0e5 : "rpc_s_key_id_not_found",
  389. 0x16c9a0e6 : "rpc_s_auth_bad_integrity",
  390. 0x16c9a0e7 : "rpc_s_auth_tkt_expired",
  391. 0x16c9a0e8 : "rpc_s_auth_tkt_nyv",
  392. 0x16c9a0e9 : "rpc_s_auth_repeat",
  393. 0x16c9a0ea : "rpc_s_auth_not_us",
  394. 0x16c9a0eb : "rpc_s_auth_badmatch",
  395. 0x16c9a0ec : "rpc_s_auth_skew",
  396. 0x16c9a0ed : "rpc_s_auth_badaddr",
  397. 0x16c9a0ee : "rpc_s_auth_badversion",
  398. 0x16c9a0ef : "rpc_s_auth_msg_type",
  399. 0x16c9a0f0 : "rpc_s_auth_modified",
  400. 0x16c9a0f1 : "rpc_s_auth_badorder",
  401. 0x16c9a0f2 : "rpc_s_auth_badkeyver",
  402. 0x16c9a0f3 : "rpc_s_auth_nokey",
  403. 0x16c9a0f4 : "rpc_s_auth_mut_fail",
  404. 0x16c9a0f5 : "rpc_s_auth_baddirection",
  405. 0x16c9a0f6 : "rpc_s_auth_method",
  406. 0x16c9a0f7 : "rpc_s_auth_badseq",
  407. 0x16c9a0f8 : "rpc_s_auth_inapp_cksum",
  408. 0x16c9a0f9 : "rpc_s_auth_field_toolong",
  409. 0x16c9a0fa : "rpc_s_invalid_crc",
  410. 0x16c9a0fb : "rpc_s_binding_incomplete",
  411. 0x16c9a0fc : "rpc_s_key_func_not_allowed",
  412. 0x16c9a0fd : "rpc_s_unknown_stub_rtl_if_vers",
  413. 0x16c9a0fe : "rpc_s_unknown_ifspec_vers",
  414. 0x16c9a0ff : "rpc_s_proto_unsupp_by_auth",
  415. 0x16c9a100 : "rpc_s_authn_challenge_malformed",
  416. 0x16c9a101 : "rpc_s_protect_level_mismatch",
  417. 0x16c9a102 : "rpc_s_no_mepv",
  418. 0x16c9a103 : "rpc_s_stub_protocol_error",
  419. 0x16c9a104 : "rpc_s_class_version_mismatch",
  420. 0x16c9a105 : "rpc_s_helper_not_running",
  421. 0x16c9a106 : "rpc_s_helper_short_read",
  422. 0x16c9a107 : "rpc_s_helper_catatonic",
  423. 0x16c9a108 : "rpc_s_helper_aborted",
  424. 0x16c9a109 : "rpc_s_not_in_kernel",
  425. 0x16c9a10a : "rpc_s_helper_wrong_user",
  426. 0x16c9a10b : "rpc_s_helper_overflow",
  427. 0x16c9a10c : "rpc_s_dg_need_way_auth",
  428. 0x16c9a10d : "rpc_s_unsupported_auth_subtype",
  429. 0x16c9a10e : "rpc_s_wrong_pickle_type",
  430. 0x16c9a10f : "rpc_s_not_listening",
  431. 0x16c9a110 : "rpc_s_ss_bad_buffer",
  432. 0x16c9a111 : "rpc_s_ss_bad_es_action",
  433. 0x16c9a112 : "rpc_s_ss_wrong_es_version",
  434. 0x16c9a113 : "rpc_s_fault_user_defined",
  435. 0x16c9a114 : "rpc_s_ss_incompatible_codesets",
  436. 0x16c9a115 : "rpc_s_tx_not_in_transaction",
  437. 0x16c9a116 : "rpc_s_tx_open_failed",
  438. 0x16c9a117 : "rpc_s_partial_credentials",
  439. 0x16c9a118 : "rpc_s_ss_invalid_codeset_tag",
  440. 0x16c9a119 : "rpc_s_mgmt_bad_type",
  441. 0x16c9a11a : "rpc_s_ss_invalid_char_input",
  442. 0x16c9a11b : "rpc_s_ss_short_conv_buffer",
  443. 0x16c9a11c : "rpc_s_ss_iconv_error",
  444. 0x16c9a11d : "rpc_s_ss_no_compat_codeset",
  445. 0x16c9a11e : "rpc_s_ss_no_compat_charsets",
  446. 0x16c9a11f : "dce_cs_c_ok",
  447. 0x16c9a120 : "dce_cs_c_unknown",
  448. 0x16c9a121 : "dce_cs_c_notfound",
  449. 0x16c9a122 : "dce_cs_c_cannot_open_file",
  450. 0x16c9a123 : "dce_cs_c_cannot_read_file",
  451. 0x16c9a124 : "dce_cs_c_cannot_allocate_memory",
  452. 0x16c9a125 : "rpc_s_ss_cleanup_failed",
  453. 0x16c9a126 : "rpc_svc_desc_general",
  454. 0x16c9a127 : "rpc_svc_desc_mutex",
  455. 0x16c9a128 : "rpc_svc_desc_xmit",
  456. 0x16c9a129 : "rpc_svc_desc_recv",
  457. 0x16c9a12a : "rpc_svc_desc_dg_state",
  458. 0x16c9a12b : "rpc_svc_desc_cancel",
  459. 0x16c9a12c : "rpc_svc_desc_orphan",
  460. 0x16c9a12d : "rpc_svc_desc_cn_state",
  461. 0x16c9a12e : "rpc_svc_desc_cn_pkt",
  462. 0x16c9a12f : "rpc_svc_desc_pkt_quotas",
  463. 0x16c9a130 : "rpc_svc_desc_auth",
  464. 0x16c9a131 : "rpc_svc_desc_source",
  465. 0x16c9a132 : "rpc_svc_desc_stats",
  466. 0x16c9a133 : "rpc_svc_desc_mem",
  467. 0x16c9a134 : "rpc_svc_desc_mem_type",
  468. 0x16c9a135 : "rpc_svc_desc_dg_pktlog",
  469. 0x16c9a136 : "rpc_svc_desc_thread_id",
  470. 0x16c9a137 : "rpc_svc_desc_timestamp",
  471. 0x16c9a138 : "rpc_svc_desc_cn_errors",
  472. 0x16c9a139 : "rpc_svc_desc_conv_thread",
  473. 0x16c9a13a : "rpc_svc_desc_pid",
  474. 0x16c9a13b : "rpc_svc_desc_atfork",
  475. 0x16c9a13c : "rpc_svc_desc_cma_thread",
  476. 0x16c9a13d : "rpc_svc_desc_inherit",
  477. 0x16c9a13e : "rpc_svc_desc_dg_sockets",
  478. 0x16c9a13f : "rpc_svc_desc_timer",
  479. 0x16c9a140 : "rpc_svc_desc_threads",
  480. 0x16c9a141 : "rpc_svc_desc_server_call",
  481. 0x16c9a142 : "rpc_svc_desc_nsi",
  482. 0x16c9a143 : "rpc_svc_desc_dg_pkt",
  483. 0x16c9a144 : "rpc_m_cn_ill_state_trans_sa",
  484. 0x16c9a145 : "rpc_m_cn_ill_state_trans_ca",
  485. 0x16c9a146 : "rpc_m_cn_ill_state_trans_sg",
  486. 0x16c9a147 : "rpc_m_cn_ill_state_trans_cg",
  487. 0x16c9a148 : "rpc_m_cn_ill_state_trans_sr",
  488. 0x16c9a149 : "rpc_m_cn_ill_state_trans_cr",
  489. 0x16c9a14a : "rpc_m_bad_pkt_type",
  490. 0x16c9a14b : "rpc_m_prot_mismatch",
  491. 0x16c9a14c : "rpc_m_frag_toobig",
  492. 0x16c9a14d : "rpc_m_unsupp_stub_rtl_if",
  493. 0x16c9a14e : "rpc_m_unhandled_callstate",
  494. 0x16c9a14f : "rpc_m_call_failed",
  495. 0x16c9a150 : "rpc_m_call_failed_no_status",
  496. 0x16c9a151 : "rpc_m_call_failed_errno",
  497. 0x16c9a152 : "rpc_m_call_failed_s",
  498. 0x16c9a153 : "rpc_m_call_failed_c",
  499. 0x16c9a154 : "rpc_m_errmsg_toobig",
  500. 0x16c9a155 : "rpc_m_invalid_srchattr",
  501. 0x16c9a156 : "rpc_m_nts_not_found",
  502. 0x16c9a157 : "rpc_m_invalid_accbytcnt",
  503. 0x16c9a158 : "rpc_m_pre_v2_ifspec",
  504. 0x16c9a159 : "rpc_m_unk_ifspec",
  505. 0x16c9a15a : "rpc_m_recvbuf_toosmall",
  506. 0x16c9a15b : "rpc_m_unalign_authtrl",
  507. 0x16c9a15c : "rpc_m_unexpected_exc",
  508. 0x16c9a15d : "rpc_m_no_stub_data",
  509. 0x16c9a15e : "rpc_m_eventlist_full",
  510. 0x16c9a15f : "rpc_m_unk_sock_type",
  511. 0x16c9a160 : "rpc_m_unimp_call",
  512. 0x16c9a161 : "rpc_m_invalid_seqnum",
  513. 0x16c9a162 : "rpc_m_cant_create_uuid",
  514. 0x16c9a163 : "rpc_m_pre_v2_ss",
  515. 0x16c9a164 : "rpc_m_dgpkt_pool_corrupt",
  516. 0x16c9a165 : "rpc_m_dgpkt_bad_free",
  517. 0x16c9a166 : "rpc_m_lookaside_corrupt",
  518. 0x16c9a167 : "rpc_m_alloc_fail",
  519. 0x16c9a168 : "rpc_m_realloc_fail",
  520. 0x16c9a169 : "rpc_m_cant_open_file",
  521. 0x16c9a16a : "rpc_m_cant_read_addr",
  522. 0x16c9a16b : "rpc_svc_desc_libidl",
  523. 0x16c9a16c : "rpc_m_ctxrundown_nomem",
  524. 0x16c9a16d : "rpc_m_ctxrundown_exc",
  525. 0x16c9a16e : "rpc_s_fault_codeset_conv_error",
  526. 0x16c9a16f : "rpc_s_no_call_active",
  527. 0x16c9a170 : "rpc_s_cannot_support",
  528. 0x16c9a171 : "rpc_s_no_context_available",
  529. }
  530. class DCERPCException(Exception):
  531. """
  532. This is the exception every client should catch regardless of the underlying
  533. DCERPC Transport used.
  534. """
  535. def __init__(self, error_string=None, error_code=None, packet=None):
  536. """
  537. :param string error_string: A string you want to show explaining the exception. Otherwise the default ones will be used
  538. :param integer error_code: the error_code if we're using a dictionary with error's descriptions
  539. :param NDR packet: if successfully decoded, the NDR packet of the response call. This could probably have useful
  540. information
  541. """
  542. Exception.__init__(self)
  543. self.packet = packet
  544. self.error_string = error_string
  545. if packet is not None:
  546. try:
  547. self.error_code = packet['ErrorCode']
  548. except:
  549. self.error_code = error_code
  550. else:
  551. self.error_code = error_code
  552. def get_error_code( self ):
  553. return self.error_code
  554. def get_packet( self ):
  555. return self.packet
  556. def __str__( self ):
  557. key = self.error_code
  558. if self.error_string is not None:
  559. return self.error_string
  560. if key in rpc_status_codes:
  561. error_msg_short = rpc_status_codes[key]
  562. return 'DCERPC Runtime Error: code: 0x%x - %s ' % (self.error_code, error_msg_short)
  563. else:
  564. return 'DCERPC Runtime Error: unknown error code: 0x%x' % self.error_code
  565. # Context Item
  566. class CtxItem(Structure):
  567. structure = (
  568. ('ContextID','<H=0'),
  569. ('TransItems','B=0'),
  570. ('Pad','B=0'),
  571. ('AbstractSyntax','20s=""'),
  572. ('TransferSyntax','20s=""'),
  573. )
  574. class CtxItemResult(Structure):
  575. structure = (
  576. ('Result','<H=0'),
  577. ('Reason','<H=0'),
  578. ('TransferSyntax','20s=""'),
  579. )
  580. class SEC_TRAILER(Structure):
  581. commonHdr = (
  582. ('auth_type', 'B=10'),
  583. ('auth_level','B=0'),
  584. ('auth_pad_len','B=0'),
  585. ('auth_rsvrd','B=0'),
  586. ('auth_ctx_id','<L=747920'),
  587. )
  588. class MSRPCHeader(Structure):
  589. _SIZE = 16
  590. commonHdr = (
  591. ('ver_major','B=5'), # 0
  592. ('ver_minor','B=0'), # 1
  593. ('type','B=0'), # 2
  594. ('flags','B=0'), # 3
  595. ('representation','<L=0x10'), # 4
  596. ('frag_len','<H=self._SIZE+len(auth_data)+(16 if (self["flags"] & 0x80) > 0 else 0)+len(pduData)+len(pad)+len(sec_trailer)'), # 8
  597. ('auth_len','<H=len(auth_data)'), # 10
  598. ('call_id','<L=1'), # 12 <-- Common up to here (including this)
  599. )
  600. structure = (
  601. ('dataLen','_-pduData','self["frag_len"]-self["auth_len"]-self._SIZE-(8 if self["auth_len"] > 0 else 0)'),
  602. ('pduData',':'),
  603. ('_pad', '_-pad','(4 - ((self._SIZE + (16 if (self["flags"] & 0x80) > 0 else 0) + len(self["pduData"])) & 3) & 3)'),
  604. ('pad', ':'),
  605. ('_sec_trailer', '_-sec_trailer', '8 if self["auth_len"] > 0 else 0'),
  606. ('sec_trailer',':'),
  607. ('auth_dataLen','_-auth_data','self["auth_len"]'),
  608. ('auth_data',':'),
  609. )
  610. def __init__(self, data = None, alignment = 0):
  611. Structure.__init__(self,data, alignment)
  612. if data is None:
  613. self['ver_major'] = 5
  614. self['ver_minor'] = 0
  615. self['flags'] = PFC_FIRST_FRAG | PFC_LAST_FRAG
  616. self['type'] = MSRPC_REQUEST
  617. self.__frag_len_set = 0
  618. self['auth_len'] = 0
  619. self['pduData'] = b''
  620. self['auth_data'] = b''
  621. self['sec_trailer'] = b''
  622. self['pad'] = b''
  623. def get_header_size(self):
  624. return self._SIZE + (16 if (self["flags"] & PFC_OBJECT_UUID) > 0 else 0)
  625. def get_packet(self):
  626. if self['auth_data'] != b'':
  627. self['auth_len'] = len(self['auth_data'])
  628. # The sec_trailer structure MUST be 4-byte aligned with respect to
  629. # the beginning of the PDU. Padding octets MUST be used to align the
  630. # sec_trailer structure if its natural beginning is not already 4-byte aligned
  631. ##self['pad'] = '\xAA' * (4 - ((self._SIZE + len(self['pduData'])) & 3) & 3)
  632. return self.getData()
  633. class MSRPCRequestHeader(MSRPCHeader):
  634. _SIZE = 24
  635. commonHdr = MSRPCHeader.commonHdr + (
  636. ('alloc_hint','<L=0'), # 16
  637. ('ctx_id','<H=0'), # 20
  638. ('op_num','<H=0'), # 22
  639. ('_uuid','_-uuid','16 if self["flags"] & 0x80 > 0 else 0' ), # 22
  640. ('uuid',':'), # 22
  641. )
  642. def __init__(self, data = None, alignment = 0):
  643. MSRPCHeader.__init__(self, data, alignment)
  644. if data is None:
  645. self['type'] = MSRPC_REQUEST
  646. self['ctx_id'] = 0
  647. self['uuid'] = b''
  648. class MSRPCRespHeader(MSRPCHeader):
  649. _SIZE = 24
  650. commonHdr = MSRPCHeader.commonHdr + (
  651. ('alloc_hint','<L=0'), # 16
  652. ('ctx_id','<H=0'), # 20
  653. ('cancel_count','<B=0'), # 22
  654. ('padding','<B=0'), # 23
  655. )
  656. def __init__(self, aBuffer = None, alignment = 0):
  657. MSRPCHeader.__init__(self, aBuffer, alignment)
  658. if aBuffer is None:
  659. self['type'] = MSRPC_RESPONSE
  660. self['ctx_id'] = 0
  661. class MSRPCBind(Structure):
  662. _CTX_ITEM_LEN = len(CtxItem())
  663. structure = (
  664. ('max_tfrag','<H=4280'),
  665. ('max_rfrag','<H=4280'),
  666. ('assoc_group','<L=0'),
  667. ('ctx_num','B=0'),
  668. ('Reserved','B=0'),
  669. ('Reserved2','<H=0'),
  670. ('_ctx_items', '_-ctx_items', 'self["ctx_num"]*self._CTX_ITEM_LEN'),
  671. ('ctx_items',':'),
  672. )
  673. def __init__(self, data = None, alignment = 0):
  674. Structure.__init__(self, data, alignment)
  675. if data is None:
  676. self['max_tfrag'] = 4280
  677. self['max_rfrag'] = 4280
  678. self['assoc_group'] = 0
  679. self['ctx_num'] = 1
  680. self['ctx_items'] = b''
  681. self.__ctx_items = []
  682. def addCtxItem(self, item):
  683. self.__ctx_items.append(item)
  684. def getData(self):
  685. self['ctx_num'] = len(self.__ctx_items)
  686. for i in self.__ctx_items:
  687. self['ctx_items'] += i.getData()
  688. return Structure.getData(self)
  689. class MSRPCBindAck(MSRPCHeader):
  690. _SIZE = 26 # Up to SecondaryAddr
  691. _CTX_ITEM_LEN = len(CtxItemResult())
  692. structure = (
  693. ('max_tfrag','<H=0'),
  694. ('max_rfrag','<H=0'),
  695. ('assoc_group','<L=0'),
  696. ('SecondaryAddrLen','<H&SecondaryAddr'),
  697. ('SecondaryAddr','z'), # Optional if SecondaryAddrLen == 0
  698. ('PadLen','_-Pad','(4-((self["SecondaryAddrLen"]+self._SIZE) % 4))%4'),
  699. ('Pad',':'),
  700. ('ctx_num','B=0'),
  701. ('Reserved','B=0'),
  702. ('Reserved2','<H=0'),
  703. ('_ctx_items','_-ctx_items','self["ctx_num"]*self._CTX_ITEM_LEN'),
  704. ('ctx_items',':'),
  705. ('_sec_trailer', '_-sec_trailer', '8 if self["auth_len"] > 0 else 0'),
  706. ('sec_trailer',':'),
  707. ('auth_dataLen','_-auth_data','self["auth_len"]'),
  708. ('auth_data',':'),
  709. )
  710. def __init__(self, data = None, alignment = 0):
  711. self.__ctx_items = []
  712. MSRPCHeader.__init__(self,data,alignment)
  713. if data is None:
  714. self['Pad'] = b''
  715. self['ctx_items'] = b''
  716. self['sec_trailer'] = b''
  717. self['auth_data'] = b''
  718. def getCtxItems(self):
  719. return self.__ctx_items
  720. def getCtxItem(self,index):
  721. return self.__ctx_items[index-1]
  722. def fromString(self, data):
  723. Structure.fromString(self,data)
  724. # Parse the ctx_items
  725. data = self['ctx_items']
  726. for i in range(self['ctx_num']):
  727. item = CtxItemResult(data)
  728. self.__ctx_items.append(item)
  729. data = data[len(item):]
  730. class MSRPCBindNak(Structure):
  731. structure = (
  732. ('RejectedReason','<H=0'),
  733. ('SupportedVersions',':'),
  734. )
  735. def __init__(self, data = None, alignment = 0):
  736. Structure.__init__(self,data,alignment)
  737. if data is None:
  738. self['SupportedVersions'] = b''
  739. class DCERPC:
  740. # Standard NDR Representation
  741. NDRSyntax = uuidtup_to_bin(('8a885d04-1ceb-11c9-9fe8-08002b104860', '2.0'))
  742. # NDR 64
  743. NDR64Syntax = uuidtup_to_bin(('71710533-BEBA-4937-8319-B5DBEF9CCC36', '1.0'))
  744. transfer_syntax = NDRSyntax
  745. def __init__(self,transport):
  746. self._transport = transport
  747. self.set_ctx_id(0)
  748. self._max_user_frag = None
  749. self.set_default_max_fragment_size()
  750. self._ctx = None
  751. def get_rpc_transport(self):
  752. return self._transport
  753. def set_ctx_id(self, ctx_id):
  754. self._ctx = ctx_id
  755. def connect(self):
  756. return self._transport.connect()
  757. def disconnect(self):
  758. return self._transport.disconnect()
  759. def set_max_fragment_size(self, fragment_size):
  760. # -1 is default fragment size: 0 for v5, 1300 y pico for v4
  761. # 0 is don't fragment
  762. # other values are max fragment size
  763. if fragment_size == -1:
  764. self.set_default_max_fragment_size()
  765. else:
  766. self._max_user_frag = fragment_size
  767. def set_default_max_fragment_size(self):
  768. # default is 0: don'fragment. v4 will override this method
  769. self._max_user_frag = 0
  770. def send(self, data):
  771. raise RuntimeError ('virtual method. Not implemented in subclass')
  772. def recv(self):
  773. raise RuntimeError ('virtual method. Not implemented in subclass')
  774. def alter_ctx(self, newUID, bogus_binds=''):
  775. raise RuntimeError ('virtual method. Not implemented in subclass')
  776. def set_credentials(self, username, password, domain='', lmhash='', nthash='', aesKey='', TGT=None, TGS=None):
  777. pass
  778. def set_auth_level(self, auth_level):
  779. pass
  780. def set_auth_type(self, auth_type, callback=None):
  781. pass
  782. def get_idempotent(self):
  783. return 0
  784. def set_idempotent(self, flag):
  785. pass
  786. def call(self, function, body, uuid=None):
  787. if hasattr(body, 'getData'):
  788. return self.send(DCERPC_RawCall(function, body.getData(), uuid))
  789. else:
  790. return self.send(DCERPC_RawCall(function, body, uuid))
  791. def request(self, request, uuid=None, checkError=True):
  792. if self.transfer_syntax == self.NDR64Syntax:
  793. request.changeTransferSyntax(self.NDR64Syntax)
  794. isNDR64 = True
  795. else:
  796. isNDR64 = False
  797. self.call(request.opnum, request, uuid)
  798. answer = self.recv()
  799. __import__(request.__module__)
  800. module = sys.modules[request.__module__]
  801. respClass = getattr(module, request.__class__.__name__ + 'Response')
  802. if answer[-4:] != b'\x00\x00\x00\x00' and checkError is True:
  803. error_code = unpack('<L', answer[-4:])[0]
  804. if error_code in rpc_status_codes:
  805. # This is an error we can handle
  806. exception = DCERPCException(error_code = error_code)
  807. else:
  808. sessionErrorClass = getattr(module, 'DCERPCSessionError')
  809. try:
  810. # Try to unpack the answer, even if it is an error, it works most of the times
  811. response = respClass(answer, isNDR64 = isNDR64)
  812. except:
  813. # No luck :(
  814. exception = sessionErrorClass(error_code = error_code)
  815. else:
  816. exception = sessionErrorClass(packet = response, error_code = error_code)
  817. raise exception
  818. else:
  819. response = respClass(answer, isNDR64 = isNDR64)
  820. return response
  821. class DCERPC_v4(DCERPC):
  822. pass
  823. class DCERPC_v5(DCERPC):
  824. def __init__(self, transport):
  825. DCERPC.__init__(self, transport)
  826. self.__auth_level = RPC_C_AUTHN_LEVEL_NONE
  827. self.__auth_type = RPC_C_AUTHN_WINNT
  828. self.__auth_type_callback = None
  829. # Flags of the authenticated session. We will need them throughout the connection
  830. self.__auth_flags = 0
  831. self.__username = None
  832. self.__password = None
  833. self.__domain = ''
  834. self.__lmhash = ''
  835. self.__nthash = ''
  836. self.__aesKey = ''
  837. self.__TGT = None
  838. self.__TGS = None
  839. self.__clientSigningKey = b''
  840. self.__serverSigningKey = b''
  841. self.__clientSealingKey = b''
  842. self.__clientSealingHandle = b''
  843. self.__serverSealingKey = b''
  844. self.__serverSealingHandle = b''
  845. self.__sequence = 0
  846. self.transfer_syntax = uuidtup_to_bin(('8a885d04-1ceb-11c9-9fe8-08002b104860', '2.0'))
  847. self.__callid = 1
  848. self._ctx = 0
  849. self.__sessionKey = None
  850. self.__max_xmit_size = 0
  851. self.__flags = 0
  852. self.__cipher = None
  853. self.__confounder = b''
  854. self.__gss = None
  855. def set_session_key(self, session_key):
  856. self.__sessionKey = session_key
  857. def get_session_key(self):
  858. return self.__sessionKey
  859. def set_auth_level(self, auth_level):
  860. self.__auth_level = auth_level
  861. def set_auth_type(self, auth_type, callback = None):
  862. self.__auth_type = auth_type
  863. self.__auth_type_callback = callback
  864. def get_auth_type(self):
  865. return self.__auth_type
  866. def set_max_tfrag(self, size):
  867. self.__max_xmit_size = size
  868. def get_credentials(self):
  869. return self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash, self.__aesKey, self.__TGT, self.__TGS
  870. def set_credentials(self, username, password, domain = '', lmhash = '', nthash = '', aesKey = '', TGT = None, TGS = None):
  871. self.set_auth_level(RPC_C_AUTHN_LEVEL_CONNECT)
  872. self.__username = username
  873. self.__password = password
  874. self.__domain = domain
  875. self.__aesKey = aesKey
  876. self.__TGT = TGT
  877. self.__TGS = TGS
  878. if lmhash != '' or nthash != '':
  879. if len(lmhash) % 2:
  880. lmhash = '0%s' % lmhash
  881. if len(nthash) % 2:
  882. nthash = '0%s' % nthash
  883. try: # just in case they were converted already
  884. self.__lmhash = unhexlify(lmhash)
  885. self.__nthash = unhexlify(nthash)
  886. except:
  887. self.__lmhash = lmhash
  888. self.__nthash = nthash
  889. pass
  890. def bind(self, iface_uuid, alter = 0, bogus_binds = 0, transfer_syntax = ('8a885d04-1ceb-11c9-9fe8-08002b104860', '2.0')):
  891. bind = MSRPCBind()
  892. #item['TransferSyntax']['Version'] = 1
  893. ctx = self._ctx
  894. for i in range(bogus_binds):
  895. item = CtxItem()
  896. item['ContextID'] = ctx
  897. item['TransItems'] = 1
  898. item['ContextID'] = ctx
  899. # We generate random UUIDs for bogus binds
  900. item['AbstractSyntax'] = generate() + stringver_to_bin('2.0')
  901. item['TransferSyntax'] = uuidtup_to_bin(transfer_syntax)
  902. bind.addCtxItem(item)
  903. self._ctx += 1
  904. ctx += 1
  905. # The true one :)
  906. item = CtxItem()
  907. item['AbstractSyntax'] = iface_uuid
  908. item['TransferSyntax'] = uuidtup_to_bin(transfer_syntax)
  909. item['ContextID'] = ctx
  910. item['TransItems'] = 1
  911. bind.addCtxItem(item)
  912. packet = MSRPCHeader()
  913. packet['type'] = MSRPC_BIND
  914. packet['pduData'] = bind.getData()
  915. packet['call_id'] = self.__callid
  916. if alter:
  917. packet['type'] = MSRPC_ALTERCTX
  918. if self.__auth_level != RPC_C_AUTHN_LEVEL_NONE:
  919. if (self.__username is None) or (self.__password is None):
  920. self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash, self.__aesKey, self.__TGT, self.__TGS = self._transport.get_credentials()
  921. if self.__auth_type == RPC_C_AUTHN_WINNT:
  922. auth = ntlm.getNTLMSSPType1('', '', signingRequired=True,
  923. use_ntlmv2=self._transport.doesSupportNTLMv2())
  924. elif self.__auth_type == RPC_C_AUTHN_NETLOGON:
  925. from impacket.dcerpc.v5 import nrpc
  926. auth = nrpc.getSSPType1(self.__username[:-1], self.__domain, signingRequired=True)
  927. elif self.__auth_type == RPC_C_AUTHN_GSS_NEGOTIATE:
  928. self.__cipher, self.__sessionKey, auth = kerberosv5.getKerberosType1(self.__username, self.__password,
  929. self.__domain, self.__lmhash,
  930. self.__nthash, self.__aesKey,
  931. self.__TGT, self.__TGS,
  932. self._transport.getRemoteName(),
  933. self._transport.get_kdcHost())
  934. else:
  935. raise DCERPCException('Unsupported auth_type 0x%x' % self.__auth_type)
  936. sec_trailer = SEC_TRAILER()
  937. sec_trailer['auth_type'] = self.__auth_type
  938. sec_trailer['auth_level'] = self.__auth_level
  939. sec_trailer['auth_ctx_id'] = self._ctx + 79231
  940. pad = (4 - (len(packet.get_packet()) % 4)) % 4
  941. if pad != 0:
  942. packet['pduData'] += b'\xFF'*pad
  943. sec_trailer['auth_pad_len']=pad
  944. packet['sec_trailer'] = sec_trailer
  945. packet['auth_data'] = auth
  946. self._transport.send(packet.get_packet())
  947. s = self._transport.recv()
  948. if s != 0:
  949. resp = MSRPCHeader(s)
  950. else:
  951. return 0 #mmm why not None?
  952. if resp['type'] == MSRPC_BINDACK or resp['type'] == MSRPC_ALTERCTX_R:
  953. bindResp = MSRPCBindAck(resp.getData())
  954. elif resp['type'] == MSRPC_BINDNAK or resp['type'] == MSRPC_FAULT:
  955. if resp['type'] == MSRPC_FAULT:
  956. resp = MSRPCRespHeader(resp.getData())
  957. status_code = unpack('<L', resp['pduData'][:4])[0]
  958. else:
  959. resp = MSRPCBindNak(resp['pduData'])
  960. status_code = resp['RejectedReason']
  961. if status_code in rpc_status_codes:
  962. raise DCERPCException(error_code = status_code)
  963. elif status_code in rpc_provider_reason:
  964. raise DCERPCException("Bind context rejected: %s" % rpc_provider_reason[status_code])
  965. else:
  966. raise DCERPCException('Unknown DCE RPC fault status code: %.8x' % status_code)
  967. else:
  968. raise DCERPCException('Unknown DCE RPC packet type received: %d' % resp['type'])
  969. # check ack results for each context, except for the bogus ones
  970. for ctx in range(bogus_binds+1,bindResp['ctx_num']+1):
  971. ctxItems = bindResp.getCtxItem(ctx)
  972. if ctxItems['Result'] != 0:
  973. msg = "Bind context %d rejected: " % ctx
  974. msg += rpc_cont_def_result.get(ctxItems['Result'], 'Unknown DCE RPC context result code: %.4x' % ctxItems['Result'])
  975. msg += "; "
  976. reason = bindResp.getCtxItem(ctx)['Reason']
  977. msg += rpc_provider_reason.get(reason, 'Unknown reason code: %.4x' % reason)
  978. if (ctxItems['Result'], reason) == (2, 1): # provider_rejection, abstract syntax not supported
  979. msg += " (this usually means the interface isn't listening on the given endpoint)"
  980. raise DCERPCException(msg)
  981. # Save the transfer syntax for later use
  982. self.transfer_syntax = ctxItems['TransferSyntax']
  983. # The received transmit size becomes the client's receive size, and the received receive size becomes the client's transmit size.
  984. self.__max_xmit_size = bindResp['max_rfrag']
  985. if self.__auth_level != RPC_C_AUTHN_LEVEL_NONE:
  986. if self.__auth_type == RPC_C_AUTHN_WINNT:
  987. response, self.__sessionKey = ntlm.getNTLMSSPType3(auth, bindResp['auth_data'], self.__username,
  988. self.__password, self.__domain, self.__lmhash,
  989. self.__nthash,
  990. use_ntlmv2=self._transport.doesSupportNTLMv2())
  991. self.__flags = response['flags']
  992. elif self.__auth_type == RPC_C_AUTHN_NETLOGON:
  993. response = None
  994. elif self.__auth_type == RPC_C_AUTHN_GSS_NEGOTIATE:
  995. self.__cipher, self.__sessionKey, response = kerberosv5.getKerberosType3(self.__cipher,
  996. self.__sessionKey,
  997. bindResp['auth_data'])
  998. self.__sequence = 0
  999. if self.__auth_level in (RPC_C_AUTHN_LEVEL_CONNECT, RPC_C_AUTHN_LEVEL_PKT_INTEGRITY, RPC_C_AUTHN_LEVEL_PKT_PRIVACY):
  1000. if self.__auth_type == RPC_C_AUTHN_WINNT:
  1001. if self.__flags & ntlm.NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY:
  1002. self.__clientSigningKey = ntlm.SIGNKEY(self.__flags, self.__sessionKey)
  1003. self.__serverSigningKey = ntlm.SIGNKEY(self.__flags, self.__sessionKey,b"Server")
  1004. self.__clientSealingKey = ntlm.SEALKEY(self.__flags, self.__sessionKey)
  1005. self.__serverSealingKey = ntlm.SEALKEY(self.__flags, self.__sessionKey,b"Server")
  1006. # Preparing the keys handle states
  1007. cipher3 = ARC4.new(self.__clientSealingKey)
  1008. self.__clientSealingHandle = cipher3.encrypt
  1009. cipher4 = ARC4.new(self.__serverSealingKey)
  1010. self.__serverSealingHandle = cipher4.encrypt
  1011. else:
  1012. # Same key for everything
  1013. self.__clientSigningKey = self.__sessionKey
  1014. self.__serverSigningKey = self.__sessionKey
  1015. self.__clientSealingKey = self.__sessionKey
  1016. self.__serverSealingKey = self.__sessionKey
  1017. cipher = ARC4.new(self.__clientSigningKey)
  1018. self.__clientSealingHandle = cipher.encrypt
  1019. self.__serverSealingHandle = cipher.encrypt
  1020. elif self.__auth_type == RPC_C_AUTHN_NETLOGON:
  1021. if self.__auth_level == RPC_C_AUTHN_LEVEL_PKT_INTEGRITY:
  1022. self.__confounder = b''
  1023. else:
  1024. self.__confounder = b'12345678'
  1025. sec_trailer = SEC_TRAILER()
  1026. sec_trailer['auth_type'] = self.__auth_type
  1027. sec_trailer['auth_level'] = self.__auth_level
  1028. sec_trailer['auth_ctx_id'] = self._ctx + 79231
  1029. if response is not None:
  1030. if self.__auth_type == RPC_C_AUTHN_GSS_NEGOTIATE:
  1031. alter_ctx = MSRPCHeader()
  1032. alter_ctx['type'] = MSRPC_ALTERCTX
  1033. alter_ctx['pduData'] = bind.getData()
  1034. alter_ctx['sec_trailer'] = sec_trailer
  1035. alter_ctx['auth_data'] = response
  1036. self._transport.send(alter_ctx.get_packet(), forceWriteAndx = 1)
  1037. self.__gss = gssapi.GSSAPI(self.__cipher)
  1038. self.__sequence = 0
  1039. self.recv()
  1040. self.__sequence = 0
  1041. else:
  1042. auth3 = MSRPCHeader()
  1043. auth3['type'] = MSRPC_AUTH3
  1044. # pad (4 bytes): Can be set to any arbitrary value when set and MUST be
  1045. # ignored on receipt. The pad field MUST be immediately followed by a
  1046. # sec_trailer structure whose layout, location, and alignment are as
  1047. # specified in section 2.2.2.11
  1048. auth3['pduData'] = b' '
  1049. auth3['sec_trailer'] = sec_trailer
  1050. auth3['auth_data'] = response.getData()
  1051. # Use the same call_id
  1052. self.__callid = resp['call_id']
  1053. auth3['call_id'] = self.__callid
  1054. self._transport.send(auth3.get_packet(), forceWriteAndx = 1)
  1055. self.__callid += 1
  1056. return resp # means packet is signed, if verifier is wrong it fails
  1057. def _transport_send(self, rpc_packet, forceWriteAndx = 0, forceRecv = 0):
  1058. rpc_packet['ctx_id'] = self._ctx
  1059. rpc_packet['sec_trailer'] = b''
  1060. rpc_packet['auth_data'] = b''
  1061. if self.__auth_level in [RPC_C_AUTHN_LEVEL_PKT_INTEGRITY, RPC_C_AUTHN_LEVEL_PKT_PRIVACY]:
  1062. # Dummy verifier, just for the calculations
  1063. sec_trailer = SEC_TRAILER()
  1064. sec_trailer['auth_type'] = self.__auth_type
  1065. sec_trailer['auth_level'] = self.__auth_level
  1066. sec_trailer['auth_pad_len'] = 0
  1067. sec_trailer['auth_ctx_id'] = self._ctx + 79231
  1068. pad = (4 - (len(rpc_packet.get_packet()) % 4)) % 4
  1069. if pad != 0:
  1070. rpc_packet['pduData'] += b'\xBB'*pad
  1071. sec_trailer['auth_pad_len']=pad
  1072. rpc_packet['sec_trailer'] = sec_trailer.getData()
  1073. rpc_packet['auth_data'] = b' '*16
  1074. plain_data = rpc_packet['pduData']
  1075. if self.__auth_level == RPC_C_AUTHN_LEVEL_PKT_PRIVACY:
  1076. if self.__auth_type == RPC_C_AUTHN_WINNT:
  1077. if self.__flags & ntlm.NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY:
  1078. # When NTLM2 is on, we sign the whole pdu, but encrypt just
  1079. # the data, not the dcerpc header. Weird..
  1080. sealedMessage, signature = ntlm.SEAL(self.__flags,
  1081. self.__clientSigningKey,
  1082. self.__clientSealingKey,
  1083. rpc_packet.get_packet()[:-16],
  1084. plain_data,
  1085. self.__sequence,
  1086. self.__clientSealingHandle)
  1087. else:
  1088. sealedMessage, signature = ntlm.SEAL(self.__flags,
  1089. self.__clientSigningKey,
  1090. self.__clientSealingKey,
  1091. plain_data,
  1092. plain_data,
  1093. self.__sequence,
  1094. self.__clientSealingHandle)
  1095. elif self.__auth_type == RPC_C_AUTHN_NETLOGON:
  1096. from impacket.dcerpc.v5 import nrpc
  1097. sea