scp.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  1. """A re-implementation of the MS DirectoryService samples related to services.
  2. * Adds and removes an ActiveDirectory "Service Connection Point",
  3. including managing the security on the object.
  4. * Creates and registers Service Principal Names.
  5. * Changes the username for a domain user.
  6. Some of these functions are likely to become move to a module - but there
  7. is also a little command-line-interface to try these functions out.
  8. For example:
  9. scp.py --account-name=domain\\user --service-class=PythonScpTest \\
  10. --keyword=foo --keyword=bar --binding-string=bind_info \\
  11. ScpCreate SpnCreate SpnRegister
  12. would:
  13. * Attempt to delete a Service Connection Point for the service class
  14. 'PythonScpTest'
  15. * Attempt to create a Service Connection Point for that class, with 2
  16. keywords and a binding string of 'bind_info'
  17. * Create a Service Principal Name for the service and register it
  18. to undo those changes, you could execute:
  19. scp.py --account-name=domain\\user --service-class=PythonScpTest \\
  20. SpnCreate SpnUnregister ScpDelete
  21. which will:
  22. * Create a SPN
  23. * Unregister that SPN from the Active Directory.
  24. * Delete the Service Connection Point
  25. Executing with --test will create and remove one of everything.
  26. """
  27. from win32com.adsi.adsicon import *
  28. from win32com.adsi import adsi
  29. import win32api, win32con, winerror
  30. from win32com.client import Dispatch
  31. import ntsecuritycon as dscon
  32. import win32security
  33. import optparse, textwrap
  34. import traceback
  35. verbose = 1
  36. g_createdSCP = None
  37. g_createdSPNs = []
  38. g_createdSPNLast = None
  39. import logging
  40. logger = logging # use logging module global methods for now.
  41. # still a bit confused about log(n, ...) vs logger.info/debug()
  42. # Returns distinguished name of SCP.
  43. def ScpCreate(
  44. service_binding_info,
  45. service_class_name, # Service class string to store in SCP.
  46. account_name = None, # Logon account that needs access to SCP.
  47. container_name = None,
  48. keywords = None,
  49. object_class = "serviceConnectionPoint",
  50. dns_name_type = "A",
  51. dn = None,
  52. dns_name = None,
  53. ):
  54. container_name = container_name or service_class_name
  55. if not dns_name:
  56. # Get the DNS name of the local computer
  57. dns_name = win32api.GetComputerNameEx(win32con.ComputerNameDnsFullyQualified)
  58. # Get the distinguished name of the computer object for the local computer
  59. if dn is None:
  60. dn = win32api.GetComputerObjectName(win32con.NameFullyQualifiedDN)
  61. # Compose the ADSpath and bind to the computer object for the local computer
  62. comp = adsi.ADsGetObject("LDAP://" + dn, adsi.IID_IDirectoryObject)
  63. # Publish the SCP as a child of the computer object
  64. keywords = keywords or []
  65. # Fill in the attribute values to be stored in the SCP.
  66. attrs = [
  67. ("cn", ADS_ATTR_UPDATE, ADSTYPE_CASE_IGNORE_STRING, (container_name,)),
  68. ("objectClass", ADS_ATTR_UPDATE, ADSTYPE_CASE_IGNORE_STRING, (object_class,)),
  69. ("keywords", ADS_ATTR_UPDATE, ADSTYPE_CASE_IGNORE_STRING, keywords),
  70. ("serviceDnsName", ADS_ATTR_UPDATE, ADSTYPE_CASE_IGNORE_STRING, (dns_name,)),
  71. ("serviceDnsNameType", ADS_ATTR_UPDATE, ADSTYPE_CASE_IGNORE_STRING, (dns_name_type,)),
  72. ("serviceClassName", ADS_ATTR_UPDATE, ADSTYPE_CASE_IGNORE_STRING, (service_class_name,)),
  73. ("serviceBindingInformation", ADS_ATTR_UPDATE, ADSTYPE_CASE_IGNORE_STRING, (service_binding_info,)),
  74. ]
  75. new = comp.CreateDSObject("cn=" + container_name, attrs)
  76. logger.info("New connection point is at %s", container_name)
  77. # Wrap in a usable IDispatch object.
  78. new = Dispatch(new)
  79. # And allow access to the SCP for the specified account name
  80. AllowAccessToScpProperties(account_name, new)
  81. return new
  82. def ScpDelete(container_name, dn = None):
  83. if dn is None:
  84. dn = win32api.GetComputerObjectName(win32con.NameFullyQualifiedDN)
  85. logger.debug("Removing connection point '%s' from %s", container_name, dn)
  86. # Compose the ADSpath and bind to the computer object for the local computer
  87. comp = adsi.ADsGetObject("LDAP://" + dn, adsi.IID_IDirectoryObject)
  88. comp.DeleteDSObject("cn=" + container_name)
  89. logger.info("Deleted service connection point '%s'", container_name)
  90. # This function is described in detail in the MSDN article titled
  91. # "Enabling Service Account to Access SCP Properties"
  92. # From that article:
  93. # The following sample code sets a pair of ACEs on a service connection point
  94. # (SCP) object. The ACEs grant read/write access to the user or computer account
  95. # under which the service instance will be running. Your service installation
  96. # program calls this code to ensure that the service will be allowed to update
  97. # its properties at run time. If you don't set ACEs like these, your service
  98. # will get access-denied errors if it tries to modify the SCP's properties.
  99. #
  100. # The code uses the IADsSecurityDescriptor, IADsAccessControlList, and
  101. # IADsAccessControlEntry interfaces to do the following:
  102. # * Get the SCP object's security descriptor.
  103. # * Set ACEs in the DACL of the security descriptor.
  104. # * Set the security descriptor back on the SCP object.
  105. def AllowAccessToScpProperties(
  106. accountSAM, #Service account to allow access.
  107. scpObject, # The IADs SCP object.
  108. schemaIDGUIDs = # Attributes to allow write-access to.
  109. ("{28630eb8-41d5-11d1-a9c1-0000f80367c1}", # serviceDNSName
  110. "{b7b1311c-b82e-11d0-afee-0000f80367c1}", # serviceBindingInformation
  111. )
  112. ):
  113. # If no service account is specified, service runs under LocalSystem.
  114. # So allow access to the computer account of the service's host.
  115. if accountSAM:
  116. trustee = accountSAM
  117. else:
  118. # Get the SAM account name of the computer object for the server.
  119. trustee = win32api.GetComputerObjectName(win32con.NameSamCompatible)
  120. # Get the nTSecurityDescriptor attribute
  121. attribute = "nTSecurityDescriptor"
  122. sd = getattr(scpObject, attribute)
  123. acl = sd.DiscretionaryAcl
  124. for sguid in schemaIDGUIDs:
  125. ace = Dispatch(adsi.CLSID_AccessControlEntry)
  126. # Set the properties of the ACE.
  127. # Allow read and write access to the property.
  128. ace.AccessMask = ADS_RIGHT_DS_READ_PROP | ADS_RIGHT_DS_WRITE_PROP
  129. # Set the trustee, which is either the service account or the
  130. # host computer account.
  131. ace.Trustee = trustee
  132. # Set the ACE type.
  133. ace.AceType = ADS_ACETYPE_ACCESS_ALLOWED_OBJECT
  134. # Set AceFlags to zero because ACE is not inheritable.
  135. ace.AceFlags = 0
  136. # Set Flags to indicate an ACE that protects a specified object.
  137. ace.Flags = ADS_FLAG_OBJECT_TYPE_PRESENT
  138. # Set ObjectType to the schemaIDGUID of the attribute.
  139. ace.ObjectType = sguid
  140. # Add the ACEs to the DACL.
  141. acl.AddAce(ace)
  142. # Write the modified DACL back to the security descriptor.
  143. sd.DiscretionaryAcl = acl
  144. # Write the ntSecurityDescriptor property to the property cache.
  145. setattr(scpObject, attribute, sd)
  146. # SetInfo updates the SCP object in the directory.
  147. scpObject.SetInfo()
  148. logger.info("Set security on object for account '%s'" % (trustee,))
  149. # Service Principal Names functions from the same sample.
  150. # The example calls the DsWriteAccountSpn function, which stores the SPNs in
  151. # Microsoft Active Directory under the servicePrincipalName attribute of the
  152. # account object specified by the serviceAcctDN parameter. The account object
  153. # corresponds to the logon account specified in the CreateService call for this
  154. # service instance. If the logon account is a domain user account,
  155. # serviceAcctDN must be the distinguished name of the account object in
  156. # Active Directory for that user account. If the service's logon account is the
  157. # LocalSystem account, serviceAcctDN must be the distinguished name of the
  158. # computer account object for the host computer on which the service is
  159. # installed. win32api.TranslateNames and win32security.DsCrackNames can
  160. # be used to convert a domain\account format name to a distinguished name.
  161. def SpnRegister(
  162. serviceAcctDN, # DN of the service's logon account
  163. spns, # List of SPNs to register
  164. operation, # Add, replace, or delete SPNs
  165. ):
  166. assert type(spns) not in [str, str] and hasattr(spns, "__iter__"), \
  167. "spns must be a sequence of strings (got %r)" % spns
  168. # Bind to a domain controller.
  169. # Get the domain for the current user.
  170. samName = win32api.GetUserNameEx(win32api.NameSamCompatible)
  171. samName = samName.split('\\', 1)[0]
  172. if not serviceAcctDN:
  173. # Get the SAM account name of the computer object for the server.
  174. serviceAcctDN = win32api.GetComputerObjectName(win32con.NameFullyQualifiedDN)
  175. logger.debug("SpnRegister using DN '%s'", serviceAcctDN)
  176. # Get the name of a domain controller in that domain.
  177. info = win32security.DsGetDcName(
  178. domainName=samName,
  179. flags=dscon.DS_IS_FLAT_NAME |
  180. dscon.DS_RETURN_DNS_NAME |
  181. dscon.DS_DIRECTORY_SERVICE_REQUIRED)
  182. # Bind to the domain controller.
  183. handle = win32security.DsBind( info['DomainControllerName'] )
  184. # Write the SPNs to the service account or computer account.
  185. logger.debug("DsWriteAccountSpn with spns %s")
  186. win32security.DsWriteAccountSpn(
  187. handle, # handle to the directory
  188. operation, # Add or remove SPN from account's existing SPNs
  189. serviceAcctDN, # DN of service account or computer account
  190. spns) # names
  191. # Unbind the DS in any case (but Python would do it anyway)
  192. handle.Close()
  193. def UserChangePassword(username_dn, new_password):
  194. # set the password on the account.
  195. # Use the distinguished name to bind to the account object.
  196. accountPath = "LDAP://" + username_dn
  197. user = adsi.ADsGetObject(accountPath, adsi.IID_IADsUser)
  198. # Set the password on the account.
  199. user.SetPassword(new_password)
  200. # functions related to the command-line interface
  201. def log(level, msg, *args):
  202. if verbose >= level:
  203. print(msg % args)
  204. class _NoDefault: pass
  205. def _get_option(po, opt_name, default = _NoDefault):
  206. parser, options = po
  207. ret = getattr(options, opt_name, default)
  208. if not ret and default is _NoDefault:
  209. parser.error("The '%s' option must be specified for this operation" % opt_name)
  210. if not ret:
  211. ret = default
  212. return ret
  213. def _option_error(po, why):
  214. parser = po[0]
  215. parser.error(why)
  216. def do_ScpCreate(po):
  217. """Create a Service Connection Point"""
  218. global g_createdSCP
  219. scp = ScpCreate(_get_option(po, "binding_string"),
  220. _get_option(po, "service_class"),
  221. _get_option(po, "account_name_sam", None),
  222. keywords=_get_option(po, "keywords", None))
  223. g_createdSCP = scp
  224. return scp.distinguishedName
  225. def do_ScpDelete(po):
  226. """Delete a Service Connection Point"""
  227. sc = _get_option(po, "service_class")
  228. try:
  229. ScpDelete(sc)
  230. except adsi.error as details:
  231. if details[0] != winerror.ERROR_DS_OBJ_NOT_FOUND:
  232. raise
  233. log(2, "ScpDelete ignoring ERROR_DS_OBJ_NOT_FOUND for service-class '%s'",
  234. sc)
  235. return sc
  236. def do_SpnCreate(po):
  237. """Create a Service Principal Name"""
  238. # The 'service name' is the dn of our scp.
  239. if g_createdSCP is None:
  240. # Could accept an arg to avoid this?
  241. _option_error(po, "ScpCreate must have been specified before SpnCreate")
  242. # Create a Service Principal Name"
  243. spns = win32security.DsGetSpn(dscon.DS_SPN_SERVICE,
  244. _get_option(po, "service_class"),
  245. g_createdSCP.distinguishedName,
  246. _get_option(po, "port", 0),
  247. None, None)
  248. spn = spns[0]
  249. log(2, "Created SPN: %s", spn)
  250. global g_createdSPNLast
  251. g_createdSPNLast = spn
  252. g_createdSPNs.append(spn)
  253. return spn
  254. def do_SpnRegister(po):
  255. """Register a previously created Service Principal Name"""
  256. if not g_createdSPNLast:
  257. _option_error(po, "SpnCreate must appear before SpnRegister")
  258. SpnRegister(_get_option(po, "account_name_dn", None),
  259. (g_createdSPNLast,),
  260. dscon.DS_SPN_ADD_SPN_OP)
  261. return g_createdSPNLast
  262. def do_SpnUnregister(po):
  263. """Unregister a previously created Service Principal Name"""
  264. if not g_createdSPNLast:
  265. _option_error(po, "SpnCreate must appear before SpnUnregister")
  266. SpnRegister(_get_option(po, "account_name_dn", None),
  267. (g_createdSPNLast,),
  268. dscon.DS_SPN_DELETE_SPN_OP)
  269. return g_createdSPNLast
  270. def do_UserChangePassword(po):
  271. """Change the password for a specified user"""
  272. UserChangePassword(_get_option(po, "account_name_dn"),
  273. _get_option(po, "password"))
  274. return "Password changed OK"
  275. handlers = (
  276. ('ScpCreate', do_ScpCreate),
  277. ('ScpDelete', do_ScpDelete),
  278. ('SpnCreate', do_SpnCreate),
  279. ('SpnRegister', do_SpnRegister),
  280. ('SpnUnregister', do_SpnUnregister),
  281. ('UserChangePassword', do_UserChangePassword),
  282. )
  283. class HelpFormatter(optparse.IndentedHelpFormatter):
  284. def format_description(self, description):
  285. return description
  286. def main():
  287. global verbose
  288. _handlers_dict = {}
  289. arg_descs = []
  290. for arg, func in handlers:
  291. this_desc = "\n".join(textwrap.wrap(func.__doc__,
  292. subsequent_indent = " " * 8))
  293. arg_descs.append(" %s: %s" % (arg, this_desc))
  294. _handlers_dict[arg.lower()] = func
  295. description = __doc__ + "\ncommands:\n" + "\n".join(arg_descs) + "\n"
  296. parser = optparse.OptionParser(usage = "%prog [options] command ...",
  297. description=description,
  298. formatter=HelpFormatter())
  299. parser.add_option("-v", action="count",
  300. dest="verbose", default=1,
  301. help="increase the verbosity of status messages")
  302. parser.add_option("-q", "--quiet", action="store_true",
  303. help="Don't print any status messages")
  304. parser.add_option("-t", "--test", action="store_true",
  305. help="Execute a mini-test suite, providing defaults for most options and args"),
  306. parser.add_option("", "--show-tracebacks", action="store_true",
  307. help="Show the tracebacks for any exceptions")
  308. parser.add_option("", "--service-class",
  309. help="The service class name to use")
  310. parser.add_option("", "--port", default=0,
  311. help="The port number to associate with the SPN")
  312. parser.add_option("", "--binding-string",
  313. help="The binding string to use for SCP creation")
  314. parser.add_option("", "--account-name",
  315. help="The account name to use (default is LocalSystem)")
  316. parser.add_option("", "--password",
  317. help="The password to set.")
  318. parser.add_option("", "--keyword", action="append", dest="keywords",
  319. help="""A keyword to add to the SCP. May be specified
  320. multiple times""")
  321. parser.add_option("", "--log-level",
  322. help="""The log-level to use - may be a number or a logging
  323. module constant""", default=str(logging.WARNING))
  324. options, args = parser.parse_args()
  325. po = (parser, options)
  326. # fixup misc
  327. try:
  328. options.port = int(options.port)
  329. except (TypeError, ValueError):
  330. parser.error("--port must be numeric")
  331. # fixup log-level
  332. try:
  333. log_level = int(options.log_level)
  334. except (TypeError, ValueError):
  335. try:
  336. log_level = int(getattr(logging, options.log_level.upper()))
  337. except (ValueError, TypeError, AttributeError):
  338. parser.error("Invalid --log-level value")
  339. try:
  340. sl = logger.setLevel
  341. # logger is a real logger
  342. except AttributeError:
  343. # logger is logging module
  344. sl = logging.getLogger().setLevel
  345. sl(log_level)
  346. # Check -q/-v
  347. if options.quiet and options.verbose:
  348. parser.error("Can't specify --quiet and --verbose")
  349. if options.quiet:
  350. options.verbose -= 1
  351. verbose = options.verbose
  352. # --test
  353. if options.test:
  354. if args:
  355. parser.error("Can't specify args with --test")
  356. args = "ScpDelete ScpCreate SpnCreate SpnRegister SpnUnregister ScpDelete"
  357. log(1, "--test - pretending args are:\n %s", args)
  358. args = args.split()
  359. if not options.service_class:
  360. options.service_class = "PythonScpTest"
  361. log(2, "--test: --service-class=%s", options.service_class)
  362. if not options.keywords:
  363. options.keywords = "Python Powered".split()
  364. log(2, "--test: --keyword=%s", options.keywords)
  365. if not options.binding_string:
  366. options.binding_string = "test binding string"
  367. log(2, "--test: --binding-string=%s", options.binding_string)
  368. # check args
  369. if not args:
  370. parser.error("No command specified (use --help for valid commands)")
  371. for arg in args:
  372. if arg.lower() not in _handlers_dict:
  373. parser.error("Invalid command '%s' (use --help for valid commands)" % arg)
  374. # Patch up account-name.
  375. if options.account_name:
  376. log(2, "Translating account name '%s'", options.account_name)
  377. options.account_name_sam = win32security.TranslateName(options.account_name,
  378. win32api.NameUnknown,
  379. win32api.NameSamCompatible)
  380. log(2, "NameSamCompatible is '%s'",options.account_name_sam)
  381. options.account_name_dn = win32security.TranslateName(options.account_name,
  382. win32api.NameUnknown,
  383. win32api.NameFullyQualifiedDN)
  384. log(2, "NameFullyQualifiedDNis '%s'",options.account_name_dn)
  385. # do it.
  386. for arg in args:
  387. handler = _handlers_dict[arg.lower()] # already been validated
  388. if handler is None:
  389. parser.error("Invalid command '%s'" % arg)
  390. err_msg = None
  391. try:
  392. try:
  393. log(2, "Executing '%s'...", arg)
  394. result = handler(po)
  395. log(1, "%s: %s", arg, result)
  396. except:
  397. if options.show_tracebacks:
  398. print("--show-tracebacks specified - dumping exception")
  399. traceback.print_exc()
  400. raise
  401. except adsi.error as xxx_todo_changeme:
  402. (hr, desc, exc, argerr) = xxx_todo_changeme.args
  403. if exc:
  404. extra_desc = exc[2]
  405. else:
  406. extra_desc = ""
  407. err_msg = desc
  408. if extra_desc:
  409. err_msg += "\n\t" + extra_desc
  410. except win32api.error as xxx_todo_changeme1:
  411. (hr, func, msg) = xxx_todo_changeme1.args
  412. err_msg = msg
  413. if err_msg:
  414. log(1, "Command '%s' failed: %s", arg, err_msg)
  415. if __name__=='__main__':
  416. try:
  417. main()
  418. except KeyboardInterrupt:
  419. print("*** Interrupted")