Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

scp.py 19KB

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