PEP8: fix E122: continuation line missing indentation or outdented
[nivanova/samba-autobuild/.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
60 class globals:
61     def __init__(self):
62         self.global_objs = {}
63         self.ldif = LDIFWriter(sys.stdout)
64
65     def add_attr(self, dn, attname, vals):
66         if dn not in self.global_objs:
67             self.global_objs[dn] = {}
68         self.global_objs[dn][attname] = vals
69
70     def print_all(self):
71         for dn, obj in self.global_objs.items():
72             self.ldif.unparse(dn, obj)
73             continue
74         self.global_objs = {}
75
76
77 def attid_equal(a1, a2):
78     return (a1 & 0xffffffff) == (a2 & 0xffffffff)
79
80
81 ########### main code ###########
82 if __name__ == "__main__":
83     parser = OptionParser("repl_cleartext_pwd.py [options] server dn cookie_file clear_utf8_name [attid attname attmode] [clear_utf16_name")
84     sambaopts = options.SambaOptions(parser)
85     credopts = options.CredentialsOptions(parser)
86     parser.add_option_group(credopts)
87
88     (opts, args) = parser.parse_args()
89
90     if len(args) == 4:
91         pass
92     elif len(args) == 7:
93         pass
94     elif len(args) >= 8:
95         pass
96     else:
97         parser.error("more arguments required - given=%d" % (len(args)))
98
99     server = args[0]
100     dn = args[1]
101     cookie_file = args[2]
102     if len(cookie_file) == 0:
103         cookie_file = None
104     clear_utf8_name = args[3]
105     if len(args) >= 7:
106         try:
107             attid = int(args[4], 16)
108         except Exception:
109             attid = int(args[4])
110         attname = args[5]
111         attmode = args[6]
112         if attmode not in ["raw", "utf8"]:
113             parser.error("attmode should be 'raw' or 'utf8'")
114     else:
115         attid = -1
116         attname = None
117         attmode = "raw"
118     if len(args) >= 8:
119         clear_utf16_name = args[7]
120     else:
121         clear_utf16_name = None
122
123     lp = sambaopts.get_loadparm()
124     creds = credopts.get_credentials(lp)
125
126     if not creds.authentication_requested():
127         parser.error("You must supply credentials")
128
129     gls = globals()
130     try:
131         f = open(cookie_file, 'r')
132         store_blob = f.read()
133         f.close()
134
135         store_hdr = store_blob[0:28]
136         (store_version,
137          store_dn_len, store_dn_ofs,
138          store_hwm_len, store_hwm_ofs,
139          store_utdv_len, store_utdv_ofs) = \
140             struct.unpack("<LLLLLLL", store_hdr)
141
142         store_dn = store_blob[store_dn_ofs:store_dn_ofs + store_dn_len]
143         store_hwm_blob = store_blob[store_hwm_ofs:store_hwm_ofs + store_hwm_len]
144         store_utdv_blob = store_blob[store_utdv_ofs:store_utdv_ofs + store_utdv_len]
145
146         store_hwm = ndr_unpack(drsuapi.DsReplicaHighWaterMark, store_hwm_blob)
147         store_utdv = ndr_unpack(drsblobs.replUpToDateVectorBlob, store_utdv_blob)
148
149         assert store_dn == dn
150         # print "%s" % ndr_print(store_hwm)
151         # print "%s" % ndr_print(store_utdv)
152     except Exception:
153         store_dn = dn
154         store_hwm = drsuapi.DsReplicaHighWaterMark()
155         store_hwm.tmp_highest_usn  = 0
156         store_hwm.reserved_usn     = 0
157         store_hwm.highest_usn      = 0
158         store_utdv = None
159
160     binding_str = "ncacn_ip_tcp:%s[spnego,seal]" % server
161
162     drs_conn = drsuapi.drsuapi(binding_str, lp, creds)
163
164     bind_info = drsuapi.DsBindInfoCtr()
165     bind_info.length = 28
166     bind_info.info = drsuapi.DsBindInfo28()
167     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_BASE
168     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_ASYNC_REPLICATION
169     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_REMOVEAPI
170     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_MOVEREQ_V2
171     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_GETCHG_COMPRESS
172     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_DCINFO_V1
173     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_RESTORE_USN_OPTIMIZATION
174     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_KCC_EXECUTE
175     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_ADDENTRY_V2
176     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_LINKED_VALUE_REPLICATION
177     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_DCINFO_V2
178     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_INSTANCE_TYPE_NOT_REQ_ON_MOD
179     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_CRYPTO_BIND
180     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_GET_REPL_INFO
181     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_STRONG_ENCRYPTION
182     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_DCINFO_V01
183     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_TRANSITIVE_MEMBERSHIP
184     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_ADD_SID_HISTORY
185     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_POST_BETA3
186     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_GET_MEMBERSHIPS2
187     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_GETCHGREQ_V6
188     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_NONDOMAIN_NCS
189     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_GETCHGREQ_V8
190     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_GETCHGREPLY_V5
191     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_GETCHGREPLY_V6
192     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_ADDENTRYREPLY_V3
193     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_GETCHGREPLY_V7
194     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_VERIFY_OBJECT
195     (info, drs_handle) = drs_conn.DsBind(misc.GUID(drsuapi.DRSUAPI_DS_BIND_GUID), bind_info)
196
197     null_guid = misc.GUID()
198
199     naming_context = drsuapi.DsReplicaObjectIdentifier()
200     naming_context.dn              = dn
201     highwatermark                  = store_hwm
202     uptodateness_vector            = None
203     if store_utdv is not None:
204         uptodateness_vector = drsuapi.DsReplicaCursorCtrEx()
205         if store_utdv.version == 1:
206             uptodateness_vector.cursors = store_utdv.cursors
207         elif store_utdv.version == 2:
208             cursors = []
209             for i in range(0, store_utdv.ctr.count):
210                 cursor = drsuapi.DsReplicaCursor()
211                 cursor.source_dsa_invocation_id = store_utdv.ctr.cursors[i].source_dsa_invocation_id
212                 cursor.highest_usn = store_utdv.ctr.cursors[i].highest_usn
213                 cursors.append(cursor)
214             uptodateness_vector.cursors = cursors
215
216     req8 = drsuapi.DsGetNCChangesRequest8()
217
218     req8.destination_dsa_guid           = null_guid
219     req8.source_dsa_invocation_id       = null_guid
220     req8.naming_context                 = naming_context
221     req8.highwatermark                  = highwatermark
222     req8.uptodateness_vector            = uptodateness_vector
223     req8.replica_flags                  = (drsuapi.DRSUAPI_DRS_INIT_SYNC |
224                                            drsuapi.DRSUAPI_DRS_PER_SYNC |
225                                            drsuapi.DRSUAPI_DRS_GET_ANC |
226                                            drsuapi.DRSUAPI_DRS_NEVER_SYNCED |
227                                            drsuapi.DRSUAPI_DRS_WRIT_REP)
228     req8.max_object_count = 402
229     req8.max_ndr_size = 402116
230     req8.extended_op = 0
231     req8.fsmo_info = 0
232     req8.partial_attribute_set = None
233     req8.partial_attribute_set_ex = None
234     req8.mapping_ctr.num_mappings = 0
235     req8.mapping_ctr.mappings = None
236
237     user_session_key = drs_conn.user_session_key
238
239     print("# starting at usn[%d]" % (highwatermark.highest_usn))
240
241     while True:
242         (level, ctr) = drs_conn.DsGetNCChanges(drs_handle, 8, req8)
243         if ctr.first_object is None and ctr.object_count != 0:
244             raise RuntimeError("DsGetNCChanges: NULL first_object with object_count=%u" % (ctr.object_count))
245
246         obj_item = ctr.first_object
247         while obj_item is not None:
248             obj = obj_item.object
249
250             if obj.identifier is None:
251                 obj_item = obj_item.next_object
252                 continue
253
254             # print '%s' % obj.identifier.dn
255
256             is_deleted = False
257             for i in range(0, obj.attribute_ctr.num_attributes):
258                 attr = obj.attribute_ctr.attributes[i]
259                 if attid_equal(attr.attid, drsuapi.DRSUAPI_ATTID_isDeleted):
260                     is_deleted = True
261             if is_deleted:
262                 obj_item = obj_item.next_object
263                 continue
264
265             spl_crypt = None
266             attvals = None
267             for i in range(0, obj.attribute_ctr.num_attributes):
268                 attr = obj.attribute_ctr.attributes[i]
269                 if attid_equal(attr.attid, attid):
270                     attvals = []
271                     for j in range(0, attr.value_ctr.num_values):
272                         assert attr.value_ctr.values[j].blob is not None
273                         val_raw = attr.value_ctr.values[j].blob
274                         val = None
275                         if attmode == "utf8":
276                             val_unicode = unicode(val_raw, 'utf-16-le')
277                             val = val_unicode.encode('utf-8')
278                         elif attmode == "raw":
279                             val = val_raw
280                         else:
281                             assert False, "attmode[%s]" % attmode
282                         attvals.append(val)
283                 if not attid_equal(attr.attid, drsuapi.DRSUAPI_ATTID_supplementalCredentials):
284                     continue
285                 assert attr.value_ctr.num_values <= 1
286                 if attr.value_ctr.num_values == 0:
287                     break
288                 assert attr.value_ctr.values[0].blob is not None
289                 spl_crypt = attr.value_ctr.values[0].blob
290
291             if spl_crypt is None:
292                 obj_item = obj_item.next_object
293                 continue
294
295             assert len(spl_crypt) >= 20
296             confounder = spl_crypt[0:16]
297             enc_buffer = spl_crypt[16:]
298
299             m5 = hashlib.md5()
300             m5.update(user_session_key)
301             m5.update(confounder)
302             enc_key = m5.digest()
303
304             rc4 = Crypto.Cipher.ARC4.new(enc_key)
305             plain_buffer = rc4.decrypt(enc_buffer)
306
307             (crc32_v) = struct.unpack("<L", plain_buffer[0:4])
308             attr_val = plain_buffer[4:]
309             crc32_c = binascii.crc32(attr_val) & 0xffffffff
310             assert int(crc32_v[0]) == int(crc32_c), "CRC32 0x%08X != 0x%08X" % (crc32_v[0], crc32_c)
311
312             spl = ndr_unpack(drsblobs.supplementalCredentialsBlob, attr_val)
313
314             # print '%s' % ndr_print(spl)
315
316             cleartext_hex = None
317
318             for i in range(0, spl.sub.num_packages):
319                 pkg = spl.sub.packages[i]
320                 if pkg.name != "Primary:CLEARTEXT":
321                     continue
322                 cleartext_hex = pkg.data
323
324             if cleartext_hex is not None:
325                 cleartext_utf16 = binascii.a2b_hex(cleartext_hex)
326                 if clear_utf16_name is not None:
327                     gls.add_attr(obj.identifier.dn, clear_utf16_name, [cleartext_utf16])
328                 try:
329                     cleartext_unicode = unicode(cleartext_utf16, 'utf-16-le')
330                     cleartext_utf8 = cleartext_unicode.encode('utf-8')
331                     gls.add_attr(obj.identifier.dn, clear_utf8_name, [cleartext_utf8])
332                 except Exception:
333                     pass
334
335                 if attvals is not None:
336                     gls.add_attr(obj.identifier.dn, attname, attvals)
337
338             krb5_old_hex = None
339
340             for i in range(0, spl.sub.num_packages):
341                 pkg = spl.sub.packages[i]
342                 if pkg.name != "Primary:Kerberos":
343                     continue
344                 krb5_old_hex = pkg.data
345
346             if krb5_old_hex is not None:
347                 krb5_old_raw = binascii.a2b_hex(krb5_old_hex)
348                 krb5_old = ndr_unpack(drsblobs.package_PrimaryKerberosBlob, krb5_old_raw, allow_remaining=True)
349
350                 # print '%s' % ndr_print(krb5_old)
351
352             krb5_new_hex = None
353
354             for i in range(0, spl.sub.num_packages):
355                 pkg = spl.sub.packages[i]
356                 if pkg.name != "Primary:Kerberos-Newer-Keys":
357                     continue
358                 krb5_new_hex = pkg.data
359
360             if krb5_new_hex is not None:
361                 krb5_new_raw = binascii.a2b_hex(krb5_new_hex)
362                 krb5_new = ndr_unpack(drsblobs.package_PrimaryKerberosBlob, krb5_new_raw, allow_remaining=True)
363
364                 # print '%s' % ndr_print(krb5_new)
365
366             obj_item = obj_item.next_object
367
368         gls.print_all()
369
370         if ctr.more_data == 0:
371             store_hwm = ctr.new_highwatermark
372
373             store_utdv = drsblobs.replUpToDateVectorBlob()
374             store_utdv.version = ctr.uptodateness_vector.version
375             store_utdv_ctr = store_utdv.ctr
376             store_utdv_ctr.count = ctr.uptodateness_vector.count
377             store_utdv_ctr.cursors = ctr.uptodateness_vector.cursors
378             store_utdv.ctr = store_utdv_ctr
379
380             # print "%s" % ndr_print(store_hwm)
381             # print "%s" % ndr_print(store_utdv)
382
383             store_hwm_blob = ndr_pack(store_hwm)
384             store_utdv_blob = ndr_pack(store_utdv)
385
386             #
387             # uint32_t version '1'
388             # uint32_t dn_str_len
389             # uint32_t dn_str_ofs
390             # uint32_t hwm_blob_len
391             # uint32_t hwm_blob_ofs
392             # uint32_t utdv_blob_len
393             # uint32_t utdv_blob_ofs
394             store_hdr_len = 7 * 4
395             dn_ofs = store_hdr_len
396             hwm_ofs = dn_ofs + len(dn)
397             utdv_ofs = hwm_ofs + len(store_hwm_blob)
398             store_blob = struct.pack("<LLLLLLL", 1,
399                                      len(dn), dn_ofs,
400                                      len(store_hwm_blob), hwm_ofs,
401                                      len(store_utdv_blob), utdv_ofs) + \
402                 dn + store_hwm_blob + store_utdv_blob
403
404             tmp_file = "%s.tmp" % cookie_file
405             f = open(tmp_file, 'wb')
406             f.write(store_blob)
407             f.close()
408             os.rename(tmp_file, cookie_file)
409
410             print("# up to usn[%d]" % (ctr.new_highwatermark.highest_usn))
411             break
412         print("# up to tmp_usn[%d]" % (ctr.new_highwatermark.highest_usn))
413         req8.highwatermark = ctr.new_highwatermark