security_windows.go 52 KB

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