security_windows.go 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435
  1. // Copyright 2012 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package windows
  5. import (
  6. "syscall"
  7. "unsafe"
  8. )
  9. const (
  10. NameUnknown = 0
  11. NameFullyQualifiedDN = 1
  12. NameSamCompatible = 2
  13. NameDisplay = 3
  14. NameUniqueId = 6
  15. NameCanonical = 7
  16. NameUserPrincipal = 8
  17. NameCanonicalEx = 9
  18. NameServicePrincipal = 10
  19. NameDnsDomain = 12
  20. )
  21. // This function returns 1 byte BOOLEAN rather than the 4 byte BOOL.
  22. // http://blogs.msdn.com/b/drnick/archive/2007/12/19/windows-and-upn-format-credentials.aspx
  23. //sys TranslateName(accName *uint16, accNameFormat uint32, desiredNameFormat uint32, translatedName *uint16, nSize *uint32) (err error) [failretval&0xff==0] = secur32.TranslateNameW
  24. //sys GetUserNameEx(nameFormat uint32, nameBuffre *uint16, nSize *uint32) (err error) [failretval&0xff==0] = secur32.GetUserNameExW
  25. // TranslateAccountName converts a directory service
  26. // object name from one format to another.
  27. func TranslateAccountName(username string, from, to uint32, initSize int) (string, error) {
  28. u, e := UTF16PtrFromString(username)
  29. if e != nil {
  30. return "", e
  31. }
  32. n := uint32(50)
  33. for {
  34. b := make([]uint16, n)
  35. e = TranslateName(u, from, to, &b[0], &n)
  36. if e == nil {
  37. return UTF16ToString(b[:n]), nil
  38. }
  39. if e != ERROR_INSUFFICIENT_BUFFER {
  40. return "", e
  41. }
  42. if n <= uint32(len(b)) {
  43. return "", e
  44. }
  45. }
  46. }
  47. const (
  48. // do not reorder
  49. NetSetupUnknownStatus = iota
  50. NetSetupUnjoined
  51. NetSetupWorkgroupName
  52. NetSetupDomainName
  53. )
  54. type UserInfo10 struct {
  55. Name *uint16
  56. Comment *uint16
  57. UsrComment *uint16
  58. FullName *uint16
  59. }
  60. //sys NetUserGetInfo(serverName *uint16, userName *uint16, level uint32, buf **byte) (neterr error) = netapi32.NetUserGetInfo
  61. //sys NetGetJoinInformation(server *uint16, name **uint16, bufType *uint32) (neterr error) = netapi32.NetGetJoinInformation
  62. //sys NetApiBufferFree(buf *byte) (neterr error) = netapi32.NetApiBufferFree
  63. const (
  64. // do not reorder
  65. SidTypeUser = 1 + iota
  66. SidTypeGroup
  67. SidTypeDomain
  68. SidTypeAlias
  69. SidTypeWellKnownGroup
  70. SidTypeDeletedAccount
  71. SidTypeInvalid
  72. SidTypeUnknown
  73. SidTypeComputer
  74. SidTypeLabel
  75. )
  76. type SidIdentifierAuthority struct {
  77. Value [6]byte
  78. }
  79. var (
  80. SECURITY_NULL_SID_AUTHORITY = SidIdentifierAuthority{[6]byte{0, 0, 0, 0, 0, 0}}
  81. SECURITY_WORLD_SID_AUTHORITY = SidIdentifierAuthority{[6]byte{0, 0, 0, 0, 0, 1}}
  82. SECURITY_LOCAL_SID_AUTHORITY = SidIdentifierAuthority{[6]byte{0, 0, 0, 0, 0, 2}}
  83. SECURITY_CREATOR_SID_AUTHORITY = SidIdentifierAuthority{[6]byte{0, 0, 0, 0, 0, 3}}
  84. SECURITY_NON_UNIQUE_AUTHORITY = SidIdentifierAuthority{[6]byte{0, 0, 0, 0, 0, 4}}
  85. SECURITY_NT_AUTHORITY = SidIdentifierAuthority{[6]byte{0, 0, 0, 0, 0, 5}}
  86. SECURITY_MANDATORY_LABEL_AUTHORITY = SidIdentifierAuthority{[6]byte{0, 0, 0, 0, 0, 16}}
  87. )
  88. const (
  89. SECURITY_NULL_RID = 0
  90. SECURITY_WORLD_RID = 0
  91. SECURITY_LOCAL_RID = 0
  92. SECURITY_CREATOR_OWNER_RID = 0
  93. SECURITY_CREATOR_GROUP_RID = 1
  94. SECURITY_DIALUP_RID = 1
  95. SECURITY_NETWORK_RID = 2
  96. SECURITY_BATCH_RID = 3
  97. SECURITY_INTERACTIVE_RID = 4
  98. SECURITY_LOGON_IDS_RID = 5
  99. SECURITY_SERVICE_RID = 6
  100. SECURITY_LOCAL_SYSTEM_RID = 18
  101. SECURITY_BUILTIN_DOMAIN_RID = 32
  102. SECURITY_PRINCIPAL_SELF_RID = 10
  103. SECURITY_CREATOR_OWNER_SERVER_RID = 0x2
  104. SECURITY_CREATOR_GROUP_SERVER_RID = 0x3
  105. SECURITY_LOGON_IDS_RID_COUNT = 0x3
  106. SECURITY_ANONYMOUS_LOGON_RID = 0x7
  107. SECURITY_PROXY_RID = 0x8
  108. SECURITY_ENTERPRISE_CONTROLLERS_RID = 0x9
  109. SECURITY_SERVER_LOGON_RID = SECURITY_ENTERPRISE_CONTROLLERS_RID
  110. SECURITY_AUTHENTICATED_USER_RID = 0xb
  111. SECURITY_RESTRICTED_CODE_RID = 0xc
  112. SECURITY_NT_NON_UNIQUE_RID = 0x15
  113. )
  114. // Predefined domain-relative RIDs for local groups.
  115. // See https://msdn.microsoft.com/en-us/library/windows/desktop/aa379649(v=vs.85).aspx
  116. const (
  117. DOMAIN_ALIAS_RID_ADMINS = 0x220
  118. DOMAIN_ALIAS_RID_USERS = 0x221
  119. DOMAIN_ALIAS_RID_GUESTS = 0x222
  120. DOMAIN_ALIAS_RID_POWER_USERS = 0x223
  121. DOMAIN_ALIAS_RID_ACCOUNT_OPS = 0x224
  122. DOMAIN_ALIAS_RID_SYSTEM_OPS = 0x225
  123. DOMAIN_ALIAS_RID_PRINT_OPS = 0x226
  124. DOMAIN_ALIAS_RID_BACKUP_OPS = 0x227
  125. DOMAIN_ALIAS_RID_REPLICATOR = 0x228
  126. DOMAIN_ALIAS_RID_RAS_SERVERS = 0x229
  127. DOMAIN_ALIAS_RID_PREW2KCOMPACCESS = 0x22a
  128. DOMAIN_ALIAS_RID_REMOTE_DESKTOP_USERS = 0x22b
  129. DOMAIN_ALIAS_RID_NETWORK_CONFIGURATION_OPS = 0x22c
  130. DOMAIN_ALIAS_RID_INCOMING_FOREST_TRUST_BUILDERS = 0x22d
  131. DOMAIN_ALIAS_RID_MONITORING_USERS = 0x22e
  132. DOMAIN_ALIAS_RID_LOGGING_USERS = 0x22f
  133. DOMAIN_ALIAS_RID_AUTHORIZATIONACCESS = 0x230
  134. DOMAIN_ALIAS_RID_TS_LICENSE_SERVERS = 0x231
  135. DOMAIN_ALIAS_RID_DCOM_USERS = 0x232
  136. DOMAIN_ALIAS_RID_IUSERS = 0x238
  137. DOMAIN_ALIAS_RID_CRYPTO_OPERATORS = 0x239
  138. DOMAIN_ALIAS_RID_CACHEABLE_PRINCIPALS_GROUP = 0x23b
  139. DOMAIN_ALIAS_RID_NON_CACHEABLE_PRINCIPALS_GROUP = 0x23c
  140. DOMAIN_ALIAS_RID_EVENT_LOG_READERS_GROUP = 0x23d
  141. DOMAIN_ALIAS_RID_CERTSVC_DCOM_ACCESS_GROUP = 0x23e
  142. )
  143. //sys LookupAccountSid(systemName *uint16, sid *SID, name *uint16, nameLen *uint32, refdDomainName *uint16, refdDomainNameLen *uint32, use *uint32) (err error) = advapi32.LookupAccountSidW
  144. //sys LookupAccountName(systemName *uint16, accountName *uint16, sid *SID, sidLen *uint32, refdDomainName *uint16, refdDomainNameLen *uint32, use *uint32) (err error) = advapi32.LookupAccountNameW
  145. //sys ConvertSidToStringSid(sid *SID, stringSid **uint16) (err error) = advapi32.ConvertSidToStringSidW
  146. //sys ConvertStringSidToSid(stringSid *uint16, sid **SID) (err error) = advapi32.ConvertStringSidToSidW
  147. //sys GetLengthSid(sid *SID) (len uint32) = advapi32.GetLengthSid
  148. //sys CopySid(destSidLen uint32, destSid *SID, srcSid *SID) (err error) = advapi32.CopySid
  149. //sys AllocateAndInitializeSid(identAuth *SidIdentifierAuthority, subAuth byte, subAuth0 uint32, subAuth1 uint32, subAuth2 uint32, subAuth3 uint32, subAuth4 uint32, subAuth5 uint32, subAuth6 uint32, subAuth7 uint32, sid **SID) (err error) = advapi32.AllocateAndInitializeSid
  150. //sys createWellKnownSid(sidType WELL_KNOWN_SID_TYPE, domainSid *SID, sid *SID, sizeSid *uint32) (err error) = advapi32.CreateWellKnownSid
  151. //sys isWellKnownSid(sid *SID, sidType WELL_KNOWN_SID_TYPE) (isWellKnown bool) = advapi32.IsWellKnownSid
  152. //sys FreeSid(sid *SID) (err error) [failretval!=0] = advapi32.FreeSid
  153. //sys EqualSid(sid1 *SID, sid2 *SID) (isEqual bool) = advapi32.EqualSid
  154. //sys getSidIdentifierAuthority(sid *SID) (authority *SidIdentifierAuthority) = advapi32.GetSidIdentifierAuthority
  155. //sys getSidSubAuthorityCount(sid *SID) (count *uint8) = advapi32.GetSidSubAuthorityCount
  156. //sys getSidSubAuthority(sid *SID, index uint32) (subAuthority *uint32) = advapi32.GetSidSubAuthority
  157. //sys isValidSid(sid *SID) (isValid bool) = advapi32.IsValidSid
  158. // The security identifier (SID) structure is a variable-length
  159. // structure used to uniquely identify users or groups.
  160. type SID struct{}
  161. // StringToSid converts a string-format security identifier
  162. // SID into a valid, functional SID.
  163. func StringToSid(s string) (*SID, error) {
  164. var sid *SID
  165. p, e := UTF16PtrFromString(s)
  166. if e != nil {
  167. return nil, e
  168. }
  169. e = ConvertStringSidToSid(p, &sid)
  170. if e != nil {
  171. return nil, e
  172. }
  173. defer LocalFree((Handle)(unsafe.Pointer(sid)))
  174. return sid.Copy()
  175. }
  176. // LookupSID retrieves a security identifier SID for the account
  177. // and the name of the domain on which the account was found.
  178. // System specify target computer to search.
  179. func LookupSID(system, account string) (sid *SID, domain string, accType uint32, err error) {
  180. if len(account) == 0 {
  181. return nil, "", 0, syscall.EINVAL
  182. }
  183. acc, e := UTF16PtrFromString(account)
  184. if e != nil {
  185. return nil, "", 0, e
  186. }
  187. var sys *uint16
  188. if len(system) > 0 {
  189. sys, e = UTF16PtrFromString(system)
  190. if e != nil {
  191. return nil, "", 0, e
  192. }
  193. }
  194. n := uint32(50)
  195. dn := uint32(50)
  196. for {
  197. b := make([]byte, n)
  198. db := make([]uint16, dn)
  199. sid = (*SID)(unsafe.Pointer(&b[0]))
  200. e = LookupAccountName(sys, acc, sid, &n, &db[0], &dn, &accType)
  201. if e == nil {
  202. return sid, UTF16ToString(db), accType, nil
  203. }
  204. if e != ERROR_INSUFFICIENT_BUFFER {
  205. return nil, "", 0, e
  206. }
  207. if n <= uint32(len(b)) {
  208. return nil, "", 0, e
  209. }
  210. }
  211. }
  212. // String converts SID to a string format suitable for display, storage, or transmission.
  213. func (sid *SID) String() string {
  214. var s *uint16
  215. e := ConvertSidToStringSid(sid, &s)
  216. if e != nil {
  217. return ""
  218. }
  219. defer LocalFree((Handle)(unsafe.Pointer(s)))
  220. return UTF16ToString((*[256]uint16)(unsafe.Pointer(s))[:])
  221. }
  222. // Len returns the length, in bytes, of a valid security identifier SID.
  223. func (sid *SID) Len() int {
  224. return int(GetLengthSid(sid))
  225. }
  226. // Copy creates a duplicate of security identifier SID.
  227. func (sid *SID) Copy() (*SID, error) {
  228. b := make([]byte, sid.Len())
  229. sid2 := (*SID)(unsafe.Pointer(&b[0]))
  230. e := CopySid(uint32(len(b)), sid2, sid)
  231. if e != nil {
  232. return nil, e
  233. }
  234. return sid2, nil
  235. }
  236. // IdentifierAuthority returns the identifier authority of the SID.
  237. func (sid *SID) IdentifierAuthority() SidIdentifierAuthority {
  238. return *getSidIdentifierAuthority(sid)
  239. }
  240. // SubAuthorityCount returns the number of sub-authorities in the SID.
  241. func (sid *SID) SubAuthorityCount() uint8 {
  242. return *getSidSubAuthorityCount(sid)
  243. }
  244. // SubAuthority returns the sub-authority of the SID as specified by
  245. // the index, which must be less than sid.SubAuthorityCount().
  246. func (sid *SID) SubAuthority(idx uint32) uint32 {
  247. if idx >= uint32(sid.SubAuthorityCount()) {
  248. panic("sub-authority index out of range")
  249. }
  250. return *getSidSubAuthority(sid, idx)
  251. }
  252. // IsValid returns whether the SID has a valid revision and length.
  253. func (sid *SID) IsValid() bool {
  254. return isValidSid(sid)
  255. }
  256. // Equals compares two SIDs for equality.
  257. func (sid *SID) Equals(sid2 *SID) bool {
  258. return EqualSid(sid, sid2)
  259. }
  260. // IsWellKnown determines whether the SID matches the well-known sidType.
  261. func (sid *SID) IsWellKnown(sidType WELL_KNOWN_SID_TYPE) bool {
  262. return isWellKnownSid(sid, sidType)
  263. }
  264. // LookupAccount retrieves the name of the account for this SID
  265. // and the name of the first domain on which this SID is found.
  266. // System specify target computer to search for.
  267. func (sid *SID) LookupAccount(system string) (account, domain string, accType uint32, err error) {
  268. var sys *uint16
  269. if len(system) > 0 {
  270. sys, err = UTF16PtrFromString(system)
  271. if err != nil {
  272. return "", "", 0, err
  273. }
  274. }
  275. n := uint32(50)
  276. dn := uint32(50)
  277. for {
  278. b := make([]uint16, n)
  279. db := make([]uint16, dn)
  280. e := LookupAccountSid(sys, sid, &b[0], &n, &db[0], &dn, &accType)
  281. if e == nil {
  282. return UTF16ToString(b), UTF16ToString(db), accType, nil
  283. }
  284. if e != ERROR_INSUFFICIENT_BUFFER {
  285. return "", "", 0, e
  286. }
  287. if n <= uint32(len(b)) {
  288. return "", "", 0, e
  289. }
  290. }
  291. }
  292. // Various types of pre-specified SIDs that can be synthesized and compared at runtime.
  293. type WELL_KNOWN_SID_TYPE uint32
  294. const (
  295. WinNullSid = 0
  296. WinWorldSid = 1
  297. WinLocalSid = 2
  298. WinCreatorOwnerSid = 3
  299. WinCreatorGroupSid = 4
  300. WinCreatorOwnerServerSid = 5
  301. WinCreatorGroupServerSid = 6
  302. WinNtAuthoritySid = 7
  303. WinDialupSid = 8
  304. WinNetworkSid = 9
  305. WinBatchSid = 10
  306. WinInteractiveSid = 11
  307. WinServiceSid = 12
  308. WinAnonymousSid = 13
  309. WinProxySid = 14
  310. WinEnterpriseControllersSid = 15
  311. WinSelfSid = 16
  312. WinAuthenticatedUserSid = 17
  313. WinRestrictedCodeSid = 18
  314. WinTerminalServerSid = 19
  315. WinRemoteLogonIdSid = 20
  316. WinLogonIdsSid = 21
  317. WinLocalSystemSid = 22
  318. WinLocalServiceSid = 23
  319. WinNetworkServiceSid = 24
  320. WinBuiltinDomainSid = 25
  321. WinBuiltinAdministratorsSid = 26
  322. WinBuiltinUsersSid = 27
  323. WinBuiltinGuestsSid = 28
  324. WinBuiltinPowerUsersSid = 29
  325. WinBuiltinAccountOperatorsSid = 30
  326. WinBuiltinSystemOperatorsSid = 31
  327. WinBuiltinPrintOperatorsSid = 32
  328. WinBuiltinBackupOperatorsSid = 33
  329. WinBuiltinReplicatorSid = 34
  330. WinBuiltinPreWindows2000CompatibleAccessSid = 35
  331. WinBuiltinRemoteDesktopUsersSid = 36
  332. WinBuiltinNetworkConfigurationOperatorsSid = 37
  333. WinAccountAdministratorSid = 38
  334. WinAccountGuestSid = 39
  335. WinAccountKrbtgtSid = 40
  336. WinAccountDomainAdminsSid = 41
  337. WinAccountDomainUsersSid = 42
  338. WinAccountDomainGuestsSid = 43
  339. WinAccountComputersSid = 44
  340. WinAccountControllersSid = 45
  341. WinAccountCertAdminsSid = 46
  342. WinAccountSchemaAdminsSid = 47
  343. WinAccountEnterpriseAdminsSid = 48
  344. WinAccountPolicyAdminsSid = 49
  345. WinAccountRasAndIasServersSid = 50
  346. WinNTLMAuthenticationSid = 51
  347. WinDigestAuthenticationSid = 52
  348. WinSChannelAuthenticationSid = 53
  349. WinThisOrganizationSid = 54
  350. WinOtherOrganizationSid = 55
  351. WinBuiltinIncomingForestTrustBuildersSid = 56
  352. WinBuiltinPerfMonitoringUsersSid = 57
  353. WinBuiltinPerfLoggingUsersSid = 58
  354. WinBuiltinAuthorizationAccessSid = 59
  355. WinBuiltinTerminalServerLicenseServersSid = 60
  356. WinBuiltinDCOMUsersSid = 61
  357. WinBuiltinIUsersSid = 62
  358. WinIUserSid = 63
  359. WinBuiltinCryptoOperatorsSid = 64
  360. WinUntrustedLabelSid = 65
  361. WinLowLabelSid = 66
  362. WinMediumLabelSid = 67
  363. WinHighLabelSid = 68
  364. WinSystemLabelSid = 69
  365. WinWriteRestrictedCodeSid = 70
  366. WinCreatorOwnerRightsSid = 71
  367. WinCacheablePrincipalsGroupSid = 72
  368. WinNonCacheablePrincipalsGroupSid = 73
  369. WinEnterpriseReadonlyControllersSid = 74
  370. WinAccountReadonlyControllersSid = 75
  371. WinBuiltinEventLogReadersGroup = 76
  372. WinNewEnterpriseReadonlyControllersSid = 77
  373. WinBuiltinCertSvcDComAccessGroup = 78
  374. WinMediumPlusLabelSid = 79
  375. WinLocalLogonSid = 80
  376. WinConsoleLogonSid = 81
  377. WinThisOrganizationCertificateSid = 82
  378. WinApplicationPackageAuthoritySid = 83
  379. WinBuiltinAnyPackageSid = 84
  380. WinCapabilityInternetClientSid = 85
  381. WinCapabilityInternetClientServerSid = 86
  382. WinCapabilityPrivateNetworkClientServerSid = 87
  383. WinCapabilityPicturesLibrarySid = 88
  384. WinCapabilityVideosLibrarySid = 89
  385. WinCapabilityMusicLibrarySid = 90
  386. WinCapabilityDocumentsLibrarySid = 91
  387. WinCapabilitySharedUserCertificatesSid = 92
  388. WinCapabilityEnterpriseAuthenticationSid = 93
  389. WinCapabilityRemovableStorageSid = 94
  390. WinBuiltinRDSRemoteAccessServersSid = 95
  391. WinBuiltinRDSEndpointServersSid = 96
  392. WinBuiltinRDSManagementServersSid = 97
  393. WinUserModeDriversSid = 98
  394. WinBuiltinHyperVAdminsSid = 99
  395. WinAccountCloneableControllersSid = 100
  396. WinBuiltinAccessControlAssistanceOperatorsSid = 101
  397. WinBuiltinRemoteManagementUsersSid = 102
  398. WinAuthenticationAuthorityAssertedSid = 103
  399. WinAuthenticationServiceAssertedSid = 104
  400. WinLocalAccountSid = 105
  401. WinLocalAccountAndAdministratorSid = 106
  402. WinAccountProtectedUsersSid = 107
  403. WinCapabilityAppointmentsSid = 108
  404. WinCapabilityContactsSid = 109
  405. WinAccountDefaultSystemManagedSid = 110
  406. WinBuiltinDefaultSystemManagedGroupSid = 111
  407. WinBuiltinStorageReplicaAdminsSid = 112
  408. WinAccountKeyAdminsSid = 113
  409. WinAccountEnterpriseKeyAdminsSid = 114
  410. WinAuthenticationKeyTrustSid = 115
  411. WinAuthenticationKeyPropertyMFASid = 116
  412. WinAuthenticationKeyPropertyAttestationSid = 117
  413. WinAuthenticationFreshKeyAuthSid = 118
  414. WinBuiltinDeviceOwnersSid = 119
  415. )
  416. // Creates a SID for a well-known predefined alias, generally using the constants of the form
  417. // Win*Sid, for the local machine.
  418. func CreateWellKnownSid(sidType WELL_KNOWN_SID_TYPE) (*SID, error) {
  419. return CreateWellKnownDomainSid(sidType, nil)
  420. }
  421. // Creates a SID for a well-known predefined alias, generally using the constants of the form
  422. // Win*Sid, for the domain specified by the domainSid parameter.
  423. func CreateWellKnownDomainSid(sidType WELL_KNOWN_SID_TYPE, domainSid *SID) (*SID, error) {
  424. n := uint32(50)
  425. for {
  426. b := make([]byte, n)
  427. sid := (*SID)(unsafe.Pointer(&b[0]))
  428. err := createWellKnownSid(sidType, domainSid, sid, &n)
  429. if err == nil {
  430. return sid, nil
  431. }
  432. if err != ERROR_INSUFFICIENT_BUFFER {
  433. return nil, err
  434. }
  435. if n <= uint32(len(b)) {
  436. return nil, err
  437. }
  438. }
  439. }
  440. const (
  441. // do not reorder
  442. TOKEN_ASSIGN_PRIMARY = 1 << iota
  443. TOKEN_DUPLICATE
  444. TOKEN_IMPERSONATE
  445. TOKEN_QUERY
  446. TOKEN_QUERY_SOURCE
  447. TOKEN_ADJUST_PRIVILEGES
  448. TOKEN_ADJUST_GROUPS
  449. TOKEN_ADJUST_DEFAULT
  450. TOKEN_ADJUST_SESSIONID
  451. TOKEN_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED |
  452. TOKEN_ASSIGN_PRIMARY |
  453. TOKEN_DUPLICATE |
  454. TOKEN_IMPERSONATE |
  455. TOKEN_QUERY |
  456. TOKEN_QUERY_SOURCE |
  457. TOKEN_ADJUST_PRIVILEGES |
  458. TOKEN_ADJUST_GROUPS |
  459. TOKEN_ADJUST_DEFAULT |
  460. TOKEN_ADJUST_SESSIONID
  461. TOKEN_READ = STANDARD_RIGHTS_READ | TOKEN_QUERY
  462. TOKEN_WRITE = STANDARD_RIGHTS_WRITE |
  463. TOKEN_ADJUST_PRIVILEGES |
  464. TOKEN_ADJUST_GROUPS |
  465. TOKEN_ADJUST_DEFAULT
  466. TOKEN_EXECUTE = STANDARD_RIGHTS_EXECUTE
  467. )
  468. const (
  469. // do not reorder
  470. TokenUser = 1 + iota
  471. TokenGroups
  472. TokenPrivileges
  473. TokenOwner
  474. TokenPrimaryGroup
  475. TokenDefaultDacl
  476. TokenSource
  477. TokenType
  478. TokenImpersonationLevel
  479. TokenStatistics
  480. TokenRestrictedSids
  481. TokenSessionId
  482. TokenGroupsAndPrivileges
  483. TokenSessionReference
  484. TokenSandBoxInert
  485. TokenAuditPolicy
  486. TokenOrigin
  487. TokenElevationType
  488. TokenLinkedToken
  489. TokenElevation
  490. TokenHasRestrictions
  491. TokenAccessInformation
  492. TokenVirtualizationAllowed
  493. TokenVirtualizationEnabled
  494. TokenIntegrityLevel
  495. TokenUIAccess
  496. TokenMandatoryPolicy
  497. TokenLogonSid
  498. MaxTokenInfoClass
  499. )
  500. // Group attributes inside of Tokengroups.Groups[i].Attributes
  501. const (
  502. SE_GROUP_MANDATORY = 0x00000001
  503. SE_GROUP_ENABLED_BY_DEFAULT = 0x00000002
  504. SE_GROUP_ENABLED = 0x00000004
  505. SE_GROUP_OWNER = 0x00000008
  506. SE_GROUP_USE_FOR_DENY_ONLY = 0x00000010
  507. SE_GROUP_INTEGRITY = 0x00000020
  508. SE_GROUP_INTEGRITY_ENABLED = 0x00000040
  509. SE_GROUP_LOGON_ID = 0xC0000000
  510. SE_GROUP_RESOURCE = 0x20000000
  511. SE_GROUP_VALID_ATTRIBUTES = SE_GROUP_MANDATORY | SE_GROUP_ENABLED_BY_DEFAULT | SE_GROUP_ENABLED | SE_GROUP_OWNER | SE_GROUP_USE_FOR_DENY_ONLY | SE_GROUP_LOGON_ID | SE_GROUP_RESOURCE | SE_GROUP_INTEGRITY | SE_GROUP_INTEGRITY_ENABLED
  512. )
  513. // Privilege attributes
  514. const (
  515. SE_PRIVILEGE_ENABLED_BY_DEFAULT = 0x00000001
  516. SE_PRIVILEGE_ENABLED = 0x00000002
  517. SE_PRIVILEGE_REMOVED = 0x00000004
  518. SE_PRIVILEGE_USED_FOR_ACCESS = 0x80000000
  519. SE_PRIVILEGE_VALID_ATTRIBUTES = SE_PRIVILEGE_ENABLED_BY_DEFAULT | SE_PRIVILEGE_ENABLED | SE_PRIVILEGE_REMOVED | SE_PRIVILEGE_USED_FOR_ACCESS
  520. )
  521. // Token types
  522. const (
  523. TokenPrimary = 1
  524. TokenImpersonation = 2
  525. )
  526. // Impersonation levels
  527. const (
  528. SecurityAnonymous = 0
  529. SecurityIdentification = 1
  530. SecurityImpersonation = 2
  531. SecurityDelegation = 3
  532. )
  533. type LUID struct {
  534. LowPart uint32
  535. HighPart int32
  536. }
  537. type LUIDAndAttributes struct {
  538. Luid LUID
  539. Attributes uint32
  540. }
  541. type SIDAndAttributes struct {
  542. Sid *SID
  543. Attributes uint32
  544. }
  545. type Tokenuser struct {
  546. User SIDAndAttributes
  547. }
  548. type Tokenprimarygroup struct {
  549. PrimaryGroup *SID
  550. }
  551. type Tokengroups struct {
  552. GroupCount uint32
  553. Groups [1]SIDAndAttributes // Use AllGroups() for iterating.
  554. }
  555. // AllGroups returns a slice that can be used to iterate over the groups in g.
  556. func (g *Tokengroups) AllGroups() []SIDAndAttributes {
  557. return (*[(1 << 28) - 1]SIDAndAttributes)(unsafe.Pointer(&g.Groups[0]))[:g.GroupCount:g.GroupCount]
  558. }
  559. type Tokenprivileges struct {
  560. PrivilegeCount uint32
  561. Privileges [1]LUIDAndAttributes // Use AllPrivileges() for iterating.
  562. }
  563. // AllPrivileges returns a slice that can be used to iterate over the privileges in p.
  564. func (p *Tokenprivileges) AllPrivileges() []LUIDAndAttributes {
  565. return (*[(1 << 27) - 1]LUIDAndAttributes)(unsafe.Pointer(&p.Privileges[0]))[:p.PrivilegeCount:p.PrivilegeCount]
  566. }
  567. type Tokenmandatorylabel struct {
  568. Label SIDAndAttributes
  569. }
  570. func (tml *Tokenmandatorylabel) Size() uint32 {
  571. return uint32(unsafe.Sizeof(Tokenmandatorylabel{})) + GetLengthSid(tml.Label.Sid)
  572. }
  573. // Authorization Functions
  574. //sys checkTokenMembership(tokenHandle Token, sidToCheck *SID, isMember *int32) (err error) = advapi32.CheckTokenMembership
  575. //sys isTokenRestricted(tokenHandle Token) (ret bool, err error) [!failretval] = advapi32.IsTokenRestricted
  576. //sys OpenProcessToken(process Handle, access uint32, token *Token) (err error) = advapi32.OpenProcessToken
  577. //sys OpenThreadToken(thread Handle, access uint32, openAsSelf bool, token *Token) (err error) = advapi32.OpenThreadToken
  578. //sys ImpersonateSelf(impersonationlevel uint32) (err error) = advapi32.ImpersonateSelf
  579. //sys RevertToSelf() (err error) = advapi32.RevertToSelf
  580. //sys SetThreadToken(thread *Handle, token Token) (err error) = advapi32.SetThreadToken
  581. //sys LookupPrivilegeValue(systemname *uint16, name *uint16, luid *LUID) (err error) = advapi32.LookupPrivilegeValueW
  582. //sys AdjustTokenPrivileges(token Token, disableAllPrivileges bool, newstate *Tokenprivileges, buflen uint32, prevstate *Tokenprivileges, returnlen *uint32) (err error) = advapi32.AdjustTokenPrivileges
  583. //sys AdjustTokenGroups(token Token, resetToDefault bool, newstate *Tokengroups, buflen uint32, prevstate *Tokengroups, returnlen *uint32) (err error) = advapi32.AdjustTokenGroups
  584. //sys GetTokenInformation(token Token, infoClass uint32, info *byte, infoLen uint32, returnedLen *uint32) (err error) = advapi32.GetTokenInformation
  585. //sys SetTokenInformation(token Token, infoClass uint32, info *byte, infoLen uint32) (err error) = advapi32.SetTokenInformation
  586. //sys DuplicateTokenEx(existingToken Token, desiredAccess uint32, tokenAttributes *SecurityAttributes, impersonationLevel uint32, tokenType uint32, newToken *Token) (err error) = advapi32.DuplicateTokenEx
  587. //sys GetUserProfileDirectory(t Token, dir *uint16, dirLen *uint32) (err error) = userenv.GetUserProfileDirectoryW
  588. //sys getSystemDirectory(dir *uint16, dirLen uint32) (len uint32, err error) = kernel32.GetSystemDirectoryW
  589. //sys getWindowsDirectory(dir *uint16, dirLen uint32) (len uint32, err error) = kernel32.GetWindowsDirectoryW
  590. //sys getSystemWindowsDirectory(dir *uint16, dirLen uint32) (len uint32, err error) = kernel32.GetSystemWindowsDirectoryW
  591. // An access token contains the security information for a logon session.
  592. // The system creates an access token when a user logs on, and every
  593. // process executed on behalf of the user has a copy of the token.
  594. // The token identifies the user, the user's groups, and the user's
  595. // privileges. The system uses the token to control access to securable
  596. // objects and to control the ability of the user to perform various
  597. // system-related operations on the local computer.
  598. type Token Handle
  599. // OpenCurrentProcessToken opens an access token associated with current
  600. // process with TOKEN_QUERY access. It is a real token that needs to be closed.
  601. //
  602. // Deprecated: Explicitly call OpenProcessToken(CurrentProcess(), ...)
  603. // with the desired access instead, or use GetCurrentProcessToken for a
  604. // TOKEN_QUERY token.
  605. func OpenCurrentProcessToken() (Token, error) {
  606. var token Token
  607. err := OpenProcessToken(CurrentProcess(), TOKEN_QUERY, &token)
  608. return token, err
  609. }
  610. // GetCurrentProcessToken returns the access token associated with
  611. // the current process. It is a pseudo token that does not need
  612. // to be closed.
  613. func GetCurrentProcessToken() Token {
  614. return Token(^uintptr(4 - 1))
  615. }
  616. // GetCurrentThreadToken return the access token associated with
  617. // the current thread. It is a pseudo token that does not need
  618. // to be closed.
  619. func GetCurrentThreadToken() Token {
  620. return Token(^uintptr(5 - 1))
  621. }
  622. // GetCurrentThreadEffectiveToken returns the effective access token
  623. // associated with the current thread. It is a pseudo token that does
  624. // not need to be closed.
  625. func GetCurrentThreadEffectiveToken() Token {
  626. return Token(^uintptr(6 - 1))
  627. }
  628. // Close releases access to access token.
  629. func (t Token) Close() error {
  630. return CloseHandle(Handle(t))
  631. }
  632. // getInfo retrieves a specified type of information about an access token.
  633. func (t Token) getInfo(class uint32, initSize int) (unsafe.Pointer, error) {
  634. n := uint32(initSize)
  635. for {
  636. b := make([]byte, n)
  637. e := GetTokenInformation(t, class, &b[0], uint32(len(b)), &n)
  638. if e == nil {
  639. return unsafe.Pointer(&b[0]), nil
  640. }
  641. if e != ERROR_INSUFFICIENT_BUFFER {
  642. return nil, e
  643. }
  644. if n <= uint32(len(b)) {
  645. return nil, e
  646. }
  647. }
  648. }
  649. // GetTokenUser retrieves access token t user account information.
  650. func (t Token) GetTokenUser() (*Tokenuser, error) {
  651. i, e := t.getInfo(TokenUser, 50)
  652. if e != nil {
  653. return nil, e
  654. }
  655. return (*Tokenuser)(i), nil
  656. }
  657. // GetTokenGroups retrieves group accounts associated with access token t.
  658. func (t Token) GetTokenGroups() (*Tokengroups, error) {
  659. i, e := t.getInfo(TokenGroups, 50)
  660. if e != nil {
  661. return nil, e
  662. }
  663. return (*Tokengroups)(i), nil
  664. }
  665. // GetTokenPrimaryGroup retrieves access token t primary group information.
  666. // A pointer to a SID structure representing a group that will become
  667. // the primary group of any objects created by a process using this access token.
  668. func (t Token) GetTokenPrimaryGroup() (*Tokenprimarygroup, error) {
  669. i, e := t.getInfo(TokenPrimaryGroup, 50)
  670. if e != nil {
  671. return nil, e
  672. }
  673. return (*Tokenprimarygroup)(i), nil
  674. }
  675. // GetUserProfileDirectory retrieves path to the
  676. // root directory of the access token t user's profile.
  677. func (t Token) GetUserProfileDirectory() (string, error) {
  678. n := uint32(100)
  679. for {
  680. b := make([]uint16, n)
  681. e := GetUserProfileDirectory(t, &b[0], &n)
  682. if e == nil {
  683. return UTF16ToString(b), nil
  684. }
  685. if e != ERROR_INSUFFICIENT_BUFFER {
  686. return "", e
  687. }
  688. if n <= uint32(len(b)) {
  689. return "", e
  690. }
  691. }
  692. }
  693. // IsElevated returns whether the current token is elevated from a UAC perspective.
  694. func (token Token) IsElevated() bool {
  695. var isElevated uint32
  696. var outLen uint32
  697. err := GetTokenInformation(token, TokenElevation, (*byte)(unsafe.Pointer(&isElevated)), uint32(unsafe.Sizeof(isElevated)), &outLen)
  698. if err != nil {
  699. return false
  700. }
  701. return outLen == uint32(unsafe.Sizeof(isElevated)) && isElevated != 0
  702. }
  703. // GetLinkedToken returns the linked token, which may be an elevated UAC token.
  704. func (token Token) GetLinkedToken() (Token, error) {
  705. var linkedToken Token
  706. var outLen uint32
  707. err := GetTokenInformation(token, TokenLinkedToken, (*byte)(unsafe.Pointer(&linkedToken)), uint32(unsafe.Sizeof(linkedToken)), &outLen)
  708. if err != nil {
  709. return Token(0), err
  710. }
  711. return linkedToken, nil
  712. }
  713. // GetSystemDirectory retrieves the path to current location of the system
  714. // directory, which is typically, though not always, `C:\Windows\System32`.
  715. func GetSystemDirectory() (string, error) {
  716. n := uint32(MAX_PATH)
  717. for {
  718. b := make([]uint16, n)
  719. l, e := getSystemDirectory(&b[0], n)
  720. if e != nil {
  721. return "", e
  722. }
  723. if l <= n {
  724. return UTF16ToString(b[:l]), nil
  725. }
  726. n = l
  727. }
  728. }
  729. // GetWindowsDirectory retrieves the path to current location of the Windows
  730. // directory, which is typically, though not always, `C:\Windows`. This may
  731. // be a private user directory in the case that the application is running
  732. // under a terminal server.
  733. func GetWindowsDirectory() (string, error) {
  734. n := uint32(MAX_PATH)
  735. for {
  736. b := make([]uint16, n)
  737. l, e := getWindowsDirectory(&b[0], n)
  738. if e != nil {
  739. return "", e
  740. }
  741. if l <= n {
  742. return UTF16ToString(b[:l]), nil
  743. }
  744. n = l
  745. }
  746. }
  747. // GetSystemWindowsDirectory retrieves the path to current location of the
  748. // Windows directory, which is typically, though not always, `C:\Windows`.
  749. func GetSystemWindowsDirectory() (string, error) {
  750. n := uint32(MAX_PATH)
  751. for {
  752. b := make([]uint16, n)
  753. l, e := getSystemWindowsDirectory(&b[0], n)
  754. if e != nil {
  755. return "", e
  756. }
  757. if l <= n {
  758. return UTF16ToString(b[:l]), nil
  759. }
  760. n = l
  761. }
  762. }
  763. // IsMember reports whether the access token t is a member of the provided SID.
  764. func (t Token) IsMember(sid *SID) (bool, error) {
  765. var b int32
  766. if e := checkTokenMembership(t, sid, &b); e != nil {
  767. return false, e
  768. }
  769. return b != 0, nil
  770. }
  771. // IsRestricted reports whether the access token t is a restricted token.
  772. func (t Token) IsRestricted() (isRestricted bool, err error) {
  773. isRestricted, err = isTokenRestricted(t)
  774. if !isRestricted && err == syscall.EINVAL {
  775. // If err is EINVAL, this returned ERROR_SUCCESS indicating a non-restricted token.
  776. err = nil
  777. }
  778. return
  779. }
  780. const (
  781. WTS_CONSOLE_CONNECT = 0x1
  782. WTS_CONSOLE_DISCONNECT = 0x2
  783. WTS_REMOTE_CONNECT = 0x3
  784. WTS_REMOTE_DISCONNECT = 0x4
  785. WTS_SESSION_LOGON = 0x5
  786. WTS_SESSION_LOGOFF = 0x6
  787. WTS_SESSION_LOCK = 0x7
  788. WTS_SESSION_UNLOCK = 0x8
  789. WTS_SESSION_REMOTE_CONTROL = 0x9
  790. WTS_SESSION_CREATE = 0xa
  791. WTS_SESSION_TERMINATE = 0xb
  792. )
  793. const (
  794. WTSActive = 0
  795. WTSConnected = 1
  796. WTSConnectQuery = 2
  797. WTSShadow = 3
  798. WTSDisconnected = 4
  799. WTSIdle = 5
  800. WTSListen = 6
  801. WTSReset = 7
  802. WTSDown = 8
  803. WTSInit = 9
  804. )
  805. type WTSSESSION_NOTIFICATION struct {
  806. Size uint32
  807. SessionID uint32
  808. }
  809. type WTS_SESSION_INFO struct {
  810. SessionID uint32
  811. WindowStationName *uint16
  812. State uint32
  813. }
  814. //sys WTSQueryUserToken(session uint32, token *Token) (err error) = wtsapi32.WTSQueryUserToken
  815. //sys WTSEnumerateSessions(handle Handle, reserved uint32, version uint32, sessions **WTS_SESSION_INFO, count *uint32) (err error) = wtsapi32.WTSEnumerateSessionsW
  816. //sys WTSFreeMemory(ptr uintptr) = wtsapi32.WTSFreeMemory
  817. //sys WTSGetActiveConsoleSessionId() (sessionID uint32)
  818. type ACL struct {
  819. aclRevision byte
  820. sbz1 byte
  821. aclSize uint16
  822. aceCount uint16
  823. sbz2 uint16
  824. }
  825. type SECURITY_DESCRIPTOR struct {
  826. revision byte
  827. sbz1 byte
  828. control SECURITY_DESCRIPTOR_CONTROL
  829. owner *SID
  830. group *SID
  831. sacl *ACL
  832. dacl *ACL
  833. }
  834. type SECURITY_QUALITY_OF_SERVICE struct {
  835. Length uint32
  836. ImpersonationLevel uint32
  837. ContextTrackingMode byte
  838. EffectiveOnly byte
  839. }
  840. // Constants for the ContextTrackingMode field of SECURITY_QUALITY_OF_SERVICE.
  841. const (
  842. SECURITY_STATIC_TRACKING = 0
  843. SECURITY_DYNAMIC_TRACKING = 1
  844. )
  845. type SecurityAttributes struct {
  846. Length uint32
  847. SecurityDescriptor *SECURITY_DESCRIPTOR
  848. InheritHandle uint32
  849. }
  850. type SE_OBJECT_TYPE uint32
  851. // Constants for type SE_OBJECT_TYPE
  852. const (
  853. SE_UNKNOWN_OBJECT_TYPE = 0
  854. SE_FILE_OBJECT = 1
  855. SE_SERVICE = 2
  856. SE_PRINTER = 3
  857. SE_REGISTRY_KEY = 4
  858. SE_LMSHARE = 5
  859. SE_KERNEL_OBJECT = 6
  860. SE_WINDOW_OBJECT = 7
  861. SE_DS_OBJECT = 8
  862. SE_DS_OBJECT_ALL = 9
  863. SE_PROVIDER_DEFINED_OBJECT = 10
  864. SE_WMIGUID_OBJECT = 11
  865. SE_REGISTRY_WOW64_32KEY = 12
  866. SE_REGISTRY_WOW64_64KEY = 13
  867. )
  868. type SECURITY_INFORMATION uint32
  869. // Constants for type SECURITY_INFORMATION
  870. const (
  871. OWNER_SECURITY_INFORMATION = 0x00000001
  872. GROUP_SECURITY_INFORMATION = 0x00000002
  873. DACL_SECURITY_INFORMATION = 0x00000004
  874. SACL_SECURITY_INFORMATION = 0x00000008
  875. LABEL_SECURITY_INFORMATION = 0x00000010
  876. ATTRIBUTE_SECURITY_INFORMATION = 0x00000020
  877. SCOPE_SECURITY_INFORMATION = 0x00000040
  878. BACKUP_SECURITY_INFORMATION = 0x00010000
  879. PROTECTED_DACL_SECURITY_INFORMATION = 0x80000000
  880. PROTECTED_SACL_SECURITY_INFORMATION = 0x40000000
  881. UNPROTECTED_DACL_SECURITY_INFORMATION = 0x20000000
  882. UNPROTECTED_SACL_SECURITY_INFORMATION = 0x10000000
  883. )
  884. type SECURITY_DESCRIPTOR_CONTROL uint16
  885. // Constants for type SECURITY_DESCRIPTOR_CONTROL
  886. const (
  887. SE_OWNER_DEFAULTED = 0x0001
  888. SE_GROUP_DEFAULTED = 0x0002
  889. SE_DACL_PRESENT = 0x0004
  890. SE_DACL_DEFAULTED = 0x0008
  891. SE_SACL_PRESENT = 0x0010
  892. SE_SACL_DEFAULTED = 0x0020
  893. SE_DACL_AUTO_INHERIT_REQ = 0x0100
  894. SE_SACL_AUTO_INHERIT_REQ = 0x0200
  895. SE_DACL_AUTO_INHERITED = 0x0400
  896. SE_SACL_AUTO_INHERITED = 0x0800
  897. SE_DACL_PROTECTED = 0x1000
  898. SE_SACL_PROTECTED = 0x2000
  899. SE_RM_CONTROL_VALID = 0x4000
  900. SE_SELF_RELATIVE = 0x8000
  901. )
  902. type ACCESS_MASK uint32
  903. // Constants for type ACCESS_MASK
  904. const (
  905. DELETE = 0x00010000
  906. READ_CONTROL = 0x00020000
  907. WRITE_DAC = 0x00040000
  908. WRITE_OWNER = 0x00080000
  909. SYNCHRONIZE = 0x00100000
  910. STANDARD_RIGHTS_REQUIRED = 0x000F0000
  911. STANDARD_RIGHTS_READ = READ_CONTROL
  912. STANDARD_RIGHTS_WRITE = READ_CONTROL
  913. STANDARD_RIGHTS_EXECUTE = READ_CONTROL
  914. STANDARD_RIGHTS_ALL = 0x001F0000
  915. SPECIFIC_RIGHTS_ALL = 0x0000FFFF
  916. ACCESS_SYSTEM_SECURITY = 0x01000000
  917. MAXIMUM_ALLOWED = 0x02000000
  918. GENERIC_READ = 0x80000000
  919. GENERIC_WRITE = 0x40000000
  920. GENERIC_EXECUTE = 0x20000000
  921. GENERIC_ALL = 0x10000000
  922. )
  923. type ACCESS_MODE uint32
  924. // Constants for type ACCESS_MODE
  925. const (
  926. NOT_USED_ACCESS = 0
  927. GRANT_ACCESS = 1
  928. SET_ACCESS = 2
  929. DENY_ACCESS = 3
  930. REVOKE_ACCESS = 4
  931. SET_AUDIT_SUCCESS = 5
  932. SET_AUDIT_FAILURE = 6
  933. )
  934. // Constants for AceFlags and Inheritance fields
  935. const (
  936. NO_INHERITANCE = 0x0
  937. SUB_OBJECTS_ONLY_INHERIT = 0x1
  938. SUB_CONTAINERS_ONLY_INHERIT = 0x2
  939. SUB_CONTAINERS_AND_OBJECTS_INHERIT = 0x3
  940. INHERIT_NO_PROPAGATE = 0x4
  941. INHERIT_ONLY = 0x8
  942. INHERITED_ACCESS_ENTRY = 0x10
  943. INHERITED_PARENT = 0x10000000
  944. INHERITED_GRANDPARENT = 0x20000000
  945. OBJECT_INHERIT_ACE = 0x1
  946. CONTAINER_INHERIT_ACE = 0x2
  947. NO_PROPAGATE_INHERIT_ACE = 0x4
  948. INHERIT_ONLY_ACE = 0x8
  949. INHERITED_ACE = 0x10
  950. VALID_INHERIT_FLAGS = 0x1F
  951. )
  952. type MULTIPLE_TRUSTEE_OPERATION uint32
  953. // Constants for MULTIPLE_TRUSTEE_OPERATION
  954. const (
  955. NO_MULTIPLE_TRUSTEE = 0
  956. TRUSTEE_IS_IMPERSONATE = 1
  957. )
  958. type TRUSTEE_FORM uint32
  959. // Constants for TRUSTEE_FORM
  960. const (
  961. TRUSTEE_IS_SID = 0
  962. TRUSTEE_IS_NAME = 1
  963. TRUSTEE_BAD_FORM = 2
  964. TRUSTEE_IS_OBJECTS_AND_SID = 3
  965. TRUSTEE_IS_OBJECTS_AND_NAME = 4
  966. )
  967. type TRUSTEE_TYPE uint32
  968. // Constants for TRUSTEE_TYPE
  969. const (
  970. TRUSTEE_IS_UNKNOWN = 0
  971. TRUSTEE_IS_USER = 1
  972. TRUSTEE_IS_GROUP = 2
  973. TRUSTEE_IS_DOMAIN = 3
  974. TRUSTEE_IS_ALIAS = 4
  975. TRUSTEE_IS_WELL_KNOWN_GROUP = 5
  976. TRUSTEE_IS_DELETED = 6
  977. TRUSTEE_IS_INVALID = 7
  978. TRUSTEE_IS_COMPUTER = 8
  979. )
  980. // Constants for ObjectsPresent field
  981. const (
  982. ACE_OBJECT_TYPE_PRESENT = 0x1
  983. ACE_INHERITED_OBJECT_TYPE_PRESENT = 0x2
  984. )
  985. type EXPLICIT_ACCESS struct {
  986. AccessPermissions ACCESS_MASK
  987. AccessMode ACCESS_MODE
  988. Inheritance uint32
  989. Trustee TRUSTEE
  990. }
  991. // This type is the union inside of TRUSTEE and must be created using one of the TrusteeValueFrom* functions.
  992. type TrusteeValue uintptr
  993. func TrusteeValueFromString(str string) TrusteeValue {
  994. return TrusteeValue(unsafe.Pointer(StringToUTF16Ptr(str)))
  995. }
  996. func TrusteeValueFromSID(sid *SID) TrusteeValue {
  997. return TrusteeValue(unsafe.Pointer(sid))
  998. }
  999. func TrusteeValueFromObjectsAndSid(objectsAndSid *OBJECTS_AND_SID) TrusteeValue {
  1000. return TrusteeValue(unsafe.Pointer(objectsAndSid))
  1001. }
  1002. func TrusteeValueFromObjectsAndName(objectsAndName *OBJECTS_AND_NAME) TrusteeValue {
  1003. return TrusteeValue(unsafe.Pointer(objectsAndName))
  1004. }
  1005. type TRUSTEE struct {
  1006. MultipleTrustee *TRUSTEE
  1007. MultipleTrusteeOperation MULTIPLE_TRUSTEE_OPERATION
  1008. TrusteeForm TRUSTEE_FORM
  1009. TrusteeType TRUSTEE_TYPE
  1010. TrusteeValue TrusteeValue
  1011. }
  1012. type OBJECTS_AND_SID struct {
  1013. ObjectsPresent uint32
  1014. ObjectTypeGuid GUID
  1015. InheritedObjectTypeGuid GUID
  1016. Sid *SID
  1017. }
  1018. type OBJECTS_AND_NAME struct {
  1019. ObjectsPresent uint32
  1020. ObjectType SE_OBJECT_TYPE
  1021. ObjectTypeName *uint16
  1022. InheritedObjectTypeName *uint16
  1023. Name *uint16
  1024. }
  1025. //sys getSecurityInfo(handle Handle, objectType SE_OBJECT_TYPE, securityInformation SECURITY_INFORMATION, owner **SID, group **SID, dacl **ACL, sacl **ACL, sd **SECURITY_DESCRIPTOR) (ret error) = advapi32.GetSecurityInfo
  1026. //sys SetSecurityInfo(handle Handle, objectType SE_OBJECT_TYPE, securityInformation SECURITY_INFORMATION, owner *SID, group *SID, dacl *ACL, sacl *ACL) (ret error) = advapi32.SetSecurityInfo
  1027. //sys getNamedSecurityInfo(objectName string, objectType SE_OBJECT_TYPE, securityInformation SECURITY_INFORMATION, owner **SID, group **SID, dacl **ACL, sacl **ACL, sd **SECURITY_DESCRIPTOR) (ret error) = advapi32.GetNamedSecurityInfoW
  1028. //sys SetNamedSecurityInfo(objectName string, objectType SE_OBJECT_TYPE, securityInformation SECURITY_INFORMATION, owner *SID, group *SID, dacl *ACL, sacl *ACL) (ret error) = advapi32.SetNamedSecurityInfoW
  1029. //sys SetKernelObjectSecurity(handle Handle, securityInformation SECURITY_INFORMATION, securityDescriptor *SECURITY_DESCRIPTOR) (err error) = advapi32.SetKernelObjectSecurity
  1030. //sys buildSecurityDescriptor(owner *TRUSTEE, group *TRUSTEE, countAccessEntries uint32, accessEntries *EXPLICIT_ACCESS, countAuditEntries uint32, auditEntries *EXPLICIT_ACCESS, oldSecurityDescriptor *SECURITY_DESCRIPTOR, sizeNewSecurityDescriptor *uint32, newSecurityDescriptor **SECURITY_DESCRIPTOR) (ret error) = advapi32.BuildSecurityDescriptorW
  1031. //sys initializeSecurityDescriptor(absoluteSD *SECURITY_DESCRIPTOR, revision uint32) (err error) = advapi32.InitializeSecurityDescriptor
  1032. //sys getSecurityDescriptorControl(sd *SECURITY_DESCRIPTOR, control *SECURITY_DESCRIPTOR_CONTROL, revision *uint32) (err error) = advapi32.GetSecurityDescriptorControl
  1033. //sys getSecurityDescriptorDacl(sd *SECURITY_DESCRIPTOR, daclPresent *bool, dacl **ACL, daclDefaulted *bool) (err error) = advapi32.GetSecurityDescriptorDacl
  1034. //sys getSecurityDescriptorSacl(sd *SECURITY_DESCRIPTOR, saclPresent *bool, sacl **ACL, saclDefaulted *bool) (err error) = advapi32.GetSecurityDescriptorSacl
  1035. //sys getSecurityDescriptorOwner(sd *SECURITY_DESCRIPTOR, owner **SID, ownerDefaulted *bool) (err error) = advapi32.GetSecurityDescriptorOwner
  1036. //sys getSecurityDescriptorGroup(sd *SECURITY_DESCRIPTOR, group **SID, groupDefaulted *bool) (err error) = advapi32.GetSecurityDescriptorGroup
  1037. //sys getSecurityDescriptorLength(sd *SECURITY_DESCRIPTOR) (len uint32) = advapi32.GetSecurityDescriptorLength
  1038. //sys getSecurityDescriptorRMControl(sd *SECURITY_DESCRIPTOR, rmControl *uint8) (ret error) [failretval!=0] = advapi32.GetSecurityDescriptorRMControl
  1039. //sys isValidSecurityDescriptor(sd *SECURITY_DESCRIPTOR) (isValid bool) = advapi32.IsValidSecurityDescriptor
  1040. //sys setSecurityDescriptorControl(sd *SECURITY_DESCRIPTOR, controlBitsOfInterest SECURITY_DESCRIPTOR_CONTROL, controlBitsToSet SECURITY_DESCRIPTOR_CONTROL) (err error) = advapi32.SetSecurityDescriptorControl
  1041. //sys setSecurityDescriptorDacl(sd *SECURITY_DESCRIPTOR, daclPresent bool, dacl *ACL, daclDefaulted bool) (err error) = advapi32.SetSecurityDescriptorDacl
  1042. //sys setSecurityDescriptorSacl(sd *SECURITY_DESCRIPTOR, saclPresent bool, sacl *ACL, saclDefaulted bool) (err error) = advapi32.SetSecurityDescriptorSacl
  1043. //sys setSecurityDescriptorOwner(sd *SECURITY_DESCRIPTOR, owner *SID, ownerDefaulted bool) (err error) = advapi32.SetSecurityDescriptorOwner
  1044. //sys setSecurityDescriptorGroup(sd *SECURITY_DESCRIPTOR, group *SID, groupDefaulted bool) (err error) = advapi32.SetSecurityDescriptorGroup
  1045. //sys setSecurityDescriptorRMControl(sd *SECURITY_DESCRIPTOR, rmControl *uint8) = advapi32.SetSecurityDescriptorRMControl
  1046. //sys convertStringSecurityDescriptorToSecurityDescriptor(str string, revision uint32, sd **SECURITY_DESCRIPTOR, size *uint32) (err error) = advapi32.ConvertStringSecurityDescriptorToSecurityDescriptorW
  1047. //sys convertSecurityDescriptorToStringSecurityDescriptor(sd *SECURITY_DESCRIPTOR, revision uint32, securityInformation SECURITY_INFORMATION, str **uint16, strLen *uint32) (err error) = advapi32.ConvertSecurityDescriptorToStringSecurityDescriptorW
  1048. //sys makeAbsoluteSD(selfRelativeSD *SECURITY_DESCRIPTOR, absoluteSD *SECURITY_DESCRIPTOR, absoluteSDSize *uint32, dacl *ACL, daclSize *uint32, sacl *ACL, saclSize *uint32, owner *SID, ownerSize *uint32, group *SID, groupSize *uint32) (err error) = advapi32.MakeAbsoluteSD
  1049. //sys makeSelfRelativeSD(absoluteSD *SECURITY_DESCRIPTOR, selfRelativeSD *SECURITY_DESCRIPTOR, selfRelativeSDSize *uint32) (err error) = advapi32.MakeSelfRelativeSD
  1050. //sys setEntriesInAcl(countExplicitEntries uint32, explicitEntries *EXPLICIT_ACCESS, oldACL *ACL, newACL **ACL) (ret error) = advapi32.SetEntriesInAclW
  1051. // Control returns the security descriptor control bits.
  1052. func (sd *SECURITY_DESCRIPTOR) Control() (control SECURITY_DESCRIPTOR_CONTROL, revision uint32, err error) {
  1053. err = getSecurityDescriptorControl(sd, &control, &revision)
  1054. return
  1055. }
  1056. // SetControl sets the security descriptor control bits.
  1057. func (sd *SECURITY_DESCRIPTOR) SetControl(controlBitsOfInterest SECURITY_DESCRIPTOR_CONTROL, controlBitsToSet SECURITY_DESCRIPTOR_CONTROL) error {
  1058. return setSecurityDescriptorControl(sd, controlBitsOfInterest, controlBitsToSet)
  1059. }
  1060. // RMControl returns the security descriptor resource manager control bits.
  1061. func (sd *SECURITY_DESCRIPTOR) RMControl() (control uint8, err error) {
  1062. err = getSecurityDescriptorRMControl(sd, &control)
  1063. return
  1064. }
  1065. // SetRMControl sets the security descriptor resource manager control bits.
  1066. func (sd *SECURITY_DESCRIPTOR) SetRMControl(rmControl uint8) {
  1067. setSecurityDescriptorRMControl(sd, &rmControl)
  1068. }
  1069. // DACL returns the security descriptor DACL and whether it was defaulted. The dacl return value may be nil
  1070. // if a DACL exists but is an "empty DACL", meaning fully permissive. If the DACL does not exist, err returns
  1071. // ERROR_OBJECT_NOT_FOUND.
  1072. func (sd *SECURITY_DESCRIPTOR) DACL() (dacl *ACL, defaulted bool, err error) {
  1073. var present bool
  1074. err = getSecurityDescriptorDacl(sd, &present, &dacl, &defaulted)
  1075. if !present {
  1076. err = ERROR_OBJECT_NOT_FOUND
  1077. }
  1078. return
  1079. }
  1080. // SetDACL sets the absolute security descriptor DACL.
  1081. func (absoluteSD *SECURITY_DESCRIPTOR) SetDACL(dacl *ACL, present, defaulted bool) error {
  1082. return setSecurityDescriptorDacl(absoluteSD, present, dacl, defaulted)
  1083. }
  1084. // SACL returns the security descriptor SACL and whether it was defaulted. The sacl return value may be nil
  1085. // if a SACL exists but is an "empty SACL", meaning fully permissive. If the SACL does not exist, err returns
  1086. // ERROR_OBJECT_NOT_FOUND.
  1087. func (sd *SECURITY_DESCRIPTOR) SACL() (sacl *ACL, defaulted bool, err error) {
  1088. var present bool
  1089. err = getSecurityDescriptorSacl(sd, &present, &sacl, &defaulted)
  1090. if !present {
  1091. err = ERROR_OBJECT_NOT_FOUND
  1092. }
  1093. return
  1094. }
  1095. // SetSACL sets the absolute security descriptor SACL.
  1096. func (absoluteSD *SECURITY_DESCRIPTOR) SetSACL(sacl *ACL, present, defaulted bool) error {
  1097. return setSecurityDescriptorSacl(absoluteSD, present, sacl, defaulted)
  1098. }
  1099. // Owner returns the security descriptor owner and whether it was defaulted.
  1100. func (sd *SECURITY_DESCRIPTOR) Owner() (owner *SID, defaulted bool, err error) {
  1101. err = getSecurityDescriptorOwner(sd, &owner, &defaulted)
  1102. return
  1103. }
  1104. // SetOwner sets the absolute security descriptor owner.
  1105. func (absoluteSD *SECURITY_DESCRIPTOR) SetOwner(owner *SID, defaulted bool) error {
  1106. return setSecurityDescriptorOwner(absoluteSD, owner, defaulted)
  1107. }
  1108. // Group returns the security descriptor group and whether it was defaulted.
  1109. func (sd *SECURITY_DESCRIPTOR) Group() (group *SID, defaulted bool, err error) {
  1110. err = getSecurityDescriptorGroup(sd, &group, &defaulted)
  1111. return
  1112. }
  1113. // SetGroup sets the absolute security descriptor owner.
  1114. func (absoluteSD *SECURITY_DESCRIPTOR) SetGroup(group *SID, defaulted bool) error {
  1115. return setSecurityDescriptorGroup(absoluteSD, group, defaulted)
  1116. }
  1117. // Length returns the length of the security descriptor.
  1118. func (sd *SECURITY_DESCRIPTOR) Length() uint32 {
  1119. return getSecurityDescriptorLength(sd)
  1120. }
  1121. // IsValid returns whether the security descriptor is valid.
  1122. func (sd *SECURITY_DESCRIPTOR) IsValid() bool {
  1123. return isValidSecurityDescriptor(sd)
  1124. }
  1125. // String returns the SDDL form of the security descriptor, with a function signature that can be
  1126. // used with %v formatting directives.
  1127. func (sd *SECURITY_DESCRIPTOR) String() string {
  1128. var sddl *uint16
  1129. err := convertSecurityDescriptorToStringSecurityDescriptor(sd, 1, 0xff, &sddl, nil)
  1130. if err != nil {
  1131. return ""
  1132. }
  1133. defer LocalFree(Handle(unsafe.Pointer(sddl)))
  1134. return UTF16PtrToString(sddl)
  1135. }
  1136. // ToAbsolute converts a self-relative security descriptor into an absolute one.
  1137. func (selfRelativeSD *SECURITY_DESCRIPTOR) ToAbsolute() (absoluteSD *SECURITY_DESCRIPTOR, err error) {
  1138. control, _, err := selfRelativeSD.Control()
  1139. if err != nil {
  1140. return
  1141. }
  1142. if control&SE_SELF_RELATIVE == 0 {
  1143. err = ERROR_INVALID_PARAMETER
  1144. return
  1145. }
  1146. var absoluteSDSize, daclSize, saclSize, ownerSize, groupSize uint32
  1147. err = makeAbsoluteSD(selfRelativeSD, nil, &absoluteSDSize,
  1148. nil, &daclSize, nil, &saclSize, nil, &ownerSize, nil, &groupSize)
  1149. switch err {
  1150. case ERROR_INSUFFICIENT_BUFFER:
  1151. case nil:
  1152. // makeAbsoluteSD is expected to fail, but it succeeds.
  1153. return nil, ERROR_INTERNAL_ERROR
  1154. default:
  1155. return nil, err
  1156. }
  1157. if absoluteSDSize > 0 {
  1158. absoluteSD = (*SECURITY_DESCRIPTOR)(unsafe.Pointer(&make([]byte, absoluteSDSize)[0]))
  1159. }
  1160. var (
  1161. dacl *ACL
  1162. sacl *ACL
  1163. owner *SID
  1164. group *SID
  1165. )
  1166. if daclSize > 0 {
  1167. dacl = (*ACL)(unsafe.Pointer(&make([]byte, daclSize)[0]))
  1168. }
  1169. if saclSize > 0 {
  1170. sacl = (*ACL)(unsafe.Pointer(&make([]byte, saclSize)[0]))
  1171. }
  1172. if ownerSize > 0 {
  1173. owner = (*SID)(unsafe.Pointer(&make([]byte, ownerSize)[0]))
  1174. }
  1175. if groupSize > 0 {
  1176. group = (*SID)(unsafe.Pointer(&make([]byte, groupSize)[0]))
  1177. }
  1178. err = makeAbsoluteSD(selfRelativeSD, absoluteSD, &absoluteSDSize,
  1179. dacl, &daclSize, sacl, &saclSize, owner, &ownerSize, group, &groupSize)
  1180. return
  1181. }
  1182. // ToSelfRelative converts an absolute security descriptor into a self-relative one.
  1183. func (absoluteSD *SECURITY_DESCRIPTOR) ToSelfRelative() (selfRelativeSD *SECURITY_DESCRIPTOR, err error) {
  1184. control, _, err := absoluteSD.Control()
  1185. if err != nil {
  1186. return
  1187. }
  1188. if control&SE_SELF_RELATIVE != 0 {
  1189. err = ERROR_INVALID_PARAMETER
  1190. return
  1191. }
  1192. var selfRelativeSDSize uint32
  1193. err = makeSelfRelativeSD(absoluteSD, nil, &selfRelativeSDSize)
  1194. switch err {
  1195. case ERROR_INSUFFICIENT_BUFFER:
  1196. case nil:
  1197. // makeSelfRelativeSD is expected to fail, but it succeeds.
  1198. return nil, ERROR_INTERNAL_ERROR
  1199. default:
  1200. return nil, err
  1201. }
  1202. if selfRelativeSDSize > 0 {
  1203. selfRelativeSD = (*SECURITY_DESCRIPTOR)(unsafe.Pointer(&make([]byte, selfRelativeSDSize)[0]))
  1204. }
  1205. err = makeSelfRelativeSD(absoluteSD, selfRelativeSD, &selfRelativeSDSize)
  1206. return
  1207. }
  1208. func (selfRelativeSD *SECURITY_DESCRIPTOR) copySelfRelativeSecurityDescriptor() *SECURITY_DESCRIPTOR {
  1209. sdLen := int(selfRelativeSD.Length())
  1210. const min = int(unsafe.Sizeof(SECURITY_DESCRIPTOR{}))
  1211. if sdLen < min {
  1212. sdLen = min
  1213. }
  1214. src := unsafe.Slice((*byte)(unsafe.Pointer(selfRelativeSD)), sdLen)
  1215. // SECURITY_DESCRIPTOR has pointers in it, which means checkptr expects for it to
  1216. // be aligned properly. When we're copying a Windows-allocated struct to a
  1217. // Go-allocated one, make sure that the Go allocation is aligned to the
  1218. // pointer size.
  1219. const psize = int(unsafe.Sizeof(uintptr(0)))
  1220. alloc := make([]uintptr, (sdLen+psize-1)/psize)
  1221. dst := unsafe.Slice((*byte)(unsafe.Pointer(&alloc[0])), sdLen)
  1222. copy(dst, src)
  1223. return (*SECURITY_DESCRIPTOR)(unsafe.Pointer(&dst[0]))
  1224. }
  1225. // SecurityDescriptorFromString converts an SDDL string describing a security descriptor into a
  1226. // self-relative security descriptor object allocated on the Go heap.
  1227. func SecurityDescriptorFromString(sddl string) (sd *SECURITY_DESCRIPTOR, err error) {
  1228. var winHeapSD *SECURITY_DESCRIPTOR
  1229. err = convertStringSecurityDescriptorToSecurityDescriptor(sddl, 1, &winHeapSD, nil)
  1230. if err != nil {
  1231. return
  1232. }
  1233. defer LocalFree(Handle(unsafe.Pointer(winHeapSD)))
  1234. return winHeapSD.copySelfRelativeSecurityDescriptor(), nil
  1235. }
  1236. // GetSecurityInfo queries the security information for a given handle and returns the self-relative security
  1237. // descriptor result on the Go heap.
  1238. func GetSecurityInfo(handle Handle, objectType SE_OBJECT_TYPE, securityInformation SECURITY_INFORMATION) (sd *SECURITY_DESCRIPTOR, err error) {
  1239. var winHeapSD *SECURITY_DESCRIPTOR
  1240. err = getSecurityInfo(handle, objectType, securityInformation, nil, nil, nil, nil, &winHeapSD)
  1241. if err != nil {
  1242. return
  1243. }
  1244. defer LocalFree(Handle(unsafe.Pointer(winHeapSD)))
  1245. return winHeapSD.copySelfRelativeSecurityDescriptor(), nil
  1246. }
  1247. // GetNamedSecurityInfo queries the security information for a given named object and returns the self-relative security
  1248. // descriptor result on the Go heap.
  1249. func GetNamedSecurityInfo(objectName string, objectType SE_OBJECT_TYPE, securityInformation SECURITY_INFORMATION) (sd *SECURITY_DESCRIPTOR, err error) {
  1250. var winHeapSD *SECURITY_DESCRIPTOR
  1251. err = getNamedSecurityInfo(objectName, objectType, securityInformation, nil, nil, nil, nil, &winHeapSD)
  1252. if err != nil {
  1253. return
  1254. }
  1255. defer LocalFree(Handle(unsafe.Pointer(winHeapSD)))
  1256. return winHeapSD.copySelfRelativeSecurityDescriptor(), nil
  1257. }
  1258. // BuildSecurityDescriptor makes a new security descriptor using the input trustees, explicit access lists, and
  1259. // prior security descriptor to be merged, any of which can be nil, returning the self-relative security descriptor
  1260. // result on the Go heap.
  1261. func BuildSecurityDescriptor(owner *TRUSTEE, group *TRUSTEE, accessEntries []EXPLICIT_ACCESS, auditEntries []EXPLICIT_ACCESS, mergedSecurityDescriptor *SECURITY_DESCRIPTOR) (sd *SECURITY_DESCRIPTOR, err error) {
  1262. var winHeapSD *SECURITY_DESCRIPTOR
  1263. var winHeapSDSize uint32
  1264. var firstAccessEntry *EXPLICIT_ACCESS
  1265. if len(accessEntries) > 0 {
  1266. firstAccessEntry = &accessEntries[0]
  1267. }
  1268. var firstAuditEntry *EXPLICIT_ACCESS
  1269. if len(auditEntries) > 0 {
  1270. firstAuditEntry = &auditEntries[0]
  1271. }
  1272. err = buildSecurityDescriptor(owner, group, uint32(len(accessEntries)), firstAccessEntry, uint32(len(auditEntries)), firstAuditEntry, mergedSecurityDescriptor, &winHeapSDSize, &winHeapSD)
  1273. if err != nil {
  1274. return
  1275. }
  1276. defer LocalFree(Handle(unsafe.Pointer(winHeapSD)))
  1277. return winHeapSD.copySelfRelativeSecurityDescriptor(), nil
  1278. }
  1279. // NewSecurityDescriptor creates and initializes a new absolute security descriptor.
  1280. func NewSecurityDescriptor() (absoluteSD *SECURITY_DESCRIPTOR, err error) {
  1281. absoluteSD = &SECURITY_DESCRIPTOR{}
  1282. err = initializeSecurityDescriptor(absoluteSD, 1)
  1283. return
  1284. }
  1285. // ACLFromEntries returns a new ACL on the Go heap containing a list of explicit entries as well as those of another ACL.
  1286. // Both explicitEntries and mergedACL are optional and can be nil.
  1287. func ACLFromEntries(explicitEntries []EXPLICIT_ACCESS, mergedACL *ACL) (acl *ACL, err error) {
  1288. var firstExplicitEntry *EXPLICIT_ACCESS
  1289. if len(explicitEntries) > 0 {
  1290. firstExplicitEntry = &explicitEntries[0]
  1291. }
  1292. var winHeapACL *ACL
  1293. err = setEntriesInAcl(uint32(len(explicitEntries)), firstExplicitEntry, mergedACL, &winHeapACL)
  1294. if err != nil {
  1295. return
  1296. }
  1297. defer LocalFree(Handle(unsafe.Pointer(winHeapACL)))
  1298. aclBytes := make([]byte, winHeapACL.aclSize)
  1299. copy(aclBytes, (*[(1 << 31) - 1]byte)(unsafe.Pointer(winHeapACL))[:len(aclBytes):len(aclBytes)])
  1300. return (*ACL)(unsafe.Pointer(&aclBytes[0])), nil
  1301. }