1c5100b629c3f02e510faf9fec3776bd1e2e427c
[samba.git] / source4 / scripting / devel / repl_cleartext_pwd.py
1 #!/usr/bin/env python
2 #
3 # Copyright Stefan Metzmacher 2011-2012
4 #
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 #
18 # This is useful to sync passwords from an AD domain.
19 #
20 #  $
21 #  $ source4/scripting/devel/repl_cleartext_pwd.py \
22 #       -Uadministrator%A1b2C3d4 \
23 #       172.31.9.219 DC=bla,DC=base /tmp/cookie cleartext_utf8 131085 displayName
24 #  # starting at usn[0]
25 #  dn: CN=Test User1,CN=Users,DC=bla,DC=base
26 #  cleartext_utf8: A1b2C3d4
27 #  displayName:: VABlAHMAdAAgAFUAcwBlAHIAMQA=
28 #
29 #  # up to usn[16449]
30 #  $
31 #  $ source4/scripting/devel/repl_cleartext_pwd.py \
32 #       -Uadministrator%A1b2C3d4
33 #       172.31.9.219 DC=bla,DC=base cookie_file cleartext_utf8 131085 displayName
34 #  # starting at usn[16449]
35 #  # up to usn[16449]
36 #  $
37 #
38
39 from __future__ import print_function
40 import sys
41
42 # Find right direction when running from source tree
43 sys.path.insert(0, "bin/python")
44
45 import samba.getopt as options
46 from optparse import OptionParser
47
48 from samba.dcerpc import drsuapi, drsblobs, misc
49 from samba.ndr import ndr_pack, ndr_unpack, ndr_print
50
51 import binascii
52 import hashlib
53 import Crypto.Cipher.ARC4
54 import struct
55 import os
56
57 from ldif import LDIFWriter
58
59 class globals:
60     def __init__(self):
61         self.global_objs = {}
62         self.ldif = LDIFWriter(sys.stdout)
63
64     def add_attr(self, dn, attname, vals):
65         if dn not in self.global_objs:
66             self.global_objs[dn] = {}
67         self.global_objs[dn][attname] = vals
68
69     def print_all(self):
70         for dn, obj in self.global_objs.items():
71             self.ldif.unparse(dn, obj)
72             continue
73         self.global_objs = {}
74
75 def attid_equal(a1, a2):
76     return (a1 & 0xffffffff) == (a2 & 0xffffffff)
77
78 ########### main code ###########
79 if __name__ == "__main__":
80     parser = OptionParser("repl_cleartext_pwd.py [options] server dn cookie_file clear_utf8_name [attid attname attmode] [clear_utf16_name")
81     sambaopts = options.SambaOptions(parser)
82     credopts = options.CredentialsOptions(parser)
83     parser.add_option_group(credopts)
84
85     (opts, args) = parser.parse_args()
86
87     if len(args) == 4:
88         pass
89     elif len(args) == 7:
90         pass
91     elif len(args) >= 8:
92         pass
93     else:
94         parser.error("more arguments required - given=%d" % (len(args)))
95
96     server = args[0]
97     dn = args[1]
98     cookie_file = args[2]
99     if len(cookie_file) == 0:
100         cookie_file = None
101     clear_utf8_name = args[3]
102     if len(args) >= 7:
103         try:
104             attid = int(args[4], 16)
105         except Exception:
106             attid = int(args[4])
107         attname = args[5]
108         attmode = args[6]
109         if attmode not in ["raw", "utf8"]:
110             parser.error("attmode should be 'raw' or 'utf8'")
111     else:
112         attid = -1
113         attname = None
114         attmode = "raw"
115     if len(args) >= 8:
116         clear_utf16_name = args[7]
117     else:
118         clear_utf16_name = None
119
120     lp = sambaopts.get_loadparm()
121     creds = credopts.get_credentials(lp)
122
123     if not creds.authentication_requested():
124         parser.error("You must supply credentials")
125
126     gls = globals()
127     try:
128         f = open(cookie_file, 'r')
129         store_blob = f.read()
130         f.close()
131
132         store_hdr = store_blob[0:28]
133         (store_version, \
134          store_dn_len, store_dn_ofs, \
135          store_hwm_len, store_hwm_ofs, \
136          store_utdv_len, store_utdv_ofs) = \
137         struct.unpack("<LLLLLLL", store_hdr)
138
139         store_dn = store_blob[store_dn_ofs:store_dn_ofs + store_dn_len]
140         store_hwm_blob = store_blob[store_hwm_ofs:store_hwm_ofs + store_hwm_len]
141         store_utdv_blob = store_blob[store_utdv_ofs:store_utdv_ofs + store_utdv_len]
142
143         store_hwm = ndr_unpack(drsuapi.DsReplicaHighWaterMark, store_hwm_blob)
144         store_utdv = ndr_unpack(drsblobs.replUpToDateVectorBlob, store_utdv_blob)
145
146         assert store_dn == dn
147         #print "%s" % ndr_print(store_hwm)
148         #print "%s" % ndr_print(store_utdv)
149     except Exception:
150         store_dn = dn
151         store_hwm = drsuapi.DsReplicaHighWaterMark()
152         store_hwm.tmp_highest_usn  = 0
153         store_hwm.reserved_usn     = 0
154         store_hwm.highest_usn      = 0
155         store_utdv = None
156
157     binding_str = "ncacn_ip_tcp:%s[spnego,seal]" % server
158
159     drs_conn = drsuapi.drsuapi(binding_str, lp, creds)
160
161     bind_info = drsuapi.DsBindInfoCtr()
162     bind_info.length = 28
163     bind_info.info = drsuapi.DsBindInfo28()
164     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_BASE
165     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_ASYNC_REPLICATION
166     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_REMOVEAPI
167     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_MOVEREQ_V2
168     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_GETCHG_COMPRESS
169     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_DCINFO_V1
170     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_RESTORE_USN_OPTIMIZATION
171     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_KCC_EXECUTE
172     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_ADDENTRY_V2
173     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_LINKED_VALUE_REPLICATION
174     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_DCINFO_V2
175     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_INSTANCE_TYPE_NOT_REQ_ON_MOD
176     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_CRYPTO_BIND
177     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_GET_REPL_INFO
178     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_STRONG_ENCRYPTION
179     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_DCINFO_V01
180     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_TRANSITIVE_MEMBERSHIP
181     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_ADD_SID_HISTORY
182     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_POST_BETA3
183     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_GET_MEMBERSHIPS2
184     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_GETCHGREQ_V6
185     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_NONDOMAIN_NCS
186     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_GETCHGREQ_V8
187     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_GETCHGREPLY_V5
188     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_GETCHGREPLY_V6
189     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_ADDENTRYREPLY_V3
190     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_GETCHGREPLY_V7
191     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_VERIFY_OBJECT
192     (info, drs_handle) = drs_conn.DsBind(misc.GUID(drsuapi.DRSUAPI_DS_BIND_GUID), bind_info)
193
194     null_guid = misc.GUID()
195
196     naming_context = drsuapi.DsReplicaObjectIdentifier()
197     naming_context.dn              = dn
198     highwatermark                  = store_hwm
199     uptodateness_vector            = None
200     if store_utdv is not None:
201         uptodateness_vector = drsuapi.DsReplicaCursorCtrEx()
202         if store_utdv.version == 1:
203             uptodateness_vector.cursors = store_utdv.cursors
204         elif store_utdv.version == 2:
205             cursors = []
206             for i in range(0, store_utdv.ctr.count):
207                 cursor = drsuapi.DsReplicaCursor()
208                 cursor.source_dsa_invocation_id = store_utdv.ctr.cursors[i].source_dsa_invocation_id
209                 cursor.highest_usn = store_utdv.ctr.cursors[i].highest_usn
210                 cursors.append(cursor)
211             uptodateness_vector.cursors = cursors
212
213     req8 = drsuapi.DsGetNCChangesRequest8()
214
215     req8.destination_dsa_guid           = null_guid
216     req8.source_dsa_invocation_id       = null_guid
217     req8.naming_context                 = naming_context
218     req8.highwatermark                  = highwatermark
219     req8.uptodateness_vector            = uptodateness_vector
220     req8.replica_flags                  = (drsuapi.DRSUAPI_DRS_INIT_SYNC |
221                                            drsuapi.DRSUAPI_DRS_PER_SYNC |
222                                            drsuapi.DRSUAPI_DRS_GET_ANC |
223                                            drsuapi.DRSUAPI_DRS_NEVER_SYNCED |
224                                            drsuapi.DRSUAPI_DRS_WRIT_REP)
225     req8.max_object_count = 402
226     req8.max_ndr_size = 402116
227     req8.extended_op = 0
228     req8.fsmo_info = 0
229     req8.partial_attribute_set = None
230     req8.partial_attribute_set_ex = None
231     req8.mapping_ctr.num_mappings = 0
232     req8.mapping_ctr.mappings = None
233
234     user_session_key = drs_conn.user_session_key
235
236     print("# starting at usn[%d]" % (highwatermark.highest_usn))
237
238     while True:
239         (level, ctr) = drs_conn.DsGetNCChanges(drs_handle, 8, req8)
240         if ctr.first_object == None and ctr.object_count != 0:
241             raise RuntimeError("DsGetNCChanges: NULL first_object with object_count=%u" % (ctr.object_count))
242
243         obj_item = ctr.first_object
244         while obj_item is not None:
245             obj = obj_item.object
246
247             if obj.identifier is None:
248                 obj_item = obj_item.next_object
249                 continue
250
251             #print '%s' % obj.identifier.dn
252
253             is_deleted = False
254             for i in range(0, obj.attribute_ctr.num_attributes):
255                 attr = obj.attribute_ctr.attributes[i]
256                 if attid_equal(attr.attid, drsuapi.DRSUAPI_ATTID_isDeleted):
257                     is_deleted = True
258             if is_deleted:
259                 obj_item = obj_item.next_object
260                 continue
261
262             spl_crypt = None
263             attvals = None
264             for i in range(0, obj.attribute_ctr.num_attributes):
265                 attr = obj.attribute_ctr.attributes[i]
266                 if attid_equal(attr.attid, attid):
267                     attvals = []
268                     for j in range(0, attr.value_ctr.num_values):
269                         assert attr.value_ctr.values[j].blob is not None
270                         val_raw = attr.value_ctr.values[j].blob
271                         val = None
272                         if attmode == "utf8":
273                             val_unicode = unicode(val_raw, 'utf-16-le')
274                             val = val_unicode.encode('utf-8')
275                         elif attmode == "raw":
276                             val = val_raw
277                         else:
278                             assert False, "attmode[%s]" % attmode
279                         attvals.append(val)
280                 if not attid_equal(attr.attid, drsuapi.DRSUAPI_ATTID_supplementalCredentials):
281                     continue
282                 assert attr.value_ctr.num_values <= 1
283                 if attr.value_ctr.num_values == 0:
284                     break
285                 assert attr.value_ctr.values[0].blob is not None
286                 spl_crypt = attr.value_ctr.values[0].blob
287
288             if spl_crypt is None:
289                 obj_item = obj_item.next_object
290                 continue
291
292             assert len(spl_crypt) >= 20
293             confounder = spl_crypt[0:16]
294             enc_buffer = spl_crypt[16:]
295
296             m5 = hashlib.md5()
297             m5.update(user_session_key)
298             m5.update(confounder)
299             enc_key = m5.digest()
300
301             rc4 = Crypto.Cipher.ARC4.new(enc_key)
302             plain_buffer = rc4.decrypt(enc_buffer)
303
304             (crc32_v) = struct.unpack("<L", plain_buffer[0:4])
305             attr_val = plain_buffer[4:]
306             crc32_c = binascii.crc32(attr_val) & 0xffffffff
307             assert int(crc32_v[0]) == int(crc32_c), "CRC32 0x%08X != 0x%08X" % (crc32_v[0], crc32_c)
308
309             spl = ndr_unpack(drsblobs.supplementalCredentialsBlob, attr_val)
310
311             #print '%s' % ndr_print(spl)
312
313             cleartext_hex = None
314
315             for i in range(0, spl.sub.num_packages):
316                 pkg = spl.sub.packages[i]
317                 if pkg.name != "Primary:CLEARTEXT":
318                     continue
319                 cleartext_hex = pkg.data
320
321             if cleartext_hex is not None:
322                 cleartext_utf16 = binascii.a2b_hex(cleartext_hex)
323                 if clear_utf16_name is not None:
324                     gls.add_attr(obj.identifier.dn, clear_utf16_name, [cleartext_utf16])
325                 try:
326                     cleartext_unicode = unicode(cleartext_utf16, 'utf-16-le')
327                     cleartext_utf8 = cleartext_unicode.encode('utf-8')
328                     gls.add_attr(obj.identifier.dn, clear_utf8_name, [cleartext_utf8])
329                 except Exception:
330                     pass
331
332                 if attvals is not None:
333                     gls.add_attr(obj.identifier.dn, attname, attvals)
334
335             krb5_old_hex = None
336
337             for i in range(0, spl.sub.num_packages):
338                 pkg = spl.sub.packages[i]
339                 if pkg.name != "Primary:Kerberos":
340                     continue
341                 krb5_old_hex = pkg.data
342
343             if krb5_old_hex is not None:
344                 krb5_old_raw = binascii.a2b_hex(krb5_old_hex)
345                 krb5_old = ndr_unpack(drsblobs.package_PrimaryKerberosBlob, krb5_old_raw, allow_remaining=True)
346
347                 #print '%s' % ndr_print(krb5_old)
348
349             krb5_new_hex = None
350
351             for i in range(0, spl.sub.num_packages):
352                 pkg = spl.sub.packages[i]
353                 if pkg.name != "Primary:Kerberos-Newer-Keys":
354                     continue
355                 krb5_new_hex = pkg.data
356
357             if krb5_new_hex is not None:
358                 krb5_new_raw = binascii.a2b_hex(krb5_new_hex)
359                 krb5_new = ndr_unpack(drsblobs.package_PrimaryKerberosBlob, krb5_new_raw, allow_remaining=True)
360
361                 #print '%s' % ndr_print(krb5_new)
362
363             obj_item = obj_item.next_object
364
365         gls.print_all()
366
367         if ctr.more_data == 0:
368             store_hwm = ctr.new_highwatermark
369
370             store_utdv = drsblobs.replUpToDateVectorBlob()
371             store_utdv.version = ctr.uptodateness_vector.version
372             store_utdv_ctr = store_utdv.ctr
373             store_utdv_ctr.count = ctr.uptodateness_vector.count
374             store_utdv_ctr.cursors = ctr.uptodateness_vector.cursors
375             store_utdv.ctr = store_utdv_ctr
376
377             #print "%s" % ndr_print(store_hwm)
378             #print "%s" % ndr_print(store_utdv)
379
380             store_hwm_blob = ndr_pack(store_hwm)
381             store_utdv_blob = ndr_pack(store_utdv)
382
383             #
384             # uint32_t version '1'
385             # uint32_t dn_str_len
386             # uint32_t dn_str_ofs
387             # uint32_t hwm_blob_len
388             # uint32_t hwm_blob_ofs
389             # uint32_t utdv_blob_len
390             # uint32_t utdv_blob_ofs
391             store_hdr_len = 7 * 4
392             dn_ofs = store_hdr_len
393             hwm_ofs = dn_ofs + len(dn)
394             utdv_ofs = hwm_ofs + len(store_hwm_blob)
395             store_blob = struct.pack("<LLLLLLL", 1, \
396                                      len(dn), dn_ofs,
397                                      len(store_hwm_blob), hwm_ofs, \
398                                      len(store_utdv_blob), utdv_ofs) + \
399             dn + store_hwm_blob + store_utdv_blob
400
401             tmp_file = "%s.tmp" % cookie_file
402             f = open(tmp_file, 'wb')
403             f.write(store_blob)
404             f.close()
405             os.rename(tmp_file, cookie_file)
406
407             print("# up to usn[%d]" % (ctr.new_highwatermark.highest_usn))
408             break
409         print("# up to tmp_usn[%d]" % (ctr.new_highwatermark.highest_usn))
410         req8.highwatermark = ctr.new_highwatermark