security.c 185 KB
Newer Older
1
/*
2
 * Copyright 1999, 2000 Juergen Schmied <juergen.schmied@debitel.net>
3
 * Copyright 2003 CodeWeavers Inc. (Ulrich Czekalla)
4
 * Copyright 2006 Robert Reif
5 6 7 8 9 10 11 12 13 14 15 16 17
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19
 *
20
 */
21

22
#include <stdarg.h>
23 24
#include <string.h>

25 26
#include "ntstatus.h"
#define WIN32_NO_STATUS
27
#include "windef.h"
28
#include "winbase.h"
Alexandre Julliard's avatar
Alexandre Julliard committed
29
#include "winerror.h"
30
#include "winreg.h"
31
#include "winsafer.h"
32
#include "winternl.h"
33
#include "winioctl.h"
34
#include "ntsecapi.h"
35
#include "accctrl.h"
36
#include "sddl.h"
37
#include "winsvc.h"
38
#include "aclapi.h"
39 40
#include "objbase.h"
#include "iads.h"
41
#include "advapi32_misc.h"
42
#include "lmcons.h"
43

44
#include "wine/debug.h"
45
#include "wine/unicode.h"
Alexandre Julliard's avatar
Alexandre Julliard committed
46

47
WINE_DEFAULT_DEBUG_CHANNEL(advapi);
48

49 50 51 52 53 54 55 56
static BOOL ParseStringSidToSid(LPCWSTR StringSid, PSID pSid, LPDWORD cBytes);
static BOOL ParseStringAclToAcl(LPCWSTR StringAcl, LPDWORD lpdwFlags, 
    PACL pAcl, LPDWORD cBytes);
static BYTE ParseAceStringFlags(LPCWSTR* StringAcl);
static BYTE ParseAceStringType(LPCWSTR* StringAcl);
static DWORD ParseAceStringRights(LPCWSTR* StringAcl);
static BOOL ParseStringSecurityDescriptorToSecurityDescriptor(
    LPCWSTR StringSecurityDescriptor,
57
    SECURITY_DESCRIPTOR_RELATIVE* SecurityDescriptor,
58 59 60 61 62 63 64 65 66
    LPDWORD cBytes);
static DWORD ParseAclStringFlags(LPCWSTR* StringAcl);

typedef struct _ACEFLAG
{
   LPCWSTR wstr;
   DWORD value;
} ACEFLAG, *LPACEFLAG;

67
typedef struct _MAX_SID
68
{
69 70 71 72 73
    /* same fields as struct _SID */
    BYTE Revision;
    BYTE SubAuthorityCount;
    SID_IDENTIFIER_AUTHORITY IdentifierAuthority;
    DWORD SubAuthority[SID_MAX_SUB_AUTHORITIES];
74 75 76 77 78 79 80
} MAX_SID;

typedef struct WELLKNOWNSID
{
    WCHAR wstr[2];
    WELL_KNOWN_SID_TYPE Type;
    MAX_SID Sid;
81 82
} WELLKNOWNSID;

83 84
static const WELLKNOWNSID WellKnownSids[] =
{
85 86 87 88 89 90 91
    { {0,0}, WinNullSid, { SID_REVISION, 1, { SECURITY_NULL_SID_AUTHORITY }, { SECURITY_NULL_RID } } },
    { {'W','D'}, WinWorldSid, { SID_REVISION, 1, { SECURITY_WORLD_SID_AUTHORITY }, { SECURITY_WORLD_RID } } },
    { {0,0}, WinLocalSid, { SID_REVISION, 1, { SECURITY_LOCAL_SID_AUTHORITY }, { SECURITY_LOCAL_RID } } },
    { {'C','O'}, WinCreatorOwnerSid, { SID_REVISION, 1, { SECURITY_CREATOR_SID_AUTHORITY }, { SECURITY_CREATOR_OWNER_RID } } },
    { {'C','G'}, WinCreatorGroupSid, { SID_REVISION, 1, { SECURITY_CREATOR_SID_AUTHORITY }, { SECURITY_CREATOR_GROUP_RID } } },
    { {0,0}, WinCreatorOwnerServerSid, { SID_REVISION, 1, { SECURITY_CREATOR_SID_AUTHORITY }, { SECURITY_CREATOR_OWNER_SERVER_RID } } },
    { {0,0}, WinCreatorGroupServerSid, { SID_REVISION, 1, { SECURITY_CREATOR_SID_AUTHORITY }, { SECURITY_CREATOR_GROUP_SERVER_RID } } },
92
    { {0,0}, WinNtAuthoritySid, { SID_REVISION, 0, { SECURITY_NT_AUTHORITY }, { SECURITY_NULL_RID } } },
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
    { {0,0}, WinDialupSid, { SID_REVISION, 1, { SECURITY_NT_AUTHORITY }, { SECURITY_DIALUP_RID } } },
    { {'N','U'}, WinNetworkSid, { SID_REVISION, 1, { SECURITY_NT_AUTHORITY }, { SECURITY_NETWORK_RID } } },
    { {0,0}, WinBatchSid, { SID_REVISION, 1, { SECURITY_NT_AUTHORITY }, { SECURITY_BATCH_RID } } },
    { {'I','U'}, WinInteractiveSid, { SID_REVISION, 1, { SECURITY_NT_AUTHORITY }, { SECURITY_INTERACTIVE_RID } } },
    { {'S','U'}, WinServiceSid, { SID_REVISION, 1, { SECURITY_NT_AUTHORITY }, { SECURITY_SERVICE_RID } } },
    { {'A','N'}, WinAnonymousSid, { SID_REVISION, 1, { SECURITY_NT_AUTHORITY }, { SECURITY_ANONYMOUS_LOGON_RID } } },
    { {0,0}, WinProxySid, { SID_REVISION, 1, { SECURITY_NT_AUTHORITY }, { SECURITY_PROXY_RID } } },
    { {'E','D'}, WinEnterpriseControllersSid, { SID_REVISION, 1, { SECURITY_NT_AUTHORITY }, { SECURITY_ENTERPRISE_CONTROLLERS_RID } } },
    { {'P','S'}, WinSelfSid, { SID_REVISION, 1, { SECURITY_NT_AUTHORITY }, { SECURITY_PRINCIPAL_SELF_RID } } },
    { {'A','U'}, WinAuthenticatedUserSid, { SID_REVISION, 1, { SECURITY_NT_AUTHORITY }, { SECURITY_AUTHENTICATED_USER_RID } } },
    { {'R','C'}, WinRestrictedCodeSid, { SID_REVISION, 1, { SECURITY_NT_AUTHORITY }, { SECURITY_RESTRICTED_CODE_RID } } },
    { {0,0}, WinTerminalServerSid, { SID_REVISION, 1, { SECURITY_NT_AUTHORITY }, { SECURITY_TERMINAL_SERVER_RID } } },
    { {0,0}, WinRemoteLogonIdSid, { SID_REVISION, 1, { SECURITY_NT_AUTHORITY }, { SECURITY_REMOTE_LOGON_RID } } },
    { {'S','Y'}, WinLocalSystemSid, { SID_REVISION, 1, { SECURITY_NT_AUTHORITY }, { SECURITY_LOCAL_SYSTEM_RID } } },
    { {'L','S'}, WinLocalServiceSid, { SID_REVISION, 1, { SECURITY_NT_AUTHORITY }, { SECURITY_LOCAL_SERVICE_RID } } },
    { {'N','S'}, WinNetworkServiceSid, { SID_REVISION, 1, { SECURITY_NT_AUTHORITY }, { SECURITY_NETWORK_SERVICE_RID } } },
    { {0,0}, WinBuiltinDomainSid, { SID_REVISION, 1, { SECURITY_NT_AUTHORITY }, { SECURITY_BUILTIN_DOMAIN_RID } } },
    { {'B','A'}, WinBuiltinAdministratorsSid, { SID_REVISION, 2, { SECURITY_NT_AUTHORITY }, { SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS } } },
    { {'B','U'}, WinBuiltinUsersSid, { SID_REVISION, 2, { SECURITY_NT_AUTHORITY }, { SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_USERS } } },
    { {'B','G'}, WinBuiltinGuestsSid, { SID_REVISION, 2, { SECURITY_NT_AUTHORITY }, { SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_GUESTS } } },
    { {'P','U'}, WinBuiltinPowerUsersSid, { SID_REVISION, 2, { SECURITY_NT_AUTHORITY }, { SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_POWER_USERS } } },
    { {'A','O'}, WinBuiltinAccountOperatorsSid, { SID_REVISION, 2, { SECURITY_NT_AUTHORITY }, { SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ACCOUNT_OPS } } },
    { {'S','O'}, WinBuiltinSystemOperatorsSid, { SID_REVISION, 2, { SECURITY_NT_AUTHORITY }, { SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_SYSTEM_OPS } } },
    { {'P','O'}, WinBuiltinPrintOperatorsSid, { SID_REVISION, 2, { SECURITY_NT_AUTHORITY }, { SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_PRINT_OPS } } },
    { {'B','O'}, WinBuiltinBackupOperatorsSid, { SID_REVISION, 2, { SECURITY_NT_AUTHORITY }, { SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_BACKUP_OPS } } },
    { {'R','E'}, WinBuiltinReplicatorSid, { SID_REVISION, 2, { SECURITY_NT_AUTHORITY }, { SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_REPLICATOR } } },
    { {'R','U'}, WinBuiltinPreWindows2000CompatibleAccessSid, { SID_REVISION, 2, { SECURITY_NT_AUTHORITY }, { SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_PREW2KCOMPACCESS } } },
    { {'R','D'}, WinBuiltinRemoteDesktopUsersSid, { SID_REVISION, 2, { SECURITY_NT_AUTHORITY }, { SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_REMOTE_DESKTOP_USERS } } },
    { {'N','O'}, WinBuiltinNetworkConfigurationOperatorsSid, { SID_REVISION, 2, { SECURITY_NT_AUTHORITY }, { SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_NETWORK_CONFIGURATION_OPS } } },
122 123 124 125 126
    { {0,0}, WinNTLMAuthenticationSid, { SID_REVISION, 2, { SECURITY_NT_AUTHORITY }, { SECURITY_PACKAGE_BASE_RID, SECURITY_PACKAGE_NTLM_RID } } },
    { {0,0}, WinDigestAuthenticationSid, { SID_REVISION, 2, { SECURITY_NT_AUTHORITY }, { SECURITY_PACKAGE_BASE_RID, SECURITY_PACKAGE_DIGEST_RID } } },
    { {0,0}, WinSChannelAuthenticationSid, { SID_REVISION, 2, { SECURITY_NT_AUTHORITY }, { SECURITY_PACKAGE_BASE_RID, SECURITY_PACKAGE_SCHANNEL_RID } } },
    { {0,0}, WinThisOrganizationSid, { SID_REVISION, 1, { SECURITY_NT_AUTHORITY }, { SECURITY_THIS_ORGANIZATION_RID } } },
    { {0,0}, WinOtherOrganizationSid, { SID_REVISION, 1, { SECURITY_NT_AUTHORITY }, { SECURITY_OTHER_ORGANIZATION_RID } } },
127
    { {0,0}, WinBuiltinIncomingForestTrustBuildersSid, { SID_REVISION, 2, { SECURITY_NT_AUTHORITY }, { SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_INCOMING_FOREST_TRUST_BUILDERS  } } },
128 129
    { {0,0}, WinBuiltinPerfMonitoringUsersSid, { SID_REVISION, 2, { SECURITY_NT_AUTHORITY }, { SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_MONITORING_USERS } } },
    { {0,0}, WinBuiltinPerfLoggingUsersSid, { SID_REVISION, 2, { SECURITY_NT_AUTHORITY }, { SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_LOGGING_USERS } } },
130 131
    { {0,0}, WinBuiltinAuthorizationAccessSid, { SID_REVISION, 2, { SECURITY_NT_AUTHORITY }, { SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_AUTHORIZATIONACCESS } } },
    { {0,0}, WinBuiltinTerminalServerLicenseServersSid, { SID_REVISION, 2, { SECURITY_NT_AUTHORITY }, { SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_TS_LICENSE_SERVERS } } },
132
    { {0,0}, WinBuiltinDCOMUsersSid, { SID_REVISION, 2, { SECURITY_NT_AUTHORITY }, { SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_DCOM_USERS } } },
133 134 135 136
    { {'L','W'}, WinLowLabelSid, { SID_REVISION, 1, { SECURITY_MANDATORY_LABEL_AUTHORITY}, { SECURITY_MANDATORY_LOW_RID} } },
    { {'M','E'}, WinMediumLabelSid, { SID_REVISION, 1, { SECURITY_MANDATORY_LABEL_AUTHORITY}, { SECURITY_MANDATORY_MEDIUM_RID } } },
    { {'H','I'}, WinHighLabelSid, { SID_REVISION, 1, { SECURITY_MANDATORY_LABEL_AUTHORITY}, { SECURITY_MANDATORY_HIGH_RID } } },
    { {'S','I'}, WinSystemLabelSid, { SID_REVISION, 1, { SECURITY_MANDATORY_LABEL_AUTHORITY}, { SECURITY_MANDATORY_SYSTEM_RID } } },
137 138
};

139 140
/* these SIDs must be constructed as relative to some domain - only the RID is well-known */
typedef struct WELLKNOWNRID
141 142 143 144 145
{
    WELL_KNOWN_SID_TYPE Type;
    DWORD Rid;
} WELLKNOWNRID;

146
static const WELLKNOWNRID WellKnownRids[] = {
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
    { WinAccountAdministratorSid,    DOMAIN_USER_RID_ADMIN },
    { WinAccountGuestSid,            DOMAIN_USER_RID_GUEST },
    { WinAccountKrbtgtSid,           DOMAIN_USER_RID_KRBTGT },
    { WinAccountDomainAdminsSid,     DOMAIN_GROUP_RID_ADMINS },
    { WinAccountDomainUsersSid,      DOMAIN_GROUP_RID_USERS },
    { WinAccountDomainGuestsSid,     DOMAIN_GROUP_RID_GUESTS },
    { WinAccountComputersSid,        DOMAIN_GROUP_RID_COMPUTERS },
    { WinAccountControllersSid,      DOMAIN_GROUP_RID_CONTROLLERS },
    { WinAccountCertAdminsSid,       DOMAIN_GROUP_RID_CERT_ADMINS },
    { WinAccountSchemaAdminsSid,     DOMAIN_GROUP_RID_SCHEMA_ADMINS },
    { WinAccountEnterpriseAdminsSid, DOMAIN_GROUP_RID_ENTERPRISE_ADMINS },
    { WinAccountPolicyAdminsSid,     DOMAIN_GROUP_RID_POLICY_ADMINS },
    { WinAccountRasAndIasServersSid, DOMAIN_ALIAS_RID_RAS_SERVERS },
};


163 164
static SID const sidWorld = { SID_REVISION, 1, { SECURITY_WORLD_SID_AUTHORITY} , { SECURITY_WORLD_RID } };

165 166 167 168 169
typedef struct _AccountSid {
    WELL_KNOWN_SID_TYPE type;
    LPCWSTR account;
    LPCWSTR domain;
    SID_NAME_USE name_use;
170
    LPCWSTR alias;
171 172 173 174 175 176 177 178 179 180 181
} AccountSid;

static const WCHAR Account_Operators[] = { 'A','c','c','o','u','n','t',' ','O','p','e','r','a','t','o','r','s',0 };
static const WCHAR Administrator[] = {'A','d','m','i','n','i','s','t','r','a','t','o','r',0 };
static const WCHAR Administrators[] = { 'A','d','m','i','n','i','s','t','r','a','t','o','r','s',0 };
static const WCHAR ANONYMOUS_LOGON[] = { 'A','N','O','N','Y','M','O','U','S',' ','L','O','G','O','N',0 };
static const WCHAR Authenticated_Users[] = { 'A','u','t','h','e','n','t','i','c','a','t','e','d',' ','U','s','e','r','s',0 };
static const WCHAR Backup_Operators[] = { 'B','a','c','k','u','p',' ','O','p','e','r','a','t','o','r','s',0 };
static const WCHAR BATCH[] = { 'B','A','T','C','H',0 };
static const WCHAR Blank[] = { 0 };
static const WCHAR BUILTIN[] = { 'B','U','I','L','T','I','N',0 };
182
static const WCHAR Cert_Publishers[] = { 'C','e','r','t',' ','P','u','b','l','i','s','h','e','r','s',0 };
183 184 185 186
static const WCHAR CREATOR_GROUP[] = { 'C','R','E','A','T','O','R',' ','G','R','O','U','P',0 };
static const WCHAR CREATOR_GROUP_SERVER[] = { 'C','R','E','A','T','O','R',' ','G','R','O','U','P',' ','S','E','R','V','E','R',0 };
static const WCHAR CREATOR_OWNER[] = { 'C','R','E','A','T','O','R',' ','O','W','N','E','R',0 };
static const WCHAR CREATOR_OWNER_SERVER[] = { 'C','R','E','A','T','O','R',' ','O','W','N','E','R',' ','S','E','R','V','E','R',0 };
187
static const WCHAR CURRENT_USER[] = { 'C','U','R','R','E','N','T','_','U','S','E','R',0 };
188
static const WCHAR DIALUP[] = { 'D','I','A','L','U','P',0 };
189
static const WCHAR Digest_Authentication[] = { 'D','i','g','e','s','t',' ','A','u','t','h','e','n','t','i','c','a','t','i','o','n',0 };
190
static const WCHAR DOMAIN[] = {'D','O','M','A','I','N',0};
191 192 193 194 195 196
static const WCHAR Domain_Admins[] = { 'D','o','m','a','i','n',' ','A','d','m','i','n','s',0 };
static const WCHAR Domain_Computers[] = { 'D','o','m','a','i','n',' ','C','o','m','p','u','t','e','r','s',0 };
static const WCHAR Domain_Controllers[] = { 'D','o','m','a','i','n',' ','C','o','n','t','r','o','l','l','e','r','s',0 };
static const WCHAR Domain_Guests[] = { 'D','o','m','a','i','n',' ','G','u','e','s','t','s',0 };
static const WCHAR Domain_Users[] = { 'D','o','m','a','i','n',' ','U','s','e','r','s',0 };
static const WCHAR Enterprise_Admins[] = { 'E','n','t','e','r','p','r','i','s','e',' ','A','d','m','i','n','s',0 };
197 198
static const WCHAR ENTERPRISE_DOMAIN_CONTROLLERS[] = { 'E','N','T','E','R','P','R','I','S','E',' ','D','O','M','A','I','N',' ','C','O','N','T','R','O','L','L','E','R','S',0 };
static const WCHAR Everyone[] = { 'E','v','e','r','y','o','n','e',0 };
199
static const WCHAR Group_Policy_Creator_Owners[] = { 'G','r','o','u','p',' ','P','o','l','i','c','y',' ','C','r','e','a','t','o','r',' ','O','w','n','e','r','s',0 };
200
static const WCHAR Guest[] = { 'G','u','e','s','t',0 };
201 202 203 204
static const WCHAR Guests[] = { 'G','u','e','s','t','s',0 };
static const WCHAR INTERACTIVE[] = { 'I','N','T','E','R','A','C','T','I','V','E',0 };
static const WCHAR LOCAL[] = { 'L','O','C','A','L',0 };
static const WCHAR LOCAL_SERVICE[] = { 'L','O','C','A','L',' ','S','E','R','V','I','C','E',0 };
205
static const WCHAR LOCAL_SERVICE2[] = { 'L','O','C','A','L','S','E','R','V','I','C','E',0 };
206 207 208
static const WCHAR NETWORK[] = { 'N','E','T','W','O','R','K',0 };
static const WCHAR Network_Configuration_Operators[] = { 'N','e','t','w','o','r','k',' ','C','o','n','f','i','g','u','r','a','t','i','o','n',' ','O','p','e','r','a','t','o','r','s',0 };
static const WCHAR NETWORK_SERVICE[] = { 'N','E','T','W','O','R','K',' ','S','E','R','V','I','C','E',0 };
209
static const WCHAR NETWORK_SERVICE2[] = { 'N','E','T','W','O','R','K','S','E','R','V','I','C','E',0 };
210 211
static const WCHAR NT_AUTHORITY[] = { 'N','T',' ','A','U','T','H','O','R','I','T','Y',0 };
static const WCHAR NT_Pseudo_Domain[] = { 'N','T',' ','P','s','e','u','d','o',' ','D','o','m','a','i','n',0 };
212
static const WCHAR NTML_Authentication[] = { 'N','T','M','L',' ','A','u','t','h','e','n','t','i','c','a','t','i','o','n',0 };
213
static const WCHAR NULL_SID[] = { 'N','U','L','L',' ','S','I','D',0 };
214 215 216
static const WCHAR Other_Organization[] = { 'O','t','h','e','r',' ','O','r','g','a','n','i','z','a','t','i','o','n',0 };
static const WCHAR Performance_Log_Users[] = { 'P','e','r','f','o','r','m','a','n','c','e',' ','L','o','g',' ','U','s','e','r','s',0 };
static const WCHAR Performance_Monitor_Users[] = { 'P','e','r','f','o','r','m','a','n','c','e',' ','M','o','n','i','t','o','r',' ','U','s','e','r','s',0 };
217
static const WCHAR Power_Users[] = { 'P','o','w','e','r',' ','U','s','e','r','s',0 };
218
static const WCHAR Pre_Windows_2000_Compatible_Access[] = { 'P','r','e','-','W','i','n','d','o','w','s',' ','2','0','0','0',' ','C','o','m','p','a','t','i','b','l','e',' ','A','c','c','e','s','s',0 };
219 220
static const WCHAR Print_Operators[] = { 'P','r','i','n','t',' ','O','p','e','r','a','t','o','r','s',0 };
static const WCHAR PROXY[] = { 'P','R','O','X','Y',0 };
221
static const WCHAR RAS_and_IAS_Servers[] = { 'R','A','S',' ','a','n','d',' ','I','A','S',' ','S','e','r','v','e','r','s',0 };
222 223 224 225
static const WCHAR Remote_Desktop_Users[] = { 'R','e','m','o','t','e',' ','D','e','s','k','t','o','p',' ','U','s','e','r','s',0 };
static const WCHAR REMOTE_INTERACTIVE_LOGON[] = { 'R','E','M','O','T','E',' ','I','N','T','E','R','A','C','T','I','V','E',' ','L','O','G','O','N',0 };
static const WCHAR Replicators[] = { 'R','e','p','l','i','c','a','t','o','r','s',0 };
static const WCHAR RESTRICTED[] = { 'R','E','S','T','R','I','C','T','E','D',0 };
226
static const WCHAR SChannel_Authentication[] = { 'S','C','h','a','n','n','e','l',' ','A','u','t','h','e','n','t','i','c','a','t','i','o','n',0 };
227
static const WCHAR Schema_Admins[] = { 'S','c','h','e','m','a',' ','A','d','m','i','n','s',0 };
228 229 230 231 232
static const WCHAR SELF[] = { 'S','E','L','F',0 };
static const WCHAR Server_Operators[] = { 'S','e','r','v','e','r',' ','O','p','e','r','a','t','o','r','s',0 };
static const WCHAR SERVICE[] = { 'S','E','R','V','I','C','E',0 };
static const WCHAR SYSTEM[] = { 'S','Y','S','T','E','M',0 };
static const WCHAR TERMINAL_SERVER_USER[] = { 'T','E','R','M','I','N','A','L',' ','S','E','R','V','E','R',' ','U','S','E','R',0 };
233
static const WCHAR This_Organization[] = { 'T','h','i','s',' ','O','r','g','a','n','i','z','a','t','i','o','n',0 };
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
static const WCHAR Users[] = { 'U','s','e','r','s',0 };

static const AccountSid ACCOUNT_SIDS[] = {
    { WinNullSid, NULL_SID, Blank, SidTypeWellKnownGroup },
    { WinWorldSid, Everyone, Blank, SidTypeWellKnownGroup },
    { WinLocalSid, LOCAL, Blank, SidTypeWellKnownGroup },
    { WinCreatorOwnerSid, CREATOR_OWNER, Blank, SidTypeWellKnownGroup },
    { WinCreatorGroupSid, CREATOR_GROUP, Blank, SidTypeWellKnownGroup },
    { WinCreatorOwnerServerSid, CREATOR_OWNER_SERVER, Blank, SidTypeWellKnownGroup },
    { WinCreatorGroupServerSid, CREATOR_GROUP_SERVER, Blank, SidTypeWellKnownGroup },
    { WinNtAuthoritySid, NT_Pseudo_Domain, NT_Pseudo_Domain, SidTypeDomain },
    { WinDialupSid, DIALUP, NT_AUTHORITY, SidTypeWellKnownGroup },
    { WinNetworkSid, NETWORK, NT_AUTHORITY, SidTypeWellKnownGroup },
    { WinBatchSid, BATCH, NT_AUTHORITY, SidTypeWellKnownGroup },
    { WinInteractiveSid, INTERACTIVE, NT_AUTHORITY, SidTypeWellKnownGroup },
    { WinServiceSid, SERVICE, NT_AUTHORITY, SidTypeWellKnownGroup },
    { WinAnonymousSid, ANONYMOUS_LOGON, NT_AUTHORITY, SidTypeWellKnownGroup },
    { WinProxySid, PROXY, NT_AUTHORITY, SidTypeWellKnownGroup },
    { WinEnterpriseControllersSid, ENTERPRISE_DOMAIN_CONTROLLERS, NT_AUTHORITY, SidTypeWellKnownGroup },
    { WinSelfSid, SELF, NT_AUTHORITY, SidTypeWellKnownGroup },
    { WinAuthenticatedUserSid, Authenticated_Users, NT_AUTHORITY, SidTypeWellKnownGroup },
    { WinRestrictedCodeSid, RESTRICTED, NT_AUTHORITY, SidTypeWellKnownGroup },
    { WinTerminalServerSid, TERMINAL_SERVER_USER, NT_AUTHORITY, SidTypeWellKnownGroup },
    { WinRemoteLogonIdSid, REMOTE_INTERACTIVE_LOGON, NT_AUTHORITY, SidTypeWellKnownGroup },
    { WinLocalSystemSid, SYSTEM, NT_AUTHORITY, SidTypeWellKnownGroup },
259 260
    { WinLocalServiceSid, LOCAL_SERVICE, NT_AUTHORITY, SidTypeWellKnownGroup, LOCAL_SERVICE2 },
    { WinNetworkServiceSid, NETWORK_SERVICE, NT_AUTHORITY, SidTypeWellKnownGroup , NETWORK_SERVICE2},
261 262 263 264 265 266 267 268 269 270
    { WinBuiltinDomainSid, BUILTIN, BUILTIN, SidTypeDomain },
    { WinBuiltinAdministratorsSid, Administrators, BUILTIN, SidTypeAlias },
    { WinBuiltinUsersSid, Users, BUILTIN, SidTypeAlias },
    { WinBuiltinGuestsSid, Guests, BUILTIN, SidTypeAlias },
    { WinBuiltinPowerUsersSid, Power_Users, BUILTIN, SidTypeAlias },
    { WinBuiltinAccountOperatorsSid, Account_Operators, BUILTIN, SidTypeAlias },
    { WinBuiltinSystemOperatorsSid, Server_Operators, BUILTIN, SidTypeAlias },
    { WinBuiltinPrintOperatorsSid, Print_Operators, BUILTIN, SidTypeAlias },
    { WinBuiltinBackupOperatorsSid, Backup_Operators, BUILTIN, SidTypeAlias },
    { WinBuiltinReplicatorSid, Replicators, BUILTIN, SidTypeAlias },
271
    { WinBuiltinPreWindows2000CompatibleAccessSid, Pre_Windows_2000_Compatible_Access, BUILTIN, SidTypeAlias },
272 273
    { WinBuiltinRemoteDesktopUsersSid, Remote_Desktop_Users, BUILTIN, SidTypeAlias },
    { WinBuiltinNetworkConfigurationOperatorsSid, Network_Configuration_Operators, BUILTIN, SidTypeAlias },
274 275 276 277 278 279 280
    { WinNTLMAuthenticationSid, NTML_Authentication, NT_AUTHORITY, SidTypeWellKnownGroup },
    { WinDigestAuthenticationSid, Digest_Authentication, NT_AUTHORITY, SidTypeWellKnownGroup },
    { WinSChannelAuthenticationSid, SChannel_Authentication, NT_AUTHORITY, SidTypeWellKnownGroup },
    { WinThisOrganizationSid, This_Organization, NT_AUTHORITY, SidTypeWellKnownGroup },
    { WinOtherOrganizationSid, Other_Organization, NT_AUTHORITY, SidTypeWellKnownGroup },
    { WinBuiltinPerfMonitoringUsersSid, Performance_Monitor_Users, BUILTIN, SidTypeAlias },
    { WinBuiltinPerfLoggingUsersSid, Performance_Log_Users, BUILTIN, SidTypeAlias },
281
};
282 283 284 285 286 287 288
/*
 * ACE access rights
 */
static const WCHAR SDDL_READ_CONTROL[]     = {'R','C',0};
static const WCHAR SDDL_WRITE_DAC[]        = {'W','D',0};
static const WCHAR SDDL_WRITE_OWNER[]      = {'W','O',0};
static const WCHAR SDDL_STANDARD_DELETE[]  = {'S','D',0};
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309

static const WCHAR SDDL_READ_PROPERTY[]    = {'R','P',0};
static const WCHAR SDDL_WRITE_PROPERTY[]   = {'W','P',0};
static const WCHAR SDDL_CREATE_CHILD[]     = {'C','C',0};
static const WCHAR SDDL_DELETE_CHILD[]     = {'D','C',0};
static const WCHAR SDDL_LIST_CHILDREN[]    = {'L','C',0};
static const WCHAR SDDL_SELF_WRITE[]       = {'S','W',0};
static const WCHAR SDDL_LIST_OBJECT[]      = {'L','O',0};
static const WCHAR SDDL_DELETE_TREE[]      = {'D','T',0};
static const WCHAR SDDL_CONTROL_ACCESS[]   = {'C','R',0};

static const WCHAR SDDL_FILE_ALL[]         = {'F','A',0};
static const WCHAR SDDL_FILE_READ[]        = {'F','R',0};
static const WCHAR SDDL_FILE_WRITE[]       = {'F','W',0};
static const WCHAR SDDL_FILE_EXECUTE[]     = {'F','X',0};

static const WCHAR SDDL_KEY_ALL[]          = {'K','A',0};
static const WCHAR SDDL_KEY_READ[]         = {'K','R',0};
static const WCHAR SDDL_KEY_WRITE[]        = {'K','W',0};
static const WCHAR SDDL_KEY_EXECUTE[]      = {'K','X',0};

310 311 312 313 314
static const WCHAR SDDL_GENERIC_ALL[]      = {'G','A',0};
static const WCHAR SDDL_GENERIC_READ[]     = {'G','R',0};
static const WCHAR SDDL_GENERIC_WRITE[]    = {'G','W',0};
static const WCHAR SDDL_GENERIC_EXECUTE[]  = {'G','X',0};

315 316 317 318 319 320 321
/*
 * ACL flags
 */
static const WCHAR SDDL_PROTECTED[]             = {'P',0};
static const WCHAR SDDL_AUTO_INHERIT_REQ[]      = {'A','R',0};
static const WCHAR SDDL_AUTO_INHERITED[]        = {'A','I',0};

322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344
/*
 * ACE types
 */
static const WCHAR SDDL_ACCESS_ALLOWED[]        = {'A',0};
static const WCHAR SDDL_ACCESS_DENIED[]         = {'D',0};
static const WCHAR SDDL_OBJECT_ACCESS_ALLOWED[] = {'O','A',0};
static const WCHAR SDDL_OBJECT_ACCESS_DENIED[]  = {'O','D',0};
static const WCHAR SDDL_AUDIT[]                 = {'A','U',0};
static const WCHAR SDDL_ALARM[]                 = {'A','L',0};
static const WCHAR SDDL_OBJECT_AUDIT[]          = {'O','U',0};
static const WCHAR SDDL_OBJECT_ALARMp[]         = {'O','L',0};

/*
 * ACE flags
 */
static const WCHAR SDDL_CONTAINER_INHERIT[]  = {'C','I',0};
static const WCHAR SDDL_OBJECT_INHERIT[]     = {'O','I',0};
static const WCHAR SDDL_NO_PROPAGATE[]       = {'N','P',0};
static const WCHAR SDDL_INHERIT_ONLY[]       = {'I','O',0};
static const WCHAR SDDL_INHERITED[]          = {'I','D',0};
static const WCHAR SDDL_AUDIT_SUCCESS[]      = {'S','A',0};
static const WCHAR SDDL_AUDIT_FAILURE[]      = {'F','A',0};

345
const char * debugstr_sid(PSID sid)
346 347
{
    int auth = 0;
348
    SID * psid = sid;
349 350 351 352 353 354 355 356 357 358 359 360 361

    if (psid == NULL)
        return "(null)";

    auth = psid->IdentifierAuthority.Value[5] +
           (psid->IdentifierAuthority.Value[4] << 8) +
           (psid->IdentifierAuthority.Value[3] << 16) +
           (psid->IdentifierAuthority.Value[2] << 24);

    switch (psid->SubAuthorityCount) {
    case 0:
        return wine_dbg_sprintf("S-%d-%d", psid->Revision, auth);
    case 1:
362
        return wine_dbg_sprintf("S-%d-%d-%u", psid->Revision, auth,
363 364
            psid->SubAuthority[0]);
    case 2:
365
        return wine_dbg_sprintf("S-%d-%d-%u-%u", psid->Revision, auth,
366 367
            psid->SubAuthority[0], psid->SubAuthority[1]);
    case 3:
368
        return wine_dbg_sprintf("S-%d-%d-%u-%u-%u", psid->Revision, auth,
369 370
            psid->SubAuthority[0], psid->SubAuthority[1], psid->SubAuthority[2]);
    case 4:
371
        return wine_dbg_sprintf("S-%d-%d-%u-%u-%u-%u", psid->Revision, auth,
372 373 374
            psid->SubAuthority[0], psid->SubAuthority[1], psid->SubAuthority[2],
            psid->SubAuthority[3]);
    case 5:
375
        return wine_dbg_sprintf("S-%d-%d-%u-%u-%u-%u-%u", psid->Revision, auth,
376 377 378
            psid->SubAuthority[0], psid->SubAuthority[1], psid->SubAuthority[2],
            psid->SubAuthority[3], psid->SubAuthority[4]);
    case 6:
379
        return wine_dbg_sprintf("S-%d-%d-%u-%u-%u-%u-%u-%u", psid->Revision, auth,
380 381 382
            psid->SubAuthority[3], psid->SubAuthority[1], psid->SubAuthority[2],
            psid->SubAuthority[0], psid->SubAuthority[4], psid->SubAuthority[5]);
    case 7:
383
        return wine_dbg_sprintf("S-%d-%d-%u-%u-%u-%u-%u-%u-%u", psid->Revision, auth,
384 385 386 387
            psid->SubAuthority[0], psid->SubAuthority[1], psid->SubAuthority[2],
            psid->SubAuthority[3], psid->SubAuthority[4], psid->SubAuthority[5],
            psid->SubAuthority[6]);
    case 8:
388
        return wine_dbg_sprintf("S-%d-%d-%u-%u-%u-%u-%u-%u-%u-%u", psid->Revision, auth,
389 390 391 392 393 394 395
            psid->SubAuthority[0], psid->SubAuthority[1], psid->SubAuthority[2],
            psid->SubAuthority[3], psid->SubAuthority[4], psid->SubAuthority[5],
            psid->SubAuthority[6], psid->SubAuthority[7]);
    }
    return "(too-big)";
}

396 397 398 399 400 401 402
/* set last error code from NT status and get the proper boolean return value */
/* used for functions that are a simple wrapper around the corresponding ntdll API */
static inline BOOL set_ntstatus( NTSTATUS status )
{
    if (status) SetLastError( RtlNtStatusToDosError( status ));
    return !status;
}
403

404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
#define	WINE_SIZE_OF_WORLD_ACCESS_ACL	(sizeof(ACL) + sizeof(ACCESS_ALLOWED_ACE) + sizeof(sidWorld) - sizeof(DWORD))

static void GetWorldAccessACL(PACL pACL)
{
    PACCESS_ALLOWED_ACE pACE = (PACCESS_ALLOWED_ACE) (pACL + 1);

    pACL->AclRevision = ACL_REVISION;
    pACL->Sbz1 = 0;
    pACL->AclSize = WINE_SIZE_OF_WORLD_ACCESS_ACL;
    pACL->AceCount = 1;
    pACL->Sbz2 = 0;

    pACE->Header.AceType = ACCESS_ALLOWED_ACE_TYPE;
    pACE->Header.AceFlags = CONTAINER_INHERIT_ACE;
    pACE->Header.AceSize = sizeof(ACCESS_ALLOWED_ACE) + sizeof(sidWorld) - sizeof(DWORD);
    pACE->Mask = 0xf3ffffff; /* Everything except reserved bits */
    memcpy(&pACE->SidStart, &sidWorld, sizeof(sidWorld));
}

423 424 425 426 427
/************************************************************
 *                ADVAPI_IsLocalComputer
 *
 * Checks whether the server name indicates local machine.
 */
428
BOOL ADVAPI_IsLocalComputer(LPCWSTR ServerName)
429
{
430 431 432 433 434
    DWORD dwSize = MAX_COMPUTERNAME_LENGTH + 1;
    BOOL Result;
    LPWSTR buf;

    if (!ServerName || !ServerName[0])
435
        return TRUE;
436

437 438 439 440 441 442 443 444
    buf = HeapAlloc(GetProcessHeap(), 0, dwSize * sizeof(WCHAR));
    Result = GetComputerNameW(buf,  &dwSize);
    if (Result && (ServerName[0] == '\\') && (ServerName[1] == '\\'))
        ServerName += 2;
    Result = Result && !lstrcmpW(ServerName, buf);
    HeapFree(GetProcessHeap(), 0, buf);

    return Result;
445 446
}

447 448 449 450 451 452 453 454 455
/************************************************************
 *                ADVAPI_GetComputerSid
 *
 * Reads the computer SID from the registry.
 */
BOOL ADVAPI_GetComputerSid(PSID sid)
{
    HKEY key;
    LONG ret;
456
    BOOL retval = FALSE;
457 458 459 460
    static const WCHAR Account[] = { 'S','E','C','U','R','I','T','Y','\\','S','A','M','\\','D','o','m','a','i','n','s','\\','A','c','c','o','u','n','t',0 };
    static const WCHAR V[] = { 'V',0 };

    if ((ret = RegOpenKeyExW(HKEY_LOCAL_MACHINE, Account, 0,
461 462 463 464 465 466 467 468 469 470 471 472 473 474
        KEY_READ, &key)) == ERROR_SUCCESS)
    {
        DWORD size = 0;
        ret = RegQueryValueExW(key, V, NULL, NULL, NULL, &size);
        if (ret == ERROR_MORE_DATA || ret == ERROR_SUCCESS)
        {
            BYTE * data = HeapAlloc(GetProcessHeap(), 0, size);
            if (data)
            {
                if ((ret = RegQueryValueExW(key, V, NULL, NULL,
                     data, &size)) == ERROR_SUCCESS)
                {
                    /* the SID is in the last 24 bytes of the binary data */
                    CopyMemory(sid, &data[size-24], 24);
475
                    retval = TRUE;
476
                }
477 478 479 480 481 482
                HeapFree(GetProcessHeap(), 0, data);
            }
        }
        RegCloseKey(key);
    }

483 484
    if(retval == TRUE) return retval;

485 486 487 488 489 490 491 492
    /* create a new random SID */
    if (RegCreateKeyExW(HKEY_LOCAL_MACHINE, Account,
        0, NULL, 0, KEY_ALL_ACCESS, NULL, &key, NULL) == ERROR_SUCCESS)
    {
        PSID new_sid;
        SID_IDENTIFIER_AUTHORITY identifierAuthority = {SECURITY_NT_AUTHORITY};
        DWORD id[3];

493
        if (RtlGenRandom(id, sizeof(id)))
494 495 496 497
        {
            if (AllocateAndInitializeSid(&identifierAuthority, 4, SECURITY_NT_NON_UNIQUE, id[0], id[1], id[2], 0, 0, 0, 0, &new_sid))
            {
                if (RegSetValueExW(key, V, 0, REG_BINARY, new_sid, GetLengthSid(new_sid)) == ERROR_SUCCESS)
498 499
                    retval = CopySid(GetLengthSid(new_sid), sid, new_sid);

500
                FreeSid(new_sid);
501 502 503 504
            }
        }
        RegCloseKey(key);
    }
505

506
    return retval;
507 508
}

509 510 511 512
/*	##############################
	######	TOKEN FUNCTIONS ######
	##############################
*/
513

514
/******************************************************************************
515
 * OpenProcessToken			[ADVAPI32.@]
Jon Griffiths's avatar
Jon Griffiths committed
516
 * Opens the access token associated with a process handle.
517 518
 *
 * PARAMS
519 520 521
 *   ProcessHandle [I] Handle to process
 *   DesiredAccess [I] Desired access to process
 *   TokenHandle   [O] Pointer to handle of open access token
522
 *
Jon Griffiths's avatar
Jon Griffiths committed
523 524 525 526 527 528
 * RETURNS
 *  Success: TRUE. TokenHandle contains the access token.
 *  Failure: FALSE.
 *
 * NOTES
 *  See NtOpenProcessToken.
529
 */
530
BOOL WINAPI
531
OpenProcessToken( HANDLE ProcessHandle, DWORD DesiredAccess,
532
                  HANDLE *TokenHandle )
533
{
534
	return set_ntstatus(NtOpenProcessToken( ProcessHandle, DesiredAccess, TokenHandle ));
535 536 537
}

/******************************************************************************
538
 * OpenThreadToken [ADVAPI32.@]
539
 *
Jon Griffiths's avatar
Jon Griffiths committed
540 541
 * Opens the access token associated with a thread handle.
 *
542
 * PARAMS
Jon Griffiths's avatar
Jon Griffiths committed
543 544 545 546 547 548 549 550 551 552 553
 *   ThreadHandle  [I] Handle to process
 *   DesiredAccess [I] Desired access to the thread
 *   OpenAsSelf    [I] ???
 *   TokenHandle   [O] Destination for the token handle
 *
 * RETURNS
 *  Success: TRUE. TokenHandle contains the access token.
 *  Failure: FALSE.
 *
 * NOTES
 *  See NtOpenThreadToken.
554 555
 */
BOOL WINAPI
556
OpenThreadToken( HANDLE ThreadHandle, DWORD DesiredAccess,
557 558
		 BOOL OpenAsSelf, HANDLE *TokenHandle)
{
559
	return set_ntstatus( NtOpenThreadToken(ThreadHandle, DesiredAccess, OpenAsSelf, TokenHandle));
560 561
}

562 563 564 565
BOOL WINAPI
AdjustTokenGroups( HANDLE TokenHandle, BOOL ResetToDefault, PTOKEN_GROUPS NewState,
                   DWORD BufferLength, PTOKEN_GROUPS PreviousState, PDWORD ReturnLength )
{
566 567
    return set_ntstatus( NtAdjustGroupsToken(TokenHandle, ResetToDefault, NewState, BufferLength,
                                             PreviousState, ReturnLength));
568 569
}

570
/******************************************************************************
571
 * AdjustTokenPrivileges [ADVAPI32.@]
572
 *
Jon Griffiths's avatar
Jon Griffiths committed
573 574
 * Adjust the privileges of an open token handle.
 * 
575
 * PARAMS
Jon Griffiths's avatar
Jon Griffiths committed
576 577 578 579 580 581 582 583 584 585 586 587 588 589
 *  TokenHandle          [I]   Handle from OpenProcessToken() or OpenThreadToken() 
 *  DisableAllPrivileges [I]   TRUE=Remove all privileges, FALSE=Use NewState
 *  NewState             [I]   Desired new privileges of the token
 *  BufferLength         [I]   Length of NewState
 *  PreviousState        [O]   Destination for the previous state
 *  ReturnLength         [I/O] Size of PreviousState
 *
 *
 * RETURNS
 *  Success: TRUE. Privileges are set to NewState and PreviousState is updated.
 *  Failure: FALSE.
 *
 * NOTES
 *  See NtAdjustPrivilegesToken.
590
 */
591 592
BOOL WINAPI
AdjustTokenPrivileges( HANDLE TokenHandle, BOOL DisableAllPrivileges,
593
                       PTOKEN_PRIVILEGES NewState, DWORD BufferLength,
594
                       PTOKEN_PRIVILEGES PreviousState, PDWORD ReturnLength )
595
{
596 597 598 599 600
    NTSTATUS status;

    TRACE("\n");
    
    status = NtAdjustPrivilegesToken(TokenHandle, DisableAllPrivileges,
601
                                                     NewState, BufferLength, PreviousState,
602 603 604 605 606 607
                                                     ReturnLength);
    SetLastError( RtlNtStatusToDosError( status ));
    if ((status == STATUS_SUCCESS) || (status == STATUS_NOT_ALL_ASSIGNED))
        return TRUE;
    else
        return FALSE;
608 609
}

610 611 612
/******************************************************************************
 * CheckTokenMembership [ADVAPI32.@]
 *
Jon Griffiths's avatar
Jon Griffiths committed
613 614
 * Determine if an access token is a member of a SID.
 * 
615
 * PARAMS
Jon Griffiths's avatar
Jon Griffiths committed
616 617 618 619 620 621 622
 *   TokenHandle [I] Handle from OpenProcessToken() or OpenThreadToken()
 *   SidToCheck  [I] SID that possibly contains the token
 *   IsMember    [O] Destination for result.
 *
 * RETURNS
 *  Success: TRUE. IsMember is TRUE if TokenHandle is a member, FALSE otherwise.
 *  Failure: FALSE.
623 624
 */
BOOL WINAPI
625 626
CheckTokenMembership( HANDLE token, PSID sid_to_check,
                      PBOOL is_member )
627
{
628 629
    PTOKEN_GROUPS token_groups = NULL;
    HANDLE thread_token = NULL;
630
    DWORD size, i;
631
    BOOL ret;
632

633 634 635 636 637 638
    TRACE("(%p %s %p)\n", token, debugstr_sid(sid_to_check), is_member);

    *is_member = FALSE;

    if (!token)
    {
639 640 641 642 643 644 645 646 647 648 649 650 651 652
        if (!OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, TRUE, &thread_token))
        {
            HANDLE process_token;
            ret = OpenProcessToken(GetCurrentProcess(), TOKEN_DUPLICATE, &process_token);
            if (!ret)
                goto exit;
            ret = DuplicateTokenEx(process_token, TOKEN_QUERY,
                NULL, SecurityImpersonation, TokenImpersonation,
                &thread_token);
            CloseHandle(process_token);
            if (!ret)
                goto exit;
        }
        token = thread_token;
653 654
    }

655 656 657
    ret = GetTokenInformation(token, TokenGroups, NULL, 0, &size);
    if (!ret && GetLastError() != ERROR_INSUFFICIENT_BUFFER)
        goto exit;
658 659 660 661

    token_groups = HeapAlloc(GetProcessHeap(), 0, size);
    if (!token_groups)
    {
662 663
        ret = FALSE;
        goto exit;
664 665
    }

666 667 668 669
    ret = GetTokenInformation(token, TokenGroups, token_groups, size, &size);
    if (!ret)
        goto exit;

670 671 672 673 674 675 676 677 678 679 680 681 682 683
    for (i = 0; i < token_groups->GroupCount; i++)
    {
        TRACE("Groups[%d]: {0x%x, %s}\n", i,
            token_groups->Groups[i].Attributes,
            debugstr_sid(token_groups->Groups[i].Sid));
        if ((token_groups->Groups[i].Attributes & SE_GROUP_ENABLED) &&
            EqualSid(sid_to_check, token_groups->Groups[i].Sid))
        {
            *is_member = TRUE;
            TRACE("sid enabled and found in token\n");
            break;
        }
    }

684
exit:
685
    HeapFree(GetProcessHeap(), 0, token_groups);
686
    if (thread_token != NULL) CloseHandle(thread_token);
687

688
    return ret;
689 690
}

691
/******************************************************************************
692
 * GetTokenInformation [ADVAPI32.@]
693
 *
694 695
 * Get a type of information about an access token.
 *
696
 * PARAMS
Jon Griffiths's avatar
Jon Griffiths committed
697 698 699 700 701
 *   token           [I] Handle from OpenProcessToken() or OpenThreadToken()
 *   tokeninfoclass  [I] A TOKEN_INFORMATION_CLASS from "winnt.h"
 *   tokeninfo       [O] Destination for token information
 *   tokeninfolength [I] Length of tokeninfo
 *   retlen          [O] Destination for returned token information length
702
 *
Jon Griffiths's avatar
Jon Griffiths committed
703 704 705 706 707 708
 * RETURNS
 *  Success: TRUE. tokeninfo contains retlen bytes of token information
 *  Failure: FALSE.
 *
 * NOTES
 *  See NtQueryInformationToken.
709
 */
710
BOOL WINAPI
711
GetTokenInformation( HANDLE token, TOKEN_INFORMATION_CLASS tokeninfoclass,
712
		     LPVOID tokeninfo, DWORD tokeninfolength, LPDWORD retlen )
713
{
714
    TRACE("(%p, %s, %p, %d, %p):\n",
715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732
          token,
          (tokeninfoclass == TokenUser) ? "TokenUser" :
          (tokeninfoclass == TokenGroups) ? "TokenGroups" :
          (tokeninfoclass == TokenPrivileges) ? "TokenPrivileges" :
          (tokeninfoclass == TokenOwner) ? "TokenOwner" :
          (tokeninfoclass == TokenPrimaryGroup) ? "TokenPrimaryGroup" :
          (tokeninfoclass == TokenDefaultDacl) ? "TokenDefaultDacl" :
          (tokeninfoclass == TokenSource) ? "TokenSource" :
          (tokeninfoclass == TokenType) ? "TokenType" :
          (tokeninfoclass == TokenImpersonationLevel) ? "TokenImpersonationLevel" :
          (tokeninfoclass == TokenStatistics) ? "TokenStatistics" :
          (tokeninfoclass == TokenRestrictedSids) ? "TokenRestrictedSids" :
          (tokeninfoclass == TokenSessionId) ? "TokenSessionId" :
          (tokeninfoclass == TokenGroupsAndPrivileges) ? "TokenGroupsAndPrivileges" :
          (tokeninfoclass == TokenSessionReference) ? "TokenSessionReference" :
          (tokeninfoclass == TokenSandBoxInert) ? "TokenSandBoxInert" :
          "Unknown",
          tokeninfo, tokeninfolength, retlen);
733 734
    return set_ntstatus( NtQueryInformationToken( token, tokeninfoclass, tokeninfo,
                                                  tokeninfolength, retlen));
735 736 737 738 739
}

/******************************************************************************
 * SetTokenInformation [ADVAPI32.@]
 *
Jon Griffiths's avatar
Jon Griffiths committed
740 741
 * Set information for an access token.
 *
742
 * PARAMS
Jon Griffiths's avatar
Jon Griffiths committed
743 744 745 746
 *   token           [I] Handle from OpenProcessToken() or OpenThreadToken()
 *   tokeninfoclass  [I] A TOKEN_INFORMATION_CLASS from "winnt.h"
 *   tokeninfo       [I] Token information to set
 *   tokeninfolength [I] Length of tokeninfo
747
 *
Jon Griffiths's avatar
Jon Griffiths committed
748 749 750
 * RETURNS
 *  Success: TRUE. The information for the token is set to tokeninfo.
 *  Failure: FALSE.
751 752 753 754 755
 */
BOOL WINAPI
SetTokenInformation( HANDLE token, TOKEN_INFORMATION_CLASS tokeninfoclass,
		     LPVOID tokeninfo, DWORD tokeninfolength )
{
756
    TRACE("(%p, %s, %p, %d): stub\n",
757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775
          token,
          (tokeninfoclass == TokenUser) ? "TokenUser" :
          (tokeninfoclass == TokenGroups) ? "TokenGroups" :
          (tokeninfoclass == TokenPrivileges) ? "TokenPrivileges" :
          (tokeninfoclass == TokenOwner) ? "TokenOwner" :
          (tokeninfoclass == TokenPrimaryGroup) ? "TokenPrimaryGroup" :
          (tokeninfoclass == TokenDefaultDacl) ? "TokenDefaultDacl" :
          (tokeninfoclass == TokenSource) ? "TokenSource" :
          (tokeninfoclass == TokenType) ? "TokenType" :
          (tokeninfoclass == TokenImpersonationLevel) ? "TokenImpersonationLevel" :
          (tokeninfoclass == TokenStatistics) ? "TokenStatistics" :
          (tokeninfoclass == TokenRestrictedSids) ? "TokenRestrictedSids" :
          (tokeninfoclass == TokenSessionId) ? "TokenSessionId" :
          (tokeninfoclass == TokenGroupsAndPrivileges) ? "TokenGroupsAndPrivileges" :
          (tokeninfoclass == TokenSessionReference) ? "TokenSessionReference" :
          (tokeninfoclass == TokenSandBoxInert) ? "TokenSandBoxInert" :
          "Unknown",
          tokeninfo, tokeninfolength);

776
    return set_ntstatus( NtSetInformationToken( token, tokeninfoclass, tokeninfo, tokeninfolength ));
777 778
}

779
/*************************************************************************
780
 * SetThreadToken [ADVAPI32.@]
781
 *
Jon Griffiths's avatar
Jon Griffiths committed
782
 * Assigns an 'impersonation token' to a thread so it can assume the
783
 * security privileges of another thread or process.  Can also remove
Jon Griffiths's avatar
Jon Griffiths committed
784 785 786 787 788
 * a previously assigned token. 
 *
 * PARAMS
 *   thread          [O] Handle to thread to set the token for
 *   token           [I] Token to set
789
 *
Jon Griffiths's avatar
Jon Griffiths committed
790 791 792 793 794 795 796
 * RETURNS
 *  Success: TRUE. The threads access token is set to token
 *  Failure: FALSE.
 *
 * NOTES
 *  Only supported on NT or higher. On Win9X this function does nothing.
 *  See SetTokenInformation.
797 798 799
 */
BOOL WINAPI SetThreadToken(PHANDLE thread, HANDLE token)
{
800 801
    return set_ntstatus( NtSetInformationThread( thread ? *thread : GetCurrentThread(),
                                                 ThreadImpersonationToken, &token, sizeof token ));
802 803
}

804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843
/*************************************************************************
 * CreateRestrictedToken [ADVAPI32.@]
 *
 * Create a new more restricted token from an existing token.
 *
 * PARAMS
 *   baseToken       [I] Token to base the new restricted token on
 *   flags           [I] Options
 *   nDisableSids    [I] Length of disableSids array
 *   disableSids     [I] Array of SIDs to disable in the new token
 *   nDeletePrivs    [I] Length of deletePrivs array
 *   deletePrivs     [I] Array of privileges to delete in the new token
 *   nRestrictSids   [I] Length of restrictSids array
 *   restrictSids    [I] Array of SIDs to restrict in the new token
 *   newToken        [O] Address where the new token is stored
 *
 * RETURNS
 *  Success: TRUE
 *  Failure: FALSE
 */
BOOL WINAPI CreateRestrictedToken(
    HANDLE baseToken,
    DWORD flags,
    DWORD nDisableSids,
    PSID_AND_ATTRIBUTES disableSids,
    DWORD nDeletePrivs,
    PLUID_AND_ATTRIBUTES deletePrivs,
    DWORD nRestrictSids,
    PSID_AND_ATTRIBUTES restrictSids,
    PHANDLE newToken)
{
    FIXME("(%p, 0x%x, %u, %p, %u, %p, %u, %p, %p): stub\n",
          baseToken, flags, nDisableSids, disableSids,
          nDeletePrivs, deletePrivs,
          nRestrictSids, restrictSids,
          newToken);
    SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
    return FALSE;
}

844 845 846 847 848
/*	##############################
	######	SID FUNCTIONS	######
	##############################
*/

849
/******************************************************************************
850
 * AllocateAndInitializeSid [ADVAPI32.@]
851 852
 *
 * PARAMS
853 854 855 856 857 858 859 860 861 862 863
 *   pIdentifierAuthority []
 *   nSubAuthorityCount   []
 *   nSubAuthority0       []
 *   nSubAuthority1       []
 *   nSubAuthority2       []
 *   nSubAuthority3       []
 *   nSubAuthority4       []
 *   nSubAuthority5       []
 *   nSubAuthority6       []
 *   nSubAuthority7       []
 *   pSid                 []
864
 */
865
BOOL WINAPI
866 867 868 869 870 871 872
AllocateAndInitializeSid( PSID_IDENTIFIER_AUTHORITY pIdentifierAuthority,
                          BYTE nSubAuthorityCount,
                          DWORD nSubAuthority0, DWORD nSubAuthority1,
                          DWORD nSubAuthority2, DWORD nSubAuthority3,
                          DWORD nSubAuthority4, DWORD nSubAuthority5,
                          DWORD nSubAuthority6, DWORD nSubAuthority7,
                          PSID *pSid )
873
{
874 875 876 877 878
    return set_ntstatus( RtlAllocateAndInitializeSid(
                             pIdentifierAuthority, nSubAuthorityCount,
                             nSubAuthority0, nSubAuthority1, nSubAuthority2, nSubAuthority3,
                             nSubAuthority4, nSubAuthority5, nSubAuthority6, nSubAuthority7,
                             pSid ));
879
}
880

881
/******************************************************************************
882
 * FreeSid [ADVAPI32.@]
883 884
 *
 * PARAMS
885
 *   pSid []
886
 */
887
PVOID WINAPI
888 889
FreeSid( PSID pSid )
{
890
    	RtlFreeSid(pSid);
891
	return NULL; /* is documented like this */
892 893
}

894
/******************************************************************************
895
 * CopySid [ADVAPI32.@]
896 897 898 899 900
 *
 * PARAMS
 *   nDestinationSidLength []
 *   pDestinationSid       []
 *   pSourceSid            []
901
 */
902
BOOL WINAPI
903
CopySid( DWORD nDestinationSidLength, PSID pDestinationSid, PSID pSourceSid )
904
{
905
	return RtlCopySid(nDestinationSidLength, pDestinationSid, pSourceSid);
906 907
}

908 909 910 911 912 913 914 915 916
/******************************************************************************
 * CreateWellKnownSid [ADVAPI32.@]
 */
BOOL WINAPI
CreateWellKnownSid( WELL_KNOWN_SID_TYPE WellKnownSidType,
                    PSID DomainSid,
                    PSID pSid,
                    DWORD* cbSid)
{
917
    unsigned int i;
918
    TRACE("(%d, %s, %p, %p)\n", WellKnownSidType, debugstr_sid(DomainSid), pSid, cbSid);
919

920 921
    if (cbSid == NULL || (DomainSid && !IsValidSid(DomainSid)))
    {
922 923 924 925 926 927
        SetLastError(ERROR_INVALID_PARAMETER);
        return FALSE;
    }

    for (i = 0; i < sizeof(WellKnownSids)/sizeof(WellKnownSids[0]); i++) {
        if (WellKnownSids[i].Type == WellKnownSidType) {
928
            DWORD length = GetSidLengthRequired(WellKnownSids[i].Sid.SubAuthorityCount);
929

930 931 932
            if (*cbSid < length)
            {
                *cbSid = length;
933 934 935
                SetLastError(ERROR_INSUFFICIENT_BUFFER);
                return FALSE;
            }
936 937 938 939 940
            if (!pSid)
            {
                SetLastError(ERROR_INVALID_PARAMETER);
                return FALSE;
            }
941
            CopyMemory(pSid, &WellKnownSids[i].Sid.Revision, length);
942 943 944 945 946
            *cbSid = length;
            return TRUE;
        }
    }

947 948 949 950 951 952 953 954 955 956 957 958
    if (DomainSid == NULL || *GetSidSubAuthorityCount(DomainSid) == SID_MAX_SUB_AUTHORITIES)
    {
        SetLastError(ERROR_INVALID_PARAMETER);
        return FALSE;
    }

    for (i = 0; i < sizeof(WellKnownRids)/sizeof(WellKnownRids[0]); i++)
        if (WellKnownRids[i].Type == WellKnownSidType) {
            UCHAR domain_subauth = *GetSidSubAuthorityCount(DomainSid);
            DWORD domain_sid_length = GetSidLengthRequired(domain_subauth);
            DWORD output_sid_length = GetSidLengthRequired(domain_subauth + 1);

959 960 961
            if (*cbSid < output_sid_length)
            {
                *cbSid = output_sid_length;
962 963 964
                SetLastError(ERROR_INSUFFICIENT_BUFFER);
                return FALSE;
            }
965 966 967 968 969
            if (!pSid)
            {
                SetLastError(ERROR_INVALID_PARAMETER);
                return FALSE;
            }
970 971 972 973 974 975 976
            CopyMemory(pSid, DomainSid, domain_sid_length);
            (*GetSidSubAuthorityCount(pSid))++;
            (*GetSidSubAuthority(pSid, domain_subauth)) = WellKnownRids[i].Rid;
            *cbSid = output_sid_length;
            return TRUE;
        }

977 978 979 980 981 982 983 984 985 986
    SetLastError(ERROR_INVALID_PARAMETER);
    return FALSE;
}

/******************************************************************************
 * IsWellKnownSid [ADVAPI32.@]
 */
BOOL WINAPI
IsWellKnownSid( PSID pSid, WELL_KNOWN_SID_TYPE WellKnownSidType )
{
987
    unsigned int i;
988
    TRACE("(%s, %d)\n", debugstr_sid(pSid), WellKnownSidType);
989 990 991

    for (i = 0; i < sizeof(WellKnownSids)/sizeof(WellKnownSids[0]); i++)
        if (WellKnownSids[i].Type == WellKnownSidType)
992
            if (EqualSid(pSid, (PSID)&(WellKnownSids[i].Sid.Revision)))
993 994 995 996 997
                return TRUE;

    return FALSE;
}

998 999 1000
BOOL WINAPI
IsTokenRestricted( HANDLE TokenHandle )
{
1001 1002 1003 1004
    TOKEN_GROUPS *groups;
    DWORD size;
    NTSTATUS status;
    BOOL restricted;
1005

1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033
    TRACE("(%p)\n", TokenHandle);
 
    status = NtQueryInformationToken(TokenHandle, TokenRestrictedSids, NULL, 0, &size);
    if (status != STATUS_BUFFER_TOO_SMALL)
        return FALSE;
 
    groups = HeapAlloc(GetProcessHeap(), 0, size);
    if (!groups)
    {
        SetLastError(ERROR_OUTOFMEMORY);
        return FALSE;
    }
 
    status = NtQueryInformationToken(TokenHandle, TokenRestrictedSids, groups, size, &size);
    if (status != STATUS_SUCCESS)
    {
        HeapFree(GetProcessHeap(), 0, groups);
        return set_ntstatus(status);
    }
 
    if (groups->GroupCount)
        restricted = TRUE;
    else
        restricted = FALSE;
     
    HeapFree(GetProcessHeap(), 0, groups);
 
    return restricted;
1034 1035
}

1036
/******************************************************************************
1037
 * IsValidSid [ADVAPI32.@]
1038 1039 1040
 *
 * PARAMS
 *   pSid []
Alexandre Julliard's avatar
Alexandre Julliard committed
1041
 */
1042
BOOL WINAPI
1043
IsValidSid( PSID pSid )
1044
{
1045
	return RtlValidSid( pSid );
Alexandre Julliard's avatar
Alexandre Julliard committed
1046 1047
}

1048
/******************************************************************************
1049
 * EqualSid [ADVAPI32.@]
1050 1051 1052 1053
 *
 * PARAMS
 *   pSid1 []
 *   pSid2 []
Alexandre Julliard's avatar
Alexandre Julliard committed
1054
 */
1055
BOOL WINAPI
1056
EqualSid( PSID pSid1, PSID pSid2 )
1057
{
1058 1059 1060
	BOOL ret = RtlEqualSid( pSid1, pSid2 );
	SetLastError(ERROR_SUCCESS);
	return ret;
Alexandre Julliard's avatar
Alexandre Julliard committed
1061 1062
}

1063
/******************************************************************************
1064
 * EqualPrefixSid [ADVAPI32.@]
Alexandre Julliard's avatar
Alexandre Julliard committed
1065
 */
1066
BOOL WINAPI EqualPrefixSid (PSID pSid1, PSID pSid2)
1067 1068
{
	return RtlEqualPrefixSid(pSid1, pSid2);
Alexandre Julliard's avatar
Alexandre Julliard committed
1069 1070
}

1071
/******************************************************************************
1072
 * GetSidLengthRequired [ADVAPI32.@]
1073 1074 1075
 *
 * PARAMS
 *   nSubAuthorityCount []
Alexandre Julliard's avatar
Alexandre Julliard committed
1076
 */
1077 1078 1079
DWORD WINAPI
GetSidLengthRequired( BYTE nSubAuthorityCount )
{
1080
	return RtlLengthRequiredSid(nSubAuthorityCount);
Alexandre Julliard's avatar
Alexandre Julliard committed
1081 1082
}

1083
/******************************************************************************
1084
 * InitializeSid [ADVAPI32.@]
1085 1086
 *
 * PARAMS
1087
 *   pIdentifierAuthority []
1088
 */
1089
BOOL WINAPI
1090 1091 1092 1093
InitializeSid (
	PSID pSid,
	PSID_IDENTIFIER_AUTHORITY pIdentifierAuthority,
	BYTE nSubAuthorityCount)
1094
{
1095
	return RtlInitializeSid(pSid, pIdentifierAuthority, nSubAuthorityCount);
1096 1097
}

1098 1099 1100 1101 1102
DWORD WINAPI
GetEffectiveRightsFromAclA( PACL pacl, PTRUSTEEA pTrustee, PACCESS_MASK pAccessRights )
{
    FIXME("%p %p %p - stub\n", pacl, pTrustee, pAccessRights);

1103 1104
    *pAccessRights = STANDARD_RIGHTS_ALL | SPECIFIC_RIGHTS_ALL;
    return 0;
1105 1106 1107 1108 1109 1110 1111 1112 1113 1114
}

DWORD WINAPI
GetEffectiveRightsFromAclW( PACL pacl, PTRUSTEEW pTrustee, PACCESS_MASK pAccessRights )
{
    FIXME("%p %p %p - stub\n", pacl, pTrustee, pAccessRights);

    return 1;
}

1115
/******************************************************************************
1116
 * GetSidIdentifierAuthority [ADVAPI32.@]
1117 1118
 *
 * PARAMS
1119
 *   pSid []
1120
 */
1121 1122
PSID_IDENTIFIER_AUTHORITY WINAPI
GetSidIdentifierAuthority( PSID pSid )
1123
{
1124
	return RtlIdentifierAuthoritySid(pSid);
1125
}
Alexandre Julliard's avatar
Alexandre Julliard committed
1126

1127
/******************************************************************************
1128
 * GetSidSubAuthority [ADVAPI32.@]
1129 1130 1131 1132 1133
 *
 * PARAMS
 *   pSid          []
 *   nSubAuthority []
 */
1134
PDWORD WINAPI
1135 1136
GetSidSubAuthority( PSID pSid, DWORD nSubAuthority )
{
1137
        SetLastError(ERROR_SUCCESS);
1138
	return RtlSubAuthoritySid(pSid, nSubAuthority);
1139
}
Alexandre Julliard's avatar
Alexandre Julliard committed
1140

1141
/******************************************************************************
1142
 * GetSidSubAuthorityCount [ADVAPI32.@]
1143 1144 1145 1146
 *
 * PARAMS
 *   pSid []
 */
1147
PUCHAR WINAPI
1148 1149
GetSidSubAuthorityCount (PSID pSid)
{
1150
        SetLastError(ERROR_SUCCESS);
1151
	return RtlSubAuthorityCountSid(pSid);
Alexandre Julliard's avatar
Alexandre Julliard committed
1152 1153
}

Matthew Becker's avatar
Matthew Becker committed
1154
/******************************************************************************
1155
 * GetLengthSid [ADVAPI32.@]
Matthew Becker's avatar
Matthew Becker committed
1156 1157 1158
 *
 * PARAMS
 *   pSid []
Alexandre Julliard's avatar
Alexandre Julliard committed
1159
 */
1160 1161
DWORD WINAPI
GetLengthSid (PSID pSid)
Alexandre Julliard's avatar
Alexandre Julliard committed
1162
{
1163
	return RtlLengthSid(pSid);
Alexandre Julliard's avatar
Alexandre Julliard committed
1164 1165
}

1166 1167 1168 1169
/*	##############################################
	######	SECURITY DESCRIPTOR FUNCTIONS	######
	##############################################
*/
1170

1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185
 /****************************************************************************** 
 * BuildSecurityDescriptorA [ADVAPI32.@]
 *
 * Builds a SD from 
 *
 * PARAMS
 *  pOwner                [I]
 *  pGroup                [I]
 *  cCountOfAccessEntries [I]
 *  pListOfAccessEntries  [I]
 *  cCountOfAuditEntries  [I]
 *  pListofAuditEntries   [I]
 *  pOldSD                [I]
 *  lpdwBufferLength      [I/O]
 *  pNewSD                [O]
1186 1187 1188 1189
 *
 * RETURNS
 *  Success: ERROR_SUCCESS
 *  Failure: nonzero error code from Winerror.h
1190 1191
 */
DWORD WINAPI BuildSecurityDescriptorA(
1192 1193 1194 1195 1196 1197
    IN PTRUSTEEA pOwner,
    IN PTRUSTEEA pGroup,
    IN ULONG cCountOfAccessEntries,
    IN PEXPLICIT_ACCESSA pListOfAccessEntries,
    IN ULONG cCountOfAuditEntries,
    IN PEXPLICIT_ACCESSA pListofAuditEntries,
1198
    IN PSECURITY_DESCRIPTOR pOldSD,
1199 1200
    IN OUT PULONG lpdwBufferLength,
    OUT PSECURITY_DESCRIPTOR* pNewSD)
1201
{ 
1202
    FIXME("(%p,%p,%d,%p,%d,%p,%p,%p,%p) stub!\n",pOwner,pGroup,
1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214
          cCountOfAccessEntries,pListOfAccessEntries,cCountOfAuditEntries,
          pListofAuditEntries,pOldSD,lpdwBufferLength,pNewSD);
 
    return ERROR_CALL_NOT_IMPLEMENTED;
} 
 
/******************************************************************************
 * BuildSecurityDescriptorW [ADVAPI32.@]
 *
 * See BuildSecurityDescriptorA.
 */
DWORD WINAPI BuildSecurityDescriptorW(
1215 1216 1217 1218 1219 1220
    IN PTRUSTEEW pOwner,
    IN PTRUSTEEW pGroup,
    IN ULONG cCountOfAccessEntries,
    IN PEXPLICIT_ACCESSW pListOfAccessEntries,
    IN ULONG cCountOfAuditEntries,
    IN PEXPLICIT_ACCESSW pListofAuditEntries,
1221
    IN PSECURITY_DESCRIPTOR pOldSD,
1222 1223
    IN OUT PULONG lpdwBufferLength,
    OUT PSECURITY_DESCRIPTOR* pNewSD)
1224
{ 
1225
    FIXME("(%p,%p,%d,%p,%d,%p,%p,%p,%p) stub!\n",pOwner,pGroup,
1226 1227 1228 1229 1230 1231
          cCountOfAccessEntries,pListOfAccessEntries,cCountOfAuditEntries,
          pListofAuditEntries,pOldSD,lpdwBufferLength,pNewSD);
 
    return ERROR_CALL_NOT_IMPLEMENTED;
} 

Matthew Becker's avatar
Matthew Becker committed
1232
/******************************************************************************
1233
 * InitializeSecurityDescriptor [ADVAPI32.@]
Matthew Becker's avatar
Matthew Becker committed
1234 1235 1236 1237
 *
 * PARAMS
 *   pDescr   []
 *   revision []
Alexandre Julliard's avatar
Alexandre Julliard committed
1238
 */
1239
BOOL WINAPI
1240
InitializeSecurityDescriptor( PSECURITY_DESCRIPTOR pDescr, DWORD revision )
Alexandre Julliard's avatar
Alexandre Julliard committed
1241
{
1242
	return set_ntstatus( RtlCreateSecurityDescriptor(pDescr, revision ));
Alexandre Julliard's avatar
Alexandre Julliard committed
1243 1244
}

1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261

/******************************************************************************
 * MakeAbsoluteSD [ADVAPI32.@]
 */
BOOL WINAPI MakeAbsoluteSD (
        IN PSECURITY_DESCRIPTOR pSelfRelativeSecurityDescriptor,
	OUT PSECURITY_DESCRIPTOR pAbsoluteSecurityDescriptor,
	OUT LPDWORD lpdwAbsoluteSecurityDescriptorSize,
	OUT PACL pDacl,
	OUT LPDWORD lpdwDaclSize,
	OUT PACL pSacl,
	OUT LPDWORD lpdwSaclSize,
	OUT PSID pOwner,
	OUT LPDWORD lpdwOwnerSize,
	OUT PSID pPrimaryGroup,
	OUT LPDWORD lpdwPrimaryGroupSize)
{
1262 1263 1264 1265 1266 1267
    return set_ntstatus( RtlSelfRelativeToAbsoluteSD(pSelfRelativeSecurityDescriptor,
                                                     pAbsoluteSecurityDescriptor,
                                                     lpdwAbsoluteSecurityDescriptorSize,
                                                     pDacl, lpdwDaclSize, pSacl, lpdwSaclSize,
                                                     pOwner, lpdwOwnerSize,
                                                     pPrimaryGroup, lpdwPrimaryGroupSize));
1268 1269
}

1270 1271 1272
/******************************************************************************
 * GetKernelObjectSecurity [ADVAPI32.@]
 */
1273 1274 1275 1276 1277 1278 1279
BOOL WINAPI GetKernelObjectSecurity(
        HANDLE Handle,
        SECURITY_INFORMATION RequestedInformation,
        PSECURITY_DESCRIPTOR pSecurityDescriptor,
        DWORD nLength,
        LPDWORD lpnLengthNeeded )
{
1280
    TRACE("(%p,0x%08x,%p,0x%08x,%p)\n", Handle, RequestedInformation,
1281 1282
          pSecurityDescriptor, nLength, lpnLengthNeeded);

1283 1284
    return set_ntstatus( NtQuerySecurityObject(Handle, RequestedInformation, pSecurityDescriptor,
                                               nLength, lpnLengthNeeded ));
1285 1286
}

1287 1288 1289
/******************************************************************************
 * GetPrivateObjectSecurity [ADVAPI32.@]
 */
1290 1291 1292 1293 1294 1295 1296
BOOL WINAPI GetPrivateObjectSecurity(
        PSECURITY_DESCRIPTOR ObjectDescriptor,
        SECURITY_INFORMATION SecurityInformation,
        PSECURITY_DESCRIPTOR ResultantDescriptor,
        DWORD DescriptorLength,
        PDWORD ReturnLength )
{
1297 1298 1299 1300 1301
    SECURITY_DESCRIPTOR desc;
    BOOL defaulted, present;
    PACL pacl;
    PSID psid;

1302
    TRACE("(%p,0x%08x,%p,0x%08x,%p)\n", ObjectDescriptor, SecurityInformation,
1303 1304
          ResultantDescriptor, DescriptorLength, ReturnLength);

1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336
    if (!InitializeSecurityDescriptor(&desc, SECURITY_DESCRIPTOR_REVISION))
        return FALSE;

    if (SecurityInformation & OWNER_SECURITY_INFORMATION)
    {
        if (!GetSecurityDescriptorOwner(ObjectDescriptor, &psid, &defaulted))
            return FALSE;
        SetSecurityDescriptorOwner(&desc, psid, defaulted);
    }

    if (SecurityInformation & GROUP_SECURITY_INFORMATION)
    {
        if (!GetSecurityDescriptorGroup(ObjectDescriptor, &psid, &defaulted))
            return FALSE;
        SetSecurityDescriptorGroup(&desc, psid, defaulted);
    }

    if (SecurityInformation & DACL_SECURITY_INFORMATION)
    {
        if (!GetSecurityDescriptorDacl(ObjectDescriptor, &present, &pacl, &defaulted))
            return FALSE;
        SetSecurityDescriptorDacl(&desc, present, pacl, defaulted);
    }

    if (SecurityInformation & SACL_SECURITY_INFORMATION)
    {
        if (!GetSecurityDescriptorSacl(ObjectDescriptor, &present, &pacl, &defaulted))
            return FALSE;
        SetSecurityDescriptorSacl(&desc, present, pacl, defaulted);
    }

    *ReturnLength = DescriptorLength;
1337
    return MakeSelfRelativeSD(&desc, ResultantDescriptor, ReturnLength);
1338
}
1339

Matthew Becker's avatar
Matthew Becker committed
1340
/******************************************************************************
1341
 * GetSecurityDescriptorLength [ADVAPI32.@]
1342
 */
1343
DWORD WINAPI GetSecurityDescriptorLength( PSECURITY_DESCRIPTOR pDescr)
1344
{
1345
	return RtlLengthSecurityDescriptor(pDescr);
1346 1347
}

Matthew Becker's avatar
Matthew Becker committed
1348
/******************************************************************************
1349
 * GetSecurityDescriptorOwner [ADVAPI32.@]
Matthew Becker's avatar
Matthew Becker committed
1350 1351 1352 1353
 *
 * PARAMS
 *   pOwner            []
 *   lpbOwnerDefaulted []
1354
 */
1355
BOOL WINAPI
1356
GetSecurityDescriptorOwner( PSECURITY_DESCRIPTOR pDescr, PSID *pOwner,
1357
			    LPBOOL lpbOwnerDefaulted )
1358
{
1359 1360 1361 1362
    BOOLEAN defaulted;
    BOOL ret = set_ntstatus( RtlGetOwnerSecurityDescriptor( pDescr, pOwner, &defaulted ));
    *lpbOwnerDefaulted = defaulted;
    return ret;
1363
}
1364

Matthew Becker's avatar
Matthew Becker committed
1365
/******************************************************************************
1366
 * SetSecurityDescriptorOwner [ADVAPI32.@]
Matthew Becker's avatar
Matthew Becker committed
1367 1368
 *
 * PARAMS
1369
 */
1370
BOOL WINAPI SetSecurityDescriptorOwner( PSECURITY_DESCRIPTOR pSecurityDescriptor,
1371
				   PSID pOwner, BOOL bOwnerDefaulted)
1372
{
1373
    return set_ntstatus( RtlSetOwnerSecurityDescriptor(pSecurityDescriptor, pOwner, bOwnerDefaulted));
1374 1375
}
/******************************************************************************
1376
 * GetSecurityDescriptorGroup			[ADVAPI32.@]
1377
 */
1378
BOOL WINAPI GetSecurityDescriptorGroup(
1379 1380
	PSECURITY_DESCRIPTOR SecurityDescriptor,
	PSID *Group,
1381
	LPBOOL GroupDefaulted)
1382
{
1383 1384 1385 1386
    BOOLEAN defaulted;
    BOOL ret = set_ntstatus( RtlGetGroupSecurityDescriptor(SecurityDescriptor, Group, &defaulted ));
    *GroupDefaulted = defaulted;
    return ret;
1387
}
1388
/******************************************************************************
1389
 * SetSecurityDescriptorGroup [ADVAPI32.@]
1390
 */
1391 1392
BOOL WINAPI SetSecurityDescriptorGroup ( PSECURITY_DESCRIPTOR SecurityDescriptor,
					   PSID Group, BOOL GroupDefaulted)
1393
{
1394
    return set_ntstatus( RtlSetGroupSecurityDescriptor( SecurityDescriptor, Group, GroupDefaulted));
1395
}
Alexandre Julliard's avatar
Alexandre Julliard committed
1396

Matthew Becker's avatar
Matthew Becker committed
1397
/******************************************************************************
1398
 * IsValidSecurityDescriptor [ADVAPI32.@]
Matthew Becker's avatar
Matthew Becker committed
1399 1400
 *
 * PARAMS
1401
 *   lpsecdesc []
Alexandre Julliard's avatar
Alexandre Julliard committed
1402
 */
1403
BOOL WINAPI
1404
IsValidSecurityDescriptor( PSECURITY_DESCRIPTOR SecurityDescriptor )
Alexandre Julliard's avatar
Alexandre Julliard committed
1405
{
1406
    return set_ntstatus( RtlValidSecurityDescriptor(SecurityDescriptor));
1407
}
Alexandre Julliard's avatar
Alexandre Julliard committed
1408

1409
/******************************************************************************
1410
 *  GetSecurityDescriptorDacl			[ADVAPI32.@]
1411
 */
1412
BOOL WINAPI GetSecurityDescriptorDacl(
1413
	IN PSECURITY_DESCRIPTOR pSecurityDescriptor,
1414
	OUT LPBOOL lpbDaclPresent,
1415
	OUT PACL *pDacl,
1416
	OUT LPBOOL lpbDaclDefaulted)
1417
{
1418 1419 1420 1421 1422
    BOOLEAN present, defaulted;
    BOOL ret = set_ntstatus( RtlGetDaclSecurityDescriptor(pSecurityDescriptor, &present, pDacl, &defaulted));
    *lpbDaclPresent = present;
    *lpbDaclDefaulted = defaulted;
    return ret;
1423
}
Alexandre Julliard's avatar
Alexandre Julliard committed
1424

1425
/******************************************************************************
1426
 *  SetSecurityDescriptorDacl			[ADVAPI32.@]
1427
 */
1428
BOOL WINAPI
1429 1430 1431 1432 1433
SetSecurityDescriptorDacl (
	PSECURITY_DESCRIPTOR lpsd,
	BOOL daclpresent,
	PACL dacl,
	BOOL dacldefaulted )
1434
{
1435
    return set_ntstatus( RtlSetDaclSecurityDescriptor (lpsd, daclpresent, dacl, dacldefaulted ) );
1436 1437
}
/******************************************************************************
1438
 *  GetSecurityDescriptorSacl			[ADVAPI32.@]
1439 1440 1441 1442 1443 1444 1445
 */
BOOL WINAPI GetSecurityDescriptorSacl(
	IN PSECURITY_DESCRIPTOR lpsd,
	OUT LPBOOL lpbSaclPresent,
	OUT PACL *pSacl,
	OUT LPBOOL lpbSaclDefaulted)
{
1446 1447 1448 1449 1450
    BOOLEAN present, defaulted;
    BOOL ret = set_ntstatus( RtlGetSaclSecurityDescriptor(lpsd, &present, pSacl, &defaulted) );
    *lpbSaclPresent = present;
    *lpbSaclDefaulted = defaulted;
    return ret;
1451
}
1452

1453
/**************************************************************************
1454
 * SetSecurityDescriptorSacl			[ADVAPI32.@]
1455
 */
1456
BOOL WINAPI SetSecurityDescriptorSacl (
1457
	PSECURITY_DESCRIPTOR lpsd,
1458
	BOOL saclpresent,
1459
	PACL lpsacl,
1460
	BOOL sacldefaulted)
1461
{
1462
    return set_ntstatus (RtlSetSaclSecurityDescriptor(lpsd, saclpresent, lpsacl, sacldefaulted));
Alexandre Julliard's avatar
Alexandre Julliard committed
1463
}
1464
/******************************************************************************
1465
 * MakeSelfRelativeSD [ADVAPI32.@]
1466 1467
 *
 * PARAMS
1468 1469 1470
 *   lpabssecdesc  []
 *   lpselfsecdesc []
 *   lpbuflen      []
Alexandre Julliard's avatar
Alexandre Julliard committed
1471
 */
1472
BOOL WINAPI
1473 1474 1475 1476
MakeSelfRelativeSD(
	IN PSECURITY_DESCRIPTOR pAbsoluteSecurityDescriptor,
	IN PSECURITY_DESCRIPTOR pSelfRelativeSecurityDescriptor,
	IN OUT LPDWORD lpdwBufferLength)
Alexandre Julliard's avatar
Alexandre Julliard committed
1477
{
1478 1479
    return set_ntstatus( RtlMakeSelfRelativeSD( pAbsoluteSecurityDescriptor,
                                                pSelfRelativeSecurityDescriptor, lpdwBufferLength));
Alexandre Julliard's avatar
Alexandre Julliard committed
1480 1481
}

1482
/******************************************************************************
1483
 * GetSecurityDescriptorControl			[ADVAPI32.@]
1484 1485
 */

1486 1487
BOOL WINAPI GetSecurityDescriptorControl ( PSECURITY_DESCRIPTOR  pSecurityDescriptor,
		 PSECURITY_DESCRIPTOR_CONTROL pControl, LPDWORD lpdwRevision)
1488
{
1489
    return set_ntstatus( RtlGetControlSecurityDescriptor(pSecurityDescriptor,pControl,lpdwRevision));
1490
}
1491

1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502
/******************************************************************************
 * SetSecurityDescriptorControl			[ADVAPI32.@]
 */
BOOL WINAPI SetSecurityDescriptorControl( PSECURITY_DESCRIPTOR pSecurityDescriptor,
  SECURITY_DESCRIPTOR_CONTROL ControlBitsOfInterest,
  SECURITY_DESCRIPTOR_CONTROL ControlBitsToSet )
{
    return set_ntstatus( RtlSetControlSecurityDescriptor(
        pSecurityDescriptor, ControlBitsOfInterest, ControlBitsToSet ) );
}

1503 1504 1505 1506 1507 1508
/*	##############################
	######	ACL FUNCTIONS	######
	##############################
*/

/*************************************************************************
1509
 * InitializeAcl [ADVAPI32.@]
1510
 */
1511
BOOL WINAPI InitializeAcl(PACL acl, DWORD size, DWORD rev)
1512
{
1513
    return set_ntstatus( RtlCreateAcl(acl, size, rev));
1514 1515
}

1516 1517
BOOL WINAPI ImpersonateNamedPipeClient( HANDLE hNamedPipe )
{
1518 1519
    IO_STATUS_BLOCK io_block;

1520
    TRACE("(%p)\n", hNamedPipe);
1521

1522 1523
    return set_ntstatus( NtFsControlFile(hNamedPipe, NULL, NULL, NULL,
                         &io_block, FSCTL_PIPE_IMPERSONATE, NULL, 0, NULL, 0) );
1524 1525
}

1526 1527 1528 1529 1530 1531 1532 1533 1534
/******************************************************************************
 *  AddAccessAllowedAce [ADVAPI32.@]
 */
BOOL WINAPI AddAccessAllowedAce(
        IN OUT PACL pAcl,
        IN DWORD dwAceRevision,
        IN DWORD AccessMask,
        IN PSID pSid)
{
1535
    return set_ntstatus(RtlAddAccessAllowedAce(pAcl, dwAceRevision, AccessMask, pSid));
1536 1537
}

1538 1539 1540 1541 1542 1543 1544 1545 1546 1547
/******************************************************************************
 *  AddAccessAllowedAceEx [ADVAPI32.@]
 */
BOOL WINAPI AddAccessAllowedAceEx(
        IN OUT PACL pAcl,
        IN DWORD dwAceRevision,
	IN DWORD AceFlags,
        IN DWORD AccessMask,
        IN PSID pSid)
{
1548
    return set_ntstatus(RtlAddAccessAllowedAceEx(pAcl, dwAceRevision, AceFlags, AccessMask, pSid));
1549 1550
}

1551 1552 1553 1554 1555 1556 1557 1558 1559
/******************************************************************************
 *  AddAccessDeniedAce [ADVAPI32.@]
 */
BOOL WINAPI AddAccessDeniedAce(
        IN OUT PACL pAcl,
        IN DWORD dwAceRevision,
        IN DWORD AccessMask,
        IN PSID pSid)
{
1560
    return set_ntstatus(RtlAddAccessDeniedAce(pAcl, dwAceRevision, AccessMask, pSid));
1561 1562 1563
}

/******************************************************************************
1564 1565 1566 1567 1568 1569 1570 1571 1572
 *  AddAccessDeniedAceEx [ADVAPI32.@]
 */
BOOL WINAPI AddAccessDeniedAceEx(
        IN OUT PACL pAcl,
        IN DWORD dwAceRevision,
	IN DWORD AceFlags,
        IN DWORD AccessMask,
        IN PSID pSid)
{
1573
    return set_ntstatus(RtlAddAccessDeniedAceEx(pAcl, dwAceRevision, AceFlags, AccessMask, pSid));
1574 1575 1576 1577
}

/******************************************************************************
 *  AddAce [ADVAPI32.@]
1578 1579 1580 1581 1582 1583 1584 1585
 */
BOOL WINAPI AddAce(
        IN OUT PACL pAcl,
        IN DWORD dwAceRevision,
        IN DWORD dwStartingAceIndex,
        LPVOID pAceList,
        DWORD nAceListLength)
{
1586
    return set_ntstatus(RtlAddAce(pAcl, dwAceRevision, dwStartingAceIndex, pAceList, nAceListLength));
1587 1588
}

1589 1590 1591 1592 1593
/******************************************************************************
 * DeleteAce [ADVAPI32.@]
 */
BOOL WINAPI DeleteAce(PACL pAcl, DWORD dwAceIndex)
{
1594
    return set_ntstatus(RtlDeleteAce(pAcl, dwAceIndex));
1595 1596
}

1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609
/******************************************************************************
 *  FindFirstFreeAce [ADVAPI32.@]
 */
BOOL WINAPI FindFirstFreeAce(IN PACL pAcl, LPVOID * pAce)
{
	return RtlFirstFreeAce(pAcl, (PACE_HEADER *)pAce);
}

/******************************************************************************
 * GetAce [ADVAPI32.@]
 */
BOOL WINAPI GetAce(PACL pAcl,DWORD dwAceIndex,LPVOID *pAce )
{
1610
    return set_ntstatus(RtlGetAce(pAcl, dwAceIndex, pAce));
1611 1612
}

1613 1614 1615 1616 1617 1618 1619 1620 1621
/******************************************************************************
 * GetAclInformation [ADVAPI32.@]
 */
BOOL WINAPI GetAclInformation(
  PACL pAcl,
  LPVOID pAclInformation,
  DWORD nAclInformationLength,
  ACL_INFORMATION_CLASS dwAclInformationClass)
{
1622 1623
    return set_ntstatus(RtlQueryInformationAcl(pAcl, pAclInformation,
                                               nAclInformationLength, dwAclInformationClass));
1624 1625
}

1626 1627 1628 1629 1630 1631 1632 1633
/******************************************************************************
 *  IsValidAcl [ADVAPI32.@]
 */
BOOL WINAPI IsValidAcl(IN PACL pAcl)
{
	return RtlValidAcl(pAcl);
}

1634 1635 1636 1637 1638
/*	##############################
	######	MISC FUNCTIONS	######
	##############################
*/

1639 1640 1641 1642 1643 1644 1645 1646
/******************************************************************************
 * AllocateLocallyUniqueId [ADVAPI32.@]
 *
 * PARAMS
 *   lpLuid []
 */
BOOL WINAPI AllocateLocallyUniqueId( PLUID lpLuid )
{
1647
    return set_ntstatus(NtAllocateLocallyUniqueId(lpLuid));
1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741
}

static const WCHAR SE_CREATE_TOKEN_NAME_W[] =
 { 'S','e','C','r','e','a','t','e','T','o','k','e','n','P','r','i','v','i','l','e','g','e',0 };
static const WCHAR SE_ASSIGNPRIMARYTOKEN_NAME_W[] =
 { 'S','e','A','s','s','i','g','n','P','r','i','m','a','r','y','T','o','k','e','n','P','r','i','v','i','l','e','g','e',0 };
static const WCHAR SE_LOCK_MEMORY_NAME_W[] =
 { 'S','e','L','o','c','k','M','e','m','o','r','y','P','r','i','v','i','l','e','g','e',0 };
static const WCHAR SE_INCREASE_QUOTA_NAME_W[] =
 { 'S','e','I','n','c','r','e','a','s','e','Q','u','o','t','a','P','r','i','v','i','l','e','g','e',0 };
static const WCHAR SE_MACHINE_ACCOUNT_NAME_W[] =
 { 'S','e','M','a','c','h','i','n','e','A','c','c','o','u','n','t','P','r','i','v','i','l','e','g','e',0 };
static const WCHAR SE_TCB_NAME_W[] =
 { 'S','e','T','c','b','P','r','i','v','i','l','e','g','e',0 };
static const WCHAR SE_SECURITY_NAME_W[] =
 { 'S','e','S','e','c','u','r','i','t','y','P','r','i','v','i','l','e','g','e',0 };
static const WCHAR SE_TAKE_OWNERSHIP_NAME_W[] =
 { 'S','e','T','a','k','e','O','w','n','e','r','s','h','i','p','P','r','i','v','i','l','e','g','e',0 };
static const WCHAR SE_LOAD_DRIVER_NAME_W[] =
 { 'S','e','L','o','a','d','D','r','i','v','e','r','P','r','i','v','i','l','e','g','e',0 };
static const WCHAR SE_SYSTEM_PROFILE_NAME_W[] =
 { 'S','e','S','y','s','t','e','m','P','r','o','f','i','l','e','P','r','i','v','i','l','e','g','e',0 };
static const WCHAR SE_SYSTEMTIME_NAME_W[] =
 { 'S','e','S','y','s','t','e','m','t','i','m','e','P','r','i','v','i','l','e','g','e',0 };
static const WCHAR SE_PROF_SINGLE_PROCESS_NAME_W[] =
 { 'S','e','P','r','o','f','i','l','e','S','i','n','g','l','e','P','r','o','c','e','s','s','P','r','i','v','i','l','e','g','e',0 };
static const WCHAR SE_INC_BASE_PRIORITY_NAME_W[] =
 { 'S','e','I','n','c','r','e','a','s','e','B','a','s','e','P','r','i','o','r','i','t','y','P','r','i','v','i','l','e','g','e',0 };
static const WCHAR SE_CREATE_PAGEFILE_NAME_W[] =
 { 'S','e','C','r','e','a','t','e','P','a','g','e','f','i','l','e','P','r','i','v','i','l','e','g','e',0 };
static const WCHAR SE_CREATE_PERMANENT_NAME_W[] =
 { 'S','e','C','r','e','a','t','e','P','e','r','m','a','n','e','n','t','P','r','i','v','i','l','e','g','e',0 };
static const WCHAR SE_BACKUP_NAME_W[] =
 { 'S','e','B','a','c','k','u','p','P','r','i','v','i','l','e','g','e',0 };
static const WCHAR SE_RESTORE_NAME_W[] =
 { 'S','e','R','e','s','t','o','r','e','P','r','i','v','i','l','e','g','e',0 };
static const WCHAR SE_SHUTDOWN_NAME_W[] =
 { 'S','e','S','h','u','t','d','o','w','n','P','r','i','v','i','l','e','g','e',0 };
static const WCHAR SE_DEBUG_NAME_W[] =
 { 'S','e','D','e','b','u','g','P','r','i','v','i','l','e','g','e',0 };
static const WCHAR SE_AUDIT_NAME_W[] =
 { 'S','e','A','u','d','i','t','P','r','i','v','i','l','e','g','e',0 };
static const WCHAR SE_SYSTEM_ENVIRONMENT_NAME_W[] =
 { 'S','e','S','y','s','t','e','m','E','n','v','i','r','o','n','m','e','n','t','P','r','i','v','i','l','e','g','e',0 };
static const WCHAR SE_CHANGE_NOTIFY_NAME_W[] =
 { 'S','e','C','h','a','n','g','e','N','o','t','i','f','y','P','r','i','v','i','l','e','g','e',0 };
static const WCHAR SE_REMOTE_SHUTDOWN_NAME_W[] =
 { 'S','e','R','e','m','o','t','e','S','h','u','t','d','o','w','n','P','r','i','v','i','l','e','g','e',0 };
static const WCHAR SE_UNDOCK_NAME_W[] =
 { 'S','e','U','n','d','o','c','k','P','r','i','v','i','l','e','g','e',0 };
static const WCHAR SE_SYNC_AGENT_NAME_W[] =
 { 'S','e','S','y','n','c','A','g','e','n','t','P','r','i','v','i','l','e','g','e',0 };
static const WCHAR SE_ENABLE_DELEGATION_NAME_W[] =
 { 'S','e','E','n','a','b','l','e','D','e','l','e','g','a','t','i','o','n','P','r','i','v','i','l','e','g','e',0 };
static const WCHAR SE_MANAGE_VOLUME_NAME_W[] =
 { 'S','e','M','a','n','a','g','e','V','o','l','u','m','e','P','r','i','v','i','l','e','g','e',0 };
static const WCHAR SE_IMPERSONATE_NAME_W[] =
 { 'S','e','I','m','p','e','r','s','o','n','a','t','e','P','r','i','v','i','l','e','g','e',0 };
static const WCHAR SE_CREATE_GLOBAL_NAME_W[] =
 { 'S','e','C','r','e','a','t','e','G','l','o','b','a','l','P','r','i','v','i','l','e','g','e',0 };

static const WCHAR * const WellKnownPrivNames[SE_MAX_WELL_KNOWN_PRIVILEGE + 1] =
{
    NULL,
    NULL,
    SE_CREATE_TOKEN_NAME_W,
    SE_ASSIGNPRIMARYTOKEN_NAME_W,
    SE_LOCK_MEMORY_NAME_W,
    SE_INCREASE_QUOTA_NAME_W,
    SE_MACHINE_ACCOUNT_NAME_W,
    SE_TCB_NAME_W,
    SE_SECURITY_NAME_W,
    SE_TAKE_OWNERSHIP_NAME_W,
    SE_LOAD_DRIVER_NAME_W,
    SE_SYSTEM_PROFILE_NAME_W,
    SE_SYSTEMTIME_NAME_W,
    SE_PROF_SINGLE_PROCESS_NAME_W,
    SE_INC_BASE_PRIORITY_NAME_W,
    SE_CREATE_PAGEFILE_NAME_W,
    SE_CREATE_PERMANENT_NAME_W,
    SE_BACKUP_NAME_W,
    SE_RESTORE_NAME_W,
    SE_SHUTDOWN_NAME_W,
    SE_DEBUG_NAME_W,
    SE_AUDIT_NAME_W,
    SE_SYSTEM_ENVIRONMENT_NAME_W,
    SE_CHANGE_NOTIFY_NAME_W,
    SE_REMOTE_SHUTDOWN_NAME_W,
    SE_UNDOCK_NAME_W,
    SE_SYNC_AGENT_NAME_W,
    SE_ENABLE_DELEGATION_NAME_W,
    SE_MANAGE_VOLUME_NAME_W,
    SE_IMPERSONATE_NAME_W,
    SE_CREATE_GLOBAL_NAME_W,
1742 1743
};

1744
/******************************************************************************
1745
 * LookupPrivilegeValueW			[ADVAPI32.@]
1746
 *
Jon Griffiths's avatar
Jon Griffiths committed
1747
 * See LookupPrivilegeValueA.
Alexandre Julliard's avatar
Alexandre Julliard committed
1748
 */
1749
BOOL WINAPI
Andreas Mohr's avatar
Andreas Mohr committed
1750
LookupPrivilegeValueW( LPCWSTR lpSystemName, LPCWSTR lpName, PLUID lpLuid )
Alexandre Julliard's avatar
Alexandre Julliard committed
1751
{
1752 1753 1754 1755
    UINT i;

    TRACE("%s,%s,%p\n",debugstr_w(lpSystemName), debugstr_w(lpName), lpLuid);

1756
    if (!ADVAPI_IsLocalComputer(lpSystemName))
1757
    {
1758 1759 1760 1761 1762 1763 1764 1765
        SetLastError(RPC_S_SERVER_UNAVAILABLE);
        return FALSE;
    }
    if (!lpName)
    {
        SetLastError(ERROR_NO_SUCH_PRIVILEGE);
        return FALSE;
    }
1766
    for( i=SE_MIN_WELL_KNOWN_PRIVILEGE; i<=SE_MAX_WELL_KNOWN_PRIVILEGE; i++ )
1767 1768
    {
        if( !WellKnownPrivNames[i] )
1769
            continue;
1770
        if( strcmpiW( WellKnownPrivNames[i], lpName) )
1771 1772 1773
            continue;
        lpLuid->LowPart = i;
        lpLuid->HighPart = 0;
1774
        TRACE( "%s -> %08x-%08x\n",debugstr_w( lpSystemName ),
1775 1776 1777
               lpLuid->HighPart, lpLuid->LowPart );
        return TRUE;
    }
1778
    SetLastError(ERROR_NO_SUCH_PRIVILEGE);
1779
    return FALSE;
Alexandre Julliard's avatar
Alexandre Julliard committed
1780 1781
}

1782
/******************************************************************************
1783
 * LookupPrivilegeValueA			[ADVAPI32.@]
Jon Griffiths's avatar
Jon Griffiths committed
1784 1785 1786 1787 1788 1789
 *
 * Retrieves LUID used on a system to represent the privilege name.
 *
 * PARAMS
 *  lpSystemName [I] Name of the system
 *  lpName       [I] Name of the privilege
Jon Griffiths's avatar
Jon Griffiths committed
1790
 *  lpLuid       [O] Destination for the resulting LUID
Jon Griffiths's avatar
Jon Griffiths committed
1791 1792
 *
 * RETURNS
Jon Griffiths's avatar
Jon Griffiths committed
1793
 *  Success: TRUE. lpLuid contains the requested LUID.
Jon Griffiths's avatar
Jon Griffiths committed
1794
 *  Failure: FALSE.
Alexandre Julliard's avatar
Alexandre Julliard committed
1795
 */
1796
BOOL WINAPI
Andreas Mohr's avatar
Andreas Mohr committed
1797
LookupPrivilegeValueA( LPCSTR lpSystemName, LPCSTR lpName, PLUID lpLuid )
Alexandre Julliard's avatar
Alexandre Julliard committed
1798
{
1799 1800
    UNICODE_STRING lpSystemNameW;
    UNICODE_STRING lpNameW;
1801 1802
    BOOL ret;

1803 1804 1805 1806 1807
    RtlCreateUnicodeStringFromAsciiz(&lpSystemNameW, lpSystemName);
    RtlCreateUnicodeStringFromAsciiz(&lpNameW,lpName);
    ret = LookupPrivilegeValueW(lpSystemNameW.Buffer, lpNameW.Buffer, lpLuid);
    RtlFreeUnicodeString(&lpNameW);
    RtlFreeUnicodeString(&lpSystemNameW);
1808
    return ret;
Alexandre Julliard's avatar
Alexandre Julliard committed
1809 1810
}

1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827
BOOL WINAPI LookupPrivilegeDisplayNameA( LPCSTR lpSystemName, LPCSTR lpName, LPSTR lpDisplayName,
                                         LPDWORD cchDisplayName, LPDWORD lpLanguageId )
{
    FIXME("%s %s %s %p %p - stub\n", debugstr_a(lpSystemName), debugstr_a(lpName),
          debugstr_a(lpDisplayName), cchDisplayName, lpLanguageId);

    return FALSE;
}

BOOL WINAPI LookupPrivilegeDisplayNameW( LPCWSTR lpSystemName, LPCWSTR lpName, LPWSTR lpDisplayName,
                                         LPDWORD cchDisplayName, LPDWORD lpLanguageId )
{
    FIXME("%s %s %s %p %p - stub\n", debugstr_w(lpSystemName), debugstr_w(lpName),
          debugstr_w(lpDisplayName), cchDisplayName, lpLanguageId);

    return FALSE;
}
1828 1829 1830

/******************************************************************************
 * LookupPrivilegeNameA			[ADVAPI32.@]
1831
 *
1832
 * See LookupPrivilegeNameW.
1833 1834
 */
BOOL WINAPI
1835 1836
LookupPrivilegeNameA( LPCSTR lpSystemName, PLUID lpLuid, LPSTR lpName,
 LPDWORD cchName)
1837
{
1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854
    UNICODE_STRING lpSystemNameW;
    BOOL ret;
    DWORD wLen = 0;

    TRACE("%s %p %p %p\n", debugstr_a(lpSystemName), lpLuid, lpName, cchName);

    RtlCreateUnicodeStringFromAsciiz(&lpSystemNameW, lpSystemName);
    ret = LookupPrivilegeNameW(lpSystemNameW.Buffer, lpLuid, NULL, &wLen);
    if (!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER)
    {
        LPWSTR lpNameW = HeapAlloc(GetProcessHeap(), 0, wLen * sizeof(WCHAR));

        ret = LookupPrivilegeNameW(lpSystemNameW.Buffer, lpLuid, lpNameW,
         &wLen);
        if (ret)
        {
            /* Windows crashes if cchName is NULL, so will I */
1855
            unsigned int len = WideCharToMultiByte(CP_ACP, 0, lpNameW, -1, lpName,
1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880
             *cchName, NULL, NULL);

            if (len == 0)
            {
                /* WideCharToMultiByte failed */
                ret = FALSE;
            }
            else if (len > *cchName)
            {
                *cchName = len;
                SetLastError(ERROR_INSUFFICIENT_BUFFER);
                ret = FALSE;
            }
            else
            {
                /* WideCharToMultiByte succeeded, output length needs to be
                 * length not including NULL terminator
                 */
                *cchName = len - 1;
            }
        }
        HeapFree(GetProcessHeap(), 0, lpNameW);
    }
    RtlFreeUnicodeString(&lpSystemNameW);
    return ret;
1881 1882 1883 1884
}

/******************************************************************************
 * LookupPrivilegeNameW			[ADVAPI32.@]
1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906
 *
 * Retrieves the privilege name referred to by the LUID lpLuid.
 *
 * PARAMS
 *  lpSystemName [I]   Name of the system
 *  lpLuid       [I]   Privilege value
 *  lpName       [O]   Name of the privilege
 *  cchName      [I/O] Number of characters in lpName.
 *
 * RETURNS
 *  Success: TRUE. lpName contains the name of the privilege whose value is
 *  *lpLuid.
 *  Failure: FALSE.
 *
 * REMARKS
 *  Only well-known privilege names (those defined in winnt.h) can be retrieved
 *  using this function.
 *  If the length of lpName is too small, on return *cchName will contain the
 *  number of WCHARs needed to contain the privilege, including the NULL
 *  terminator, and GetLastError will return ERROR_INSUFFICIENT_BUFFER.
 *  On success, *cchName will contain the number of characters stored in
 *  lpName, NOT including the NULL terminator.
1907 1908
 */
BOOL WINAPI
1909 1910
LookupPrivilegeNameW( LPCWSTR lpSystemName, PLUID lpLuid, LPWSTR lpName,
 LPDWORD cchName)
1911
{
1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940
    size_t privNameLen;

    TRACE("%s,%p,%p,%p\n",debugstr_w(lpSystemName), lpLuid, lpName, cchName);

    if (!ADVAPI_IsLocalComputer(lpSystemName))
    {
        SetLastError(RPC_S_SERVER_UNAVAILABLE);
        return FALSE;
    }
    if (lpLuid->HighPart || (lpLuid->LowPart < SE_MIN_WELL_KNOWN_PRIVILEGE ||
     lpLuid->LowPart > SE_MAX_WELL_KNOWN_PRIVILEGE))
    {
        SetLastError(ERROR_NO_SUCH_PRIVILEGE);
        return FALSE;
    }
    privNameLen = strlenW(WellKnownPrivNames[lpLuid->LowPart]);
    /* Windows crashes if cchName is NULL, so will I */
    if (*cchName <= privNameLen)
    {
        *cchName = privNameLen + 1;
        SetLastError(ERROR_INSUFFICIENT_BUFFER);
        return FALSE;
    }
    else
    {
        strcpyW(lpName, WellKnownPrivNames[lpLuid->LowPart]);
        *cchName = privNameLen;
        return TRUE;
    }
1941 1942
}

1943
/******************************************************************************
1944
 * GetFileSecurityA [ADVAPI32.@]
1945
 *
Jon Griffiths's avatar
Jon Griffiths committed
1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961
 * Obtains Specified information about the security of a file or directory.
 *
 * PARAMS
 *  lpFileName           [I] Name of the file to get info for
 *  RequestedInformation [I] SE_ flags from "winnt.h"
 *  pSecurityDescriptor  [O] Destination for security information
 *  nLength              [I] Length of pSecurityDescriptor
 *  lpnLengthNeeded      [O] Destination for length of returned security information
 *
 * RETURNS
 *  Success: TRUE. pSecurityDescriptor contains the requested information.
 *  Failure: FALSE. lpnLengthNeeded contains the required space to return the info. 
 *
 * NOTES
 *  The information returned is constrained by the callers access rights and
 *  privileges.
Alexandre Julliard's avatar
Alexandre Julliard committed
1962
 */
1963
BOOL WINAPI
1964
GetFileSecurityA( LPCSTR lpFileName,
1965 1966 1967
                    SECURITY_INFORMATION RequestedInformation,
                    PSECURITY_DESCRIPTOR pSecurityDescriptor,
                    DWORD nLength, LPDWORD lpnLengthNeeded )
Alexandre Julliard's avatar
Alexandre Julliard committed
1968
{
1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981
    DWORD len;
    BOOL r;
    LPWSTR name = NULL;

    if( lpFileName )
    {
        len = MultiByteToWideChar( CP_ACP, 0, lpFileName, -1, NULL, 0 );
        name = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
        MultiByteToWideChar( CP_ACP, 0, lpFileName, -1, name, len );
    }

    r = GetFileSecurityW( name, RequestedInformation, pSecurityDescriptor,
                          nLength, lpnLengthNeeded );
1982
    HeapFree( GetProcessHeap(), 0, name );
1983 1984

    return r;
Alexandre Julliard's avatar
Alexandre Julliard committed
1985 1986
}

1987
/******************************************************************************
1988
 * GetFileSecurityW [ADVAPI32.@]
1989
 *
Jon Griffiths's avatar
Jon Griffiths committed
1990
 * See GetFileSecurityA.
Alexandre Julliard's avatar
Alexandre Julliard committed
1991
 */
1992
BOOL WINAPI
1993
GetFileSecurityW( LPCWSTR lpFileName,
1994 1995 1996
                    SECURITY_INFORMATION RequestedInformation,
                    PSECURITY_DESCRIPTOR pSecurityDescriptor,
                    DWORD nLength, LPDWORD lpnLengthNeeded )
1997
{
1998 1999
    HANDLE hfile;
    NTSTATUS status;
2000
    DWORD access = 0;
2001

2002 2003 2004 2005
    TRACE("(%s,%d,%p,%d,%p)\n", debugstr_w(lpFileName),
          RequestedInformation, pSecurityDescriptor,
          nLength, lpnLengthNeeded);

2006 2007 2008 2009 2010 2011 2012
    if (RequestedInformation & (OWNER_SECURITY_INFORMATION|GROUP_SECURITY_INFORMATION|
                                DACL_SECURITY_INFORMATION))
        access |= READ_CONTROL;
    if (RequestedInformation & SACL_SECURITY_INFORMATION)
        access |= ACCESS_SYSTEM_SECURITY;

    hfile = CreateFileW( lpFileName, access, FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
2013
                         NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0 );
2014
    if ( hfile == INVALID_HANDLE_VALUE )
2015 2016
        return FALSE;

2017 2018 2019 2020
    status = NtQuerySecurityObject( hfile, RequestedInformation, pSecurityDescriptor,
                                    nLength, lpnLengthNeeded );
    CloseHandle( hfile );
    return set_ntstatus( status );
Alexandre Julliard's avatar
Alexandre Julliard committed
2021
}
Alexandre Julliard's avatar
Alexandre Julliard committed
2022

2023

2024
/******************************************************************************
2025
 * LookupAccountSidA [ADVAPI32.@]
Alexandre Julliard's avatar
Alexandre Julliard committed
2026
 */
2027
BOOL WINAPI
2028 2029 2030 2031 2032 2033 2034 2035 2036
LookupAccountSidA(
	IN LPCSTR system,
	IN PSID sid,
	OUT LPSTR account,
	IN OUT LPDWORD accountSize,
	OUT LPSTR domain,
	IN OUT LPDWORD domainSize,
	OUT PSID_NAME_USE name_use )
{
2037 2038 2039 2040 2041
    DWORD len;
    BOOL r;
    LPWSTR systemW = NULL;
    LPWSTR accountW = NULL;
    LPWSTR domainW = NULL;
2042 2043
    DWORD accountSizeW = *accountSize;
    DWORD domainSizeW = *domainSize;
2044 2045 2046

    if (system) {
        len = MultiByteToWideChar( CP_ACP, 0, system, -1, NULL, 0 );
2047
        systemW = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
2048 2049
        MultiByteToWideChar( CP_ACP, 0, system, -1, systemW, len );
    }
2050 2051 2052 2053
    if (account)
        accountW = HeapAlloc( GetProcessHeap(), 0, accountSizeW * sizeof(WCHAR) );
    if (domain)
        domainW = HeapAlloc( GetProcessHeap(), 0, domainSizeW * sizeof(WCHAR) );
2054

2055
    r = LookupAccountSidW( systemW, sid, accountW, &accountSizeW, domainW, &domainSizeW, name_use );
2056

2057
    if (r) {
2058 2059 2060 2061 2062
        if (accountW && *accountSize) {
            len = WideCharToMultiByte( CP_ACP, 0, accountW, -1, NULL, 0, NULL, NULL );
            WideCharToMultiByte( CP_ACP, 0, accountW, -1, account, len, NULL, NULL );
            *accountSize = len;
        } else
2063
            *accountSize = accountSizeW + 1;
2064 2065 2066 2067 2068 2069

        if (domainW && *domainSize) {
            len = WideCharToMultiByte( CP_ACP, 0, domainW, -1, NULL, 0, NULL, NULL );
            WideCharToMultiByte( CP_ACP, 0, domainW, -1, domain, len, NULL, NULL );
            *domainSize = len;
        } else
2070
            *domainSize = domainSizeW + 1;
2071
    }
2072 2073 2074 2075 2076
    else
    {
        *accountSize = accountSizeW + 1;
        *domainSize = domainSizeW + 1;
    }
2077

2078 2079 2080 2081 2082
    HeapFree( GetProcessHeap(), 0, systemW );
    HeapFree( GetProcessHeap(), 0, accountW );
    HeapFree( GetProcessHeap(), 0, domainW );

    return r;
Alexandre Julliard's avatar
Alexandre Julliard committed
2083 2084
}

2085
/******************************************************************************
2086
 * LookupAccountSidW [ADVAPI32.@]
2087 2088 2089 2090 2091 2092 2093 2094 2095 2096
 *
 * PARAMS
 *   system      []
 *   sid         []
 *   account     []
 *   accountSize []
 *   domain      []
 *   domainSize  []
 *   name_use    []
 */
2097

2098
BOOL WINAPI
2099 2100 2101 2102 2103 2104 2105 2106 2107
LookupAccountSidW(
	IN LPCWSTR system,
	IN PSID sid,
	OUT LPWSTR account,
	IN OUT LPDWORD accountSize,
	OUT LPWSTR domain,
	IN OUT LPDWORD domainSize,
	OUT PSID_NAME_USE name_use )
{
2108
    unsigned int i, j;
2109 2110 2111 2112
    const WCHAR * ac = NULL;
    const WCHAR * dm = NULL;
    SID_NAME_USE use = 0;
    LPWSTR computer_name = NULL;
2113
    LPWSTR account_name = NULL;
2114

2115
    TRACE("(%s,sid=%s,%p,%p(%u),%p,%p(%u),%p)\n",
2116 2117 2118 2119
	  debugstr_w(system),debugstr_sid(sid),
	  account,accountSize,accountSize?*accountSize:0,
	  domain,domainSize,domainSize?*domainSize:0,
	  name_use);
2120

2121 2122
    if (!ADVAPI_IsLocalComputer(system)) {
        FIXME("Only local computer supported!\n");
2123
        SetLastError(RPC_S_SERVER_UNAVAILABLE);
2124 2125
        return FALSE;
    }
2126 2127

    /* check the well known SIDs first */
2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140
    for (i = 0; i <= 60; i++) {
        if (IsWellKnownSid(sid, i)) {
            for (j = 0; j < (sizeof(ACCOUNT_SIDS) / sizeof(ACCOUNT_SIDS[0])); j++) {
                if (ACCOUNT_SIDS[j].type == i) {
                    ac = ACCOUNT_SIDS[j].account;
                    dm = ACCOUNT_SIDS[j].domain;
                    use = ACCOUNT_SIDS[j].name_use;
                }
            }
            break;
        }
    }

2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156
    if (dm == NULL) {
        MAX_SID local;

        /* check for the local computer next */
        if (ADVAPI_GetComputerSid(&local)) {
            DWORD size = MAX_COMPUTERNAME_LENGTH + 1;
            BOOL result;

            computer_name = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
            result = GetComputerNameW(computer_name,  &size);

            if (result) {
                if (EqualSid(sid, &local)) {
                    dm = computer_name;
                    ac = Blank;
                    use = 3;
2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172
                } else {
                    local.SubAuthorityCount++;

                    if (EqualPrefixSid(sid, &local)) {
                        dm = computer_name;
                        use = 1;
                        switch (((MAX_SID *)sid)->SubAuthority[4]) {
                        case DOMAIN_USER_RID_ADMIN:
                            ac = Administrator;
                            break;
                        case DOMAIN_USER_RID_GUEST:
                            ac = Guest;
                            break;
                        case DOMAIN_GROUP_RID_ADMINS:
                            ac = Domain_Admins;
                            break;
2173
                        case DOMAIN_GROUP_RID_USERS:
2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198
                            ac = Domain_Users;
                            break;
                        case DOMAIN_GROUP_RID_GUESTS:
                            ac = Domain_Guests;
                            break;
                        case DOMAIN_GROUP_RID_COMPUTERS:
                            ac = Domain_Computers;
                            break;
                        case DOMAIN_GROUP_RID_CONTROLLERS:
                            ac = Domain_Controllers;
                            break;
                        case DOMAIN_GROUP_RID_CERT_ADMINS:
                            ac = Cert_Publishers;
                            break;
                        case DOMAIN_GROUP_RID_SCHEMA_ADMINS:
                            ac = Schema_Admins;
                            break;
                        case DOMAIN_GROUP_RID_ENTERPRISE_ADMINS:
                            ac = Enterprise_Admins;
                            break;
                        case DOMAIN_GROUP_RID_POLICY_ADMINS:
                            ac = Group_Policy_Creator_Owners;
                            break;
                        case DOMAIN_ALIAS_RID_RAS_SERVERS:
                            ac = RAS_and_IAS_Servers;
2199 2200 2201 2202 2203 2204 2205 2206 2207 2208
                            break;
                        case 1000:	/* first user account */
                            size = UNLEN + 1;
                            account_name = HeapAlloc(
                                GetProcessHeap(), 0, size * sizeof(WCHAR));
                            if (GetUserNameW(account_name, &size))
                                ac = account_name;
                            else
                                dm = NULL;

2209 2210 2211 2212 2213 2214
                            break;
                        default:
                            dm = NULL;
                            break;
                        }
                    }
2215 2216 2217 2218 2219 2220
                }
            }
        }
    }

    if (dm) {
2221 2222
        DWORD ac_len = lstrlenW(ac);
        DWORD dm_len = lstrlenW(dm);
2223
        BOOL status = TRUE;
2224 2225

        if (*accountSize > ac_len) {
2226 2227 2228
            if (account)
                lstrcpyW(account, ac);
        }
2229
        if (*domainSize > dm_len) {
2230 2231 2232
            if (domain)
                lstrcpyW(domain, dm);
        }
2233 2234 2235 2236 2237
        if ((*accountSize && *accountSize < ac_len) ||
            (!account && !*accountSize && ac_len)   ||
            (*domainSize && *domainSize < dm_len)   ||
            (!domain && !*domainSize && dm_len))
        {
2238
            SetLastError(ERROR_INSUFFICIENT_BUFFER);
2239 2240
            status = FALSE;
        }
2241
        if (*domainSize)
2242
            *domainSize = dm_len;
2243
        else
2244
            *domainSize = dm_len + 1;
2245
        if (*accountSize)
2246
            *accountSize = ac_len;
2247
        else
2248
            *accountSize = ac_len + 1;
2249

2250
        HeapFree(GetProcessHeap(), 0, account_name);
2251
        HeapFree(GetProcessHeap(), 0, computer_name);
2252
        if (status) *name_use = use;
2253
        return status;
2254 2255
    }

2256
    HeapFree(GetProcessHeap(), 0, account_name);
2257 2258 2259
    HeapFree(GetProcessHeap(), 0, computer_name);
    SetLastError(ERROR_NONE_MAPPED);
    return FALSE;
Alexandre Julliard's avatar
Alexandre Julliard committed
2260 2261
}

2262
/******************************************************************************
2263
 * SetFileSecurityA [ADVAPI32.@]
2264 2265
 *
 * See SetFileSecurityW.
2266
 */
2267
BOOL WINAPI SetFileSecurityA( LPCSTR lpFileName,
2268
                                SECURITY_INFORMATION RequestedInformation,
2269
                                PSECURITY_DESCRIPTOR pSecurityDescriptor)
2270
{
2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282
    DWORD len;
    BOOL r;
    LPWSTR name = NULL;

    if( lpFileName )
    {
        len = MultiByteToWideChar( CP_ACP, 0, lpFileName, -1, NULL, 0 );
        name = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
        MultiByteToWideChar( CP_ACP, 0, lpFileName, -1, name, len );
    }

    r = SetFileSecurityW( name, RequestedInformation, pSecurityDescriptor );
2283
    HeapFree( GetProcessHeap(), 0, name );
2284 2285

    return r;
2286 2287 2288
}

/******************************************************************************
2289
 * SetFileSecurityW [ADVAPI32.@]
2290 2291
 *
 * Sets the security of a file or directory.
2292 2293 2294 2295 2296
 *
 * PARAMS
 *   lpFileName           []
 *   RequestedInformation []
 *   pSecurityDescriptor  []
2297 2298 2299 2300
 *
 * RETURNS
 *  Success: TRUE.
 *  Failure: FALSE.
2301
 */
2302
BOOL WINAPI
2303
SetFileSecurityW( LPCWSTR lpFileName,
2304
                    SECURITY_INFORMATION RequestedInformation,
2305
                    PSECURITY_DESCRIPTOR pSecurityDescriptor )
2306
{
2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329
    HANDLE file;
    DWORD access = 0;
    NTSTATUS status;

    TRACE("(%s, 0x%x, %p)\n", debugstr_w(lpFileName), RequestedInformation,
          pSecurityDescriptor );

    if (RequestedInformation & OWNER_SECURITY_INFORMATION ||
        RequestedInformation & GROUP_SECURITY_INFORMATION)
        access |= WRITE_OWNER;
    if (RequestedInformation & SACL_SECURITY_INFORMATION)
        access |= ACCESS_SYSTEM_SECURITY;
    if (RequestedInformation & DACL_SECURITY_INFORMATION)
        access |= WRITE_DAC;

    file = CreateFileW( lpFileName, access, FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
                        NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL );
    if (file == INVALID_HANDLE_VALUE)
        return FALSE;

    status = NtSetSecurityObject( file, RequestedInformation, pSecurityDescriptor );
    CloseHandle( file );
    return set_ntstatus( status );
2330
}
2331

2332
/******************************************************************************
2333
 * QueryWindows31FilesMigration [ADVAPI32.@]
2334 2335 2336
 *
 * PARAMS
 *   x1 []
2337
 */
2338
BOOL WINAPI
2339 2340
QueryWindows31FilesMigration( DWORD x1 )
{
2341
	FIXME("(%d):stub\n",x1);
2342 2343 2344 2345
	return TRUE;
}

/******************************************************************************
2346
 * SynchronizeWindows31FilesAndWindowsNTRegistry [ADVAPI32.@]
2347 2348 2349 2350 2351 2352 2353
 *
 * PARAMS
 *   x1 []
 *   x2 []
 *   x3 []
 *   x4 []
 */
2354
BOOL WINAPI
2355 2356 2357
SynchronizeWindows31FilesAndWindowsNTRegistry( DWORD x1, DWORD x2, DWORD x3,
                                               DWORD x4 )
{
2358
	FIXME("(0x%08x,0x%08x,0x%08x,0x%08x):stub\n",x1,x2,x3,x4);
2359 2360 2361 2362
	return TRUE;
}

/******************************************************************************
2363
 * NotifyBootConfigStatus [ADVAPI32.@]
2364 2365 2366
 *
 * PARAMS
 *   x1 []
2367
 */
2368
BOOL WINAPI
2369
NotifyBootConfigStatus( BOOL x1 )
2370
{
2371
	FIXME("(0x%08d):stub\n",x1);
2372 2373
	return 1;
}
2374 2375

/******************************************************************************
2376
 * RevertToSelf [ADVAPI32.@]
Matthew Becker's avatar
Matthew Becker committed
2377
 *
2378 2379
 * Ends the impersonation of a user.
 *
Matthew Becker's avatar
Matthew Becker committed
2380 2381
 * PARAMS
 *   void []
2382 2383 2384 2385
 *
 * RETURNS
 *  Success: TRUE.
 *  Failure: FALSE.
2386
 */
2387
BOOL WINAPI
Matthew Becker's avatar
Matthew Becker committed
2388 2389
RevertToSelf( void )
{
2390 2391 2392
    HANDLE Token = NULL;
    return set_ntstatus( NtSetInformationThread( GetCurrentThread(),
        ThreadImpersonationToken, &Token, sizeof(Token) ) );
2393
}
2394 2395

/******************************************************************************
2396
 * ImpersonateSelf [ADVAPI32.@]
2397 2398 2399 2400 2401 2402 2403 2404 2405 2406
 *
 * Makes an impersonation token that represents the process user and assigns
 * to the current thread.
 *
 * PARAMS
 *  ImpersonationLevel [I] Level at which to impersonate.
 *
 * RETURNS
 *  Success: TRUE.
 *  Failure: FALSE.
2407
 */
2408
BOOL WINAPI
2409
ImpersonateSelf(SECURITY_IMPERSONATION_LEVEL ImpersonationLevel)
2410
{
2411
    return set_ntstatus( RtlImpersonateSelf( ImpersonationLevel ) );
2412 2413
}

2414 2415 2416 2417 2418
/******************************************************************************
 * ImpersonateLoggedOnUser [ADVAPI32.@]
 */
BOOL WINAPI ImpersonateLoggedOnUser(HANDLE hToken)
{
2419
    DWORD size;
2420 2421
    NTSTATUS Status;
    HANDLE ImpersonationToken;
2422
    TOKEN_TYPE Type;
2423
    static BOOL warn = TRUE;
2424

2425 2426 2427 2428 2429
    if (warn)
    {
        FIXME( "(%p)\n", hToken );
        warn = FALSE;
    }
2430 2431 2432
    if (!GetTokenInformation( hToken, TokenType, &Type,
                              sizeof(TOKEN_TYPE), &size ))
        return FALSE;
2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447

    if (Type == TokenPrimary)
    {
        OBJECT_ATTRIBUTES ObjectAttributes;

        InitializeObjectAttributes( &ObjectAttributes, NULL, 0, NULL, NULL );

        Status = NtDuplicateToken( hToken,
                                   TOKEN_IMPERSONATE | TOKEN_QUERY,
                                   &ObjectAttributes,
                                   SecurityImpersonation,
                                   TokenImpersonation,
                                   &ImpersonationToken );
        if (Status != STATUS_SUCCESS)
        {
2448
            ERR( "NtDuplicateToken failed with error 0x%08x\n", Status );
2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465
            SetLastError( RtlNtStatusToDosError( Status ) );
            return FALSE;
        }
    }
    else
        ImpersonationToken = hToken;

    Status = NtSetInformationThread( GetCurrentThread(),
                                     ThreadImpersonationToken,
                                     &ImpersonationToken,
                                     sizeof(ImpersonationToken) );

    if (Type == TokenPrimary)
        NtClose( ImpersonationToken );

    if (Status != STATUS_SUCCESS)
    {
2466
        ERR( "NtSetInformationThread failed with error 0x%08x\n", Status );
2467 2468 2469 2470 2471
        SetLastError( RtlNtStatusToDosError( Status ) );
        return FALSE;
    }

    return TRUE;
2472 2473
}

2474
/******************************************************************************
2475
 * AccessCheck [ADVAPI32.@]
2476
 */
2477
BOOL WINAPI
2478 2479 2480 2481 2482 2483 2484 2485 2486 2487
AccessCheck(
	PSECURITY_DESCRIPTOR SecurityDescriptor,
	HANDLE ClientToken,
	DWORD DesiredAccess,
	PGENERIC_MAPPING GenericMapping,
	PPRIVILEGE_SET PrivilegeSet,
	LPDWORD PrivilegeSetLength,
	LPDWORD GrantedAccess,
	LPBOOL AccessStatus)
{
2488 2489 2490 2491 2492 2493
    NTSTATUS access_status;
    BOOL ret = set_ntstatus( NtAccessCheck(SecurityDescriptor, ClientToken, DesiredAccess,
                                           GenericMapping, PrivilegeSet, PrivilegeSetLength,
                                           GrantedAccess, &access_status) );
    if (ret) *AccessStatus = set_ntstatus( access_status );
    return ret;
2494
}
2495

2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519

/******************************************************************************
 * AccessCheckByType [ADVAPI32.@]
 */
BOOL WINAPI AccessCheckByType(
    PSECURITY_DESCRIPTOR pSecurityDescriptor, 
    PSID PrincipalSelfSid,
    HANDLE ClientToken, 
    DWORD DesiredAccess, 
    POBJECT_TYPE_LIST ObjectTypeList,
    DWORD ObjectTypeListLength,
    PGENERIC_MAPPING GenericMapping,
    PPRIVILEGE_SET PrivilegeSet,
    LPDWORD PrivilegeSetLength, 
    LPDWORD GrantedAccess,
    LPBOOL AccessStatus)
{
	FIXME("stub\n");

	*AccessStatus = TRUE;

	return !*AccessStatus;
}

2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532
/******************************************************************************
 * MapGenericMask [ADVAPI32.@]
 *
 * Maps generic access rights into specific access rights according to the
 * supplied mapping.
 *
 * PARAMS
 *  AccessMask     [I/O] Access rights.
 *  GenericMapping [I] The mapping between generic and specific rights.
 *
 * RETURNS
 *  Nothing.
 */
2533 2534
VOID WINAPI MapGenericMask( PDWORD AccessMask, PGENERIC_MAPPING GenericMapping )
{
2535
    RtlMapGenericMask( AccessMask, GenericMapping );
2536
}
2537

2538
/*************************************************************************
2539
 * SetKernelObjectSecurity [ADVAPI32.@]
2540
 */
2541 2542 2543 2544
BOOL WINAPI SetKernelObjectSecurity (
	IN HANDLE Handle,
	IN SECURITY_INFORMATION SecurityInformation,
	IN PSECURITY_DESCRIPTOR SecurityDescriptor )
2545
{
2546
    return set_ntstatus (NtSetSecurityObject (Handle, SecurityInformation, SecurityDescriptor));
2547 2548
}

2549 2550 2551 2552 2553

/******************************************************************************
 *  AddAuditAccessAce [ADVAPI32.@]
 */
BOOL WINAPI AddAuditAccessAce(
2554 2555 2556 2557 2558 2559 2560 2561 2562
    IN OUT PACL pAcl, 
    IN DWORD dwAceRevision, 
    IN DWORD dwAccessMask, 
    IN PSID pSid, 
    IN BOOL bAuditSuccess, 
    IN BOOL bAuditFailure) 
{
    return set_ntstatus( RtlAddAuditAccessAce(pAcl, dwAceRevision, dwAccessMask, pSid, 
                                              bAuditSuccess, bAuditFailure) ); 
2563 2564
}

2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580
/******************************************************************************
 *  AddAuditAccessAce [ADVAPI32.@]
 */
BOOL WINAPI AddAuditAccessAceEx(
    IN OUT PACL pAcl,
    IN DWORD dwAceRevision,
    IN DWORD dwAceFlags,
    IN DWORD dwAccessMask,
    IN PSID pSid,
    IN BOOL bAuditSuccess,
    IN BOOL bAuditFailure)
{
    return set_ntstatus( RtlAddAuditAccessAceEx(pAcl, dwAceRevision, dwAceFlags, dwAccessMask, pSid,
                                              bAuditSuccess, bAuditFailure) );
}

2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592
/******************************************************************************
 * LookupAccountNameA [ADVAPI32.@]
 */
BOOL WINAPI
LookupAccountNameA(
	IN LPCSTR system,
	IN LPCSTR account,
	OUT PSID sid,
	OUT LPDWORD cbSid,
	LPSTR ReferencedDomainName,
	IN OUT LPDWORD cbReferencedDomainName,
	OUT PSID_NAME_USE name_use )
2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609
{
    BOOL ret;
    UNICODE_STRING lpSystemW;
    UNICODE_STRING lpAccountW;
    LPWSTR lpReferencedDomainNameW = NULL;

    RtlCreateUnicodeStringFromAsciiz(&lpSystemW, system);
    RtlCreateUnicodeStringFromAsciiz(&lpAccountW, account);

    if (ReferencedDomainName)
        lpReferencedDomainNameW = HeapAlloc(GetProcessHeap(), 0, *cbReferencedDomainName * sizeof(WCHAR));

    ret = LookupAccountNameW(lpSystemW.Buffer, lpAccountW.Buffer, sid, cbSid, lpReferencedDomainNameW,
        cbReferencedDomainName, name_use);

    if (ret && lpReferencedDomainNameW)
    {
2610 2611
        WideCharToMultiByte(CP_ACP, 0, lpReferencedDomainNameW, -1,
            ReferencedDomainName, *cbReferencedDomainName+1, NULL, NULL);
2612 2613 2614 2615
    }

    RtlFreeUnicodeString(&lpSystemW);
    RtlFreeUnicodeString(&lpAccountW);
2616
    HeapFree(GetProcessHeap(), 0, lpReferencedDomainNameW);
2617 2618 2619 2620

    return ret;
}

2621 2622 2623 2624 2625 2626
/******************************************************************************
 * lookup_user_account_name
 */
static BOOL lookup_user_account_name(PSID Sid, PDWORD cbSid, LPWSTR ReferencedDomainName,
                                     LPDWORD cchReferencedDomainName, PSID_NAME_USE peUse )
{
2627 2628 2629
    char buffer[sizeof(TOKEN_USER) + sizeof(SID) + sizeof(DWORD)*SID_MAX_SUB_AUTHORITIES];
    DWORD len = sizeof(buffer);
    HANDLE token;
2630 2631
    BOOL ret;
    PSID pSid;
2632
    WCHAR domainName[MAX_COMPUTERNAME_LENGTH + 1];
2633 2634
    DWORD nameLen;

2635
    if (!OpenThreadToken(GetCurrentThread(), TOKEN_READ, TRUE, &token))
2636
    {
2637 2638
        if (GetLastError() != ERROR_NO_TOKEN) return FALSE;
        if (!OpenProcessToken(GetCurrentProcess(), TOKEN_READ, &token)) return FALSE;
2639 2640
    }

2641 2642 2643 2644 2645 2646 2647
    ret = GetTokenInformation(token, TokenUser, buffer, len, &len);
    CloseHandle( token );

    if (!ret) return FALSE;

    pSid = ((TOKEN_USER *)buffer)->User.Sid;

2648 2649 2650 2651 2652 2653 2654 2655 2656
    if (Sid != NULL && (*cbSid >= GetLengthSid(pSid)))
       CopySid(*cbSid, Sid, pSid);
    if (*cbSid < GetLengthSid(pSid))
    {
       SetLastError(ERROR_INSUFFICIENT_BUFFER);
       ret = FALSE;
    }
    *cbSid = GetLengthSid(pSid);

2657 2658 2659 2660 2661 2662
    nameLen = MAX_COMPUTERNAME_LENGTH + 1;
    if (!GetComputerNameW(domainName, &nameLen))
    {
        domainName[0] = 0;
        nameLen = 0;
    }
2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687
    if (*cchReferencedDomainName <= nameLen || !ret)
    {
        SetLastError(ERROR_INSUFFICIENT_BUFFER);
        nameLen += 1;
        ret = FALSE;
    }
    else if (ReferencedDomainName)
        strcpyW(ReferencedDomainName, domainName);

    *cchReferencedDomainName = nameLen;

    if (ret)
        *peUse = SidTypeUser;

    return ret;
}

/******************************************************************************
 * lookup_computer_account_name
 */
static BOOL lookup_computer_account_name(PSID Sid, PDWORD cbSid, LPWSTR ReferencedDomainName,
                                         LPDWORD cchReferencedDomainName, PSID_NAME_USE peUse )
{
    MAX_SID local;
    BOOL ret;
2688
    WCHAR domainName[MAX_COMPUTERNAME_LENGTH + 1];
2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702
    DWORD nameLen;

    if ((ret = ADVAPI_GetComputerSid(&local)))
    {
        if (Sid != NULL && (*cbSid >= GetLengthSid(&local)))
           CopySid(*cbSid, Sid, &local);
        if (*cbSid < GetLengthSid(&local))
        {
           SetLastError(ERROR_INSUFFICIENT_BUFFER);
           ret = FALSE;
        }
        *cbSid = GetLengthSid(&local);
    }

2703 2704 2705 2706 2707 2708
    nameLen = MAX_COMPUTERNAME_LENGTH + 1;
    if (!GetComputerNameW(domainName, &nameLen))
    {
        domainName[0] = 0;
        nameLen = 0;
    }
2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725
    if (*cchReferencedDomainName <= nameLen || !ret)
    {
        SetLastError(ERROR_INSUFFICIENT_BUFFER);
        nameLen += 1;
        ret = FALSE;
    }
    else if (ReferencedDomainName)
        strcpyW(ReferencedDomainName, domainName);

    *cchReferencedDomainName = nameLen;

    if (ret)
        *peUse = SidTypeDomain;

    return ret;
}

2726 2727
static void split_domain_account( const LSA_UNICODE_STRING *str, LSA_UNICODE_STRING *account,
                                  LSA_UNICODE_STRING *domain )
2728
{
2729
    WCHAR *p = str->Buffer + str->Length / sizeof(WCHAR) - 1;
2730

2731
    while (p > str->Buffer && *p != '\\') p--;
2732

2733
    if (*p == '\\')
2734
    {
2735 2736
        domain->Buffer = str->Buffer;
        domain->Length = (p - str->Buffer) * sizeof(WCHAR);
2737

2738 2739 2740 2741
        account->Buffer = p + 1;
        account->Length = str->Length - ((p - str->Buffer + 1) * sizeof(WCHAR));
    }
    else
2742
    {
2743 2744 2745 2746 2747
        domain->Buffer = NULL;
        domain->Length = 0;

        account->Buffer = str->Buffer;
        account->Length = str->Length;
2748
    }
2749
}
2750

2751
static BOOL match_domain( ULONG idx, const LSA_UNICODE_STRING *domain )
2752 2753 2754 2755 2756 2757 2758 2759 2760
{
    ULONG len = strlenW( ACCOUNT_SIDS[idx].domain );

    if (len == domain->Length / sizeof(WCHAR) && !strncmpiW( domain->Buffer, ACCOUNT_SIDS[idx].domain, len ))
        return TRUE;

    return FALSE;
}

2761
static BOOL match_account( ULONG idx, const LSA_UNICODE_STRING *account )
2762 2763 2764 2765 2766 2767 2768
{
    ULONG len = strlenW( ACCOUNT_SIDS[idx].account );

    if (len == account->Length / sizeof(WCHAR) && !strncmpiW( account->Buffer, ACCOUNT_SIDS[idx].account, len ))
        return TRUE;

    if (ACCOUNT_SIDS[idx].alias)
2769
    {
2770 2771 2772
        len = strlenW( ACCOUNT_SIDS[idx].alias );
        if (len == account->Length / sizeof(WCHAR) && !strncmpiW( account->Buffer, ACCOUNT_SIDS[idx].alias, len ))
            return TRUE;
2773
    }
2774 2775
    return FALSE;
}
2776

2777 2778 2779
/*
 * Helper function for LookupAccountNameW
 */
2780
BOOL lookup_local_wellknown_name( const LSA_UNICODE_STRING *account_and_domain,
2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794
                                  PSID Sid, LPDWORD cbSid,
                                  LPWSTR ReferencedDomainName,
                                  LPDWORD cchReferencedDomainName,
                                  PSID_NAME_USE peUse, BOOL *handled )
{
    PSID pSid;
    LSA_UNICODE_STRING account, domain;
    BOOL ret = TRUE;
    ULONG i;

    *handled = FALSE;
    split_domain_account( account_and_domain, &account, &domain );

    for (i = 0; i < sizeof(ACCOUNT_SIDS) / sizeof(ACCOUNT_SIDS[0]); i++)
2795
    {
2796
        /* check domain first */
2797
        if (domain.Buffer && !match_domain( i, &domain )) continue;
2798

2799
        if (match_account( i, &account ))
2800
        {
2801
            DWORD len, sidLen = SECURITY_MAX_SID_SIZE;
2802

2803
            if (!(pSid = HeapAlloc( GetProcessHeap(), 0, sidLen ))) return FALSE;
2804

2805
            if ((ret = CreateWellKnownSid( ACCOUNT_SIDS[i].type, NULL, pSid, &sidLen )))
2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817
            {
                if (*cbSid < sidLen)
                {
                    SetLastError(ERROR_INSUFFICIENT_BUFFER);
                    ret = FALSE;
                }
                else if (Sid)
                {
                    CopySid(*cbSid, Sid, pSid);
                }
                *cbSid = sidLen;
            }
2818

2819 2820
            len = strlenW( ACCOUNT_SIDS[i].domain );
            if (*cchReferencedDomainName <= len || !ret)
2821 2822
            {
                SetLastError(ERROR_INSUFFICIENT_BUFFER);
2823
                len++;
2824 2825
                ret = FALSE;
            }
2826
            else if (ReferencedDomainName)
2827
            {
2828
                strcpyW( ReferencedDomainName, ACCOUNT_SIDS[i].domain );
2829 2830
            }

2831
            *cchReferencedDomainName = len;
2832 2833 2834
            if (ret)
                *peUse = ACCOUNT_SIDS[i].name_use;

2835
            HeapFree(GetProcessHeap(), 0, pSid);
2836
            *handled = TRUE;
2837
            return ret;
2838 2839
        }
    }
2840 2841 2842
    return ret;
}

2843
BOOL lookup_local_user_name( const LSA_UNICODE_STRING *account_and_domain,
2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855
                             PSID Sid, LPDWORD cbSid,
                             LPWSTR ReferencedDomainName,
                             LPDWORD cchReferencedDomainName,
                             PSID_NAME_USE peUse, BOOL *handled )
{
    DWORD nameLen;
    LPWSTR userName = NULL;
    LSA_UNICODE_STRING account, domain;
    BOOL ret = TRUE;

    *handled = FALSE;
    split_domain_account( account_and_domain, &account, &domain );
2856

2857 2858 2859
    /* Let the current Unix user id masquerade as first Windows user account */

    nameLen = UNLEN + 1;
2860
    if (!(userName = HeapAlloc( GetProcessHeap(), 0, nameLen * sizeof(WCHAR) ))) return FALSE;
2861

2862
    if (domain.Buffer)
2863 2864
    {
        /* check to make sure this account is on this computer */
2865 2866
        if (GetComputerNameW( userName, &nameLen ) &&
            (domain.Length / sizeof(WCHAR) != nameLen || strncmpW( domain.Buffer, userName, nameLen )))
2867 2868 2869 2870
        {
            SetLastError(ERROR_NONE_MAPPED);
            ret = FALSE;
        }
2871
        nameLen = UNLEN + 1;
2872 2873
    }

2874 2875 2876 2877 2878 2879
    if (GetUserNameW( userName, &nameLen ) &&
        account.Length / sizeof(WCHAR) == nameLen - 1 && !strncmpW( account.Buffer, userName, nameLen - 1 ))
    {
            ret = lookup_user_account_name( Sid, cbSid, ReferencedDomainName, cchReferencedDomainName, peUse );
            *handled = TRUE;
    }
2880
    else
2881
    {
2882
        nameLen = UNLEN + 1;
2883 2884
        if (GetComputerNameW( userName, &nameLen ) &&
            account.Length / sizeof(WCHAR) == nameLen && !strncmpW( account.Buffer, userName , nameLen ))
2885
        {
2886 2887
            ret = lookup_computer_account_name( Sid, cbSid, ReferencedDomainName, cchReferencedDomainName, peUse );
            *handled = TRUE;
2888
        }
2889 2890 2891
    }

    HeapFree(GetProcessHeap(), 0, userName);
2892
    return ret;
2893
}
2894

2895 2896 2897 2898 2899 2900 2901 2902 2903 2904
/******************************************************************************
 * LookupAccountNameW [ADVAPI32.@]
 */
BOOL WINAPI LookupAccountNameW( LPCWSTR lpSystemName, LPCWSTR lpAccountName, PSID Sid,
                                LPDWORD cbSid, LPWSTR ReferencedDomainName,
                                LPDWORD cchReferencedDomainName, PSID_NAME_USE peUse )
{
    BOOL ret, handled;
    LSA_UNICODE_STRING account;

2905
    TRACE("%s %s %p %p %p %p %p\n", debugstr_w(lpSystemName), debugstr_w(lpAccountName),
2906 2907 2908 2909
          Sid, cbSid, ReferencedDomainName, cchReferencedDomainName, peUse);

    if (!ADVAPI_IsLocalComputer( lpSystemName ))
    {
2910
        FIXME("remote computer not supported\n");
2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937
        SetLastError( RPC_S_SERVER_UNAVAILABLE );
        return FALSE;
    }

    if (!lpAccountName || !strcmpW( lpAccountName, Blank ))
    {
        lpAccountName = BUILTIN;
    }

    RtlInitUnicodeString( &account, lpAccountName );

    /* Check well known SIDs first */
    ret = lookup_local_wellknown_name( &account, Sid, cbSid, ReferencedDomainName,
                                       cchReferencedDomainName, peUse, &handled );
    if (handled)
        return ret;

    /* Check user names */
    ret = lookup_local_user_name( &account, Sid, cbSid, ReferencedDomainName,
                                  cchReferencedDomainName, peUse, &handled);
    if (handled)
        return ret;

    SetLastError( ERROR_NONE_MAPPED );
    return FALSE;
}

2938 2939 2940 2941 2942
/******************************************************************************
 * PrivilegeCheck [ADVAPI32.@]
 */
BOOL WINAPI PrivilegeCheck( HANDLE ClientToken, PPRIVILEGE_SET RequiredPrivileges, LPBOOL pfResult)
{
2943 2944 2945 2946 2947 2948 2949 2950 2951
    BOOL ret;
    BOOLEAN Result;

    TRACE("%p %p %p\n", ClientToken, RequiredPrivileges, pfResult);

    ret = set_ntstatus (NtPrivilegeCheck (ClientToken, RequiredPrivileges, &Result));
    if (ret)
        *pfResult = Result;
    return ret;
2952
}
2953

2954 2955 2956 2957 2958 2959 2960 2961
/******************************************************************************
 * AccessCheckAndAuditAlarmA [ADVAPI32.@]
 */
BOOL WINAPI AccessCheckAndAuditAlarmA(LPCSTR Subsystem, LPVOID HandleId, LPSTR ObjectTypeName,
  LPSTR ObjectName, PSECURITY_DESCRIPTOR SecurityDescriptor, DWORD DesiredAccess,
  PGENERIC_MAPPING GenericMapping, BOOL ObjectCreation, LPDWORD GrantedAccess,
  LPBOOL AccessStatus, LPBOOL pfGenerateOnClose)
{
2962
	FIXME("stub (%s,%p,%s,%s,%p,%08x,%p,%x,%p,%p,%p)\n", debugstr_a(Subsystem),
2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976
		HandleId, debugstr_a(ObjectTypeName), debugstr_a(ObjectName),
		SecurityDescriptor, DesiredAccess, GenericMapping,
		ObjectCreation, GrantedAccess, AccessStatus, pfGenerateOnClose);
	return TRUE;
}

/******************************************************************************
 * AccessCheckAndAuditAlarmW [ADVAPI32.@]
 */
BOOL WINAPI AccessCheckAndAuditAlarmW(LPCWSTR Subsystem, LPVOID HandleId, LPWSTR ObjectTypeName,
  LPWSTR ObjectName, PSECURITY_DESCRIPTOR SecurityDescriptor, DWORD DesiredAccess,
  PGENERIC_MAPPING GenericMapping, BOOL ObjectCreation, LPDWORD GrantedAccess,
  LPBOOL AccessStatus, LPBOOL pfGenerateOnClose)
{
2977
	FIXME("stub (%s,%p,%s,%s,%p,%08x,%p,%x,%p,%p,%p)\n", debugstr_w(Subsystem),
2978 2979 2980 2981 2982 2983
		HandleId, debugstr_w(ObjectTypeName), debugstr_w(ObjectName),
		SecurityDescriptor, DesiredAccess, GenericMapping,
		ObjectCreation, GrantedAccess, AccessStatus, pfGenerateOnClose);
	return TRUE;
}

2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997
BOOL WINAPI ObjectCloseAuditAlarmA(LPCSTR SubsystemName, LPVOID HandleId, BOOL GenerateOnClose)
{
    FIXME("stub (%s,%p,%x)\n", debugstr_a(SubsystemName), HandleId, GenerateOnClose);

    return TRUE;
}

BOOL WINAPI ObjectCloseAuditAlarmW(LPCWSTR SubsystemName, LPVOID HandleId, BOOL GenerateOnClose)
{
    FIXME("stub (%s,%p,%x)\n", debugstr_w(SubsystemName), HandleId, GenerateOnClose);

    return TRUE;
}

2998 2999 3000 3001 3002 3003 3004
BOOL WINAPI ObjectDeleteAuditAlarmW(LPCWSTR SubsystemName, LPVOID HandleId, BOOL GenerateOnClose)
{
    FIXME("stub (%s,%p,%x)\n", debugstr_w(SubsystemName), HandleId, GenerateOnClose);

    return TRUE;
}

3005 3006 3007 3008 3009
BOOL WINAPI ObjectOpenAuditAlarmA(LPCSTR SubsystemName, LPVOID HandleId, LPSTR ObjectTypeName,
  LPSTR ObjectName, PSECURITY_DESCRIPTOR pSecurityDescriptor, HANDLE ClientToken, DWORD DesiredAccess,
  DWORD GrantedAccess, PPRIVILEGE_SET Privileges, BOOL ObjectCreation, BOOL AccessGranted,
  LPBOOL GenerateOnClose)
{
3010
	FIXME("stub (%s,%p,%s,%s,%p,%p,0x%08x,0x%08x,%p,%x,%x,%p)\n", debugstr_a(SubsystemName),
3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022
		HandleId, debugstr_a(ObjectTypeName), debugstr_a(ObjectName), pSecurityDescriptor,
        ClientToken, DesiredAccess, GrantedAccess, Privileges, ObjectCreation, AccessGranted,
        GenerateOnClose);

    return TRUE;
}

BOOL WINAPI ObjectOpenAuditAlarmW(LPCWSTR SubsystemName, LPVOID HandleId, LPWSTR ObjectTypeName,
  LPWSTR ObjectName, PSECURITY_DESCRIPTOR pSecurityDescriptor, HANDLE ClientToken, DWORD DesiredAccess,
  DWORD GrantedAccess, PPRIVILEGE_SET Privileges, BOOL ObjectCreation, BOOL AccessGranted,
  LPBOOL GenerateOnClose)
{
3023
    FIXME("stub (%s,%p,%s,%s,%p,%p,0x%08x,0x%08x,%p,%x,%x,%p)\n", debugstr_w(SubsystemName),
3024 3025 3026 3027 3028 3029 3030 3031 3032 3033
        HandleId, debugstr_w(ObjectTypeName), debugstr_w(ObjectName), pSecurityDescriptor,
        ClientToken, DesiredAccess, GrantedAccess, Privileges, ObjectCreation, AccessGranted,
        GenerateOnClose);

    return TRUE;
}

BOOL WINAPI ObjectPrivilegeAuditAlarmA( LPCSTR SubsystemName, LPVOID HandleId, HANDLE ClientToken,
  DWORD DesiredAccess, PPRIVILEGE_SET Privileges, BOOL AccessGranted)
{
3034
    FIXME("stub (%s,%p,%p,0x%08x,%p,%x)\n", debugstr_a(SubsystemName), HandleId, ClientToken,
3035 3036 3037 3038 3039 3040 3041 3042
          DesiredAccess, Privileges, AccessGranted);

    return TRUE;
}

BOOL WINAPI ObjectPrivilegeAuditAlarmW( LPCWSTR SubsystemName, LPVOID HandleId, HANDLE ClientToken,
  DWORD DesiredAccess, PPRIVILEGE_SET Privileges, BOOL AccessGranted)
{
3043
    FIXME("stub (%s,%p,%p,0x%08x,%p,%x)\n", debugstr_w(SubsystemName), HandleId, ClientToken,
3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065
          DesiredAccess, Privileges, AccessGranted);

    return TRUE;
}

BOOL WINAPI PrivilegedServiceAuditAlarmA( LPCSTR SubsystemName, LPCSTR ServiceName, HANDLE ClientToken,
                                   PPRIVILEGE_SET Privileges, BOOL AccessGranted)
{
    FIXME("stub (%s,%s,%p,%p,%x)\n", debugstr_a(SubsystemName), debugstr_a(ServiceName),
          ClientToken, Privileges, AccessGranted);

    return TRUE;
}

BOOL WINAPI PrivilegedServiceAuditAlarmW( LPCWSTR SubsystemName, LPCWSTR ServiceName, HANDLE ClientToken,
                                   PPRIVILEGE_SET Privileges, BOOL AccessGranted)
{
    FIXME("stub %s,%s,%p,%p,%x)\n", debugstr_w(SubsystemName), debugstr_w(ServiceName),
          ClientToken, Privileges, AccessGranted);

    return TRUE;
}
3066

3067 3068
/******************************************************************************
 * GetSecurityInfo [ADVAPI32.@]
3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084
 *
 * Retrieves a copy of the security descriptor associated with an object.
 *
 * PARAMS
 *  hObject              [I] A handle for the object.
 *  ObjectType           [I] The type of object.
 *  SecurityInfo         [I] A bitmask indicating what info to retrieve.
 *  ppsidOwner           [O] If non-null, receives a pointer to the owner SID.
 *  ppsidGroup           [O] If non-null, receives a pointer to the group SID.
 *  ppDacl               [O] If non-null, receives a pointer to the DACL.
 *  ppSacl               [O] If non-null, receives a pointer to the SACL.
 *  ppSecurityDescriptor [O] Receives a pointer to the security descriptor,
 *                           which must be freed with LocalFree.
 *
 * RETURNS
 *  ERROR_SUCCESS if all's well, and a WIN32 error code otherwise.
3085 3086 3087 3088 3089 3090 3091 3092
 */
DWORD WINAPI GetSecurityInfo(
    HANDLE hObject, SE_OBJECT_TYPE ObjectType,
    SECURITY_INFORMATION SecurityInfo, PSID *ppsidOwner,
    PSID *ppsidGroup, PACL *ppDacl, PACL *ppSacl,
    PSECURITY_DESCRIPTOR *ppSecurityDescriptor
)
{
3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134
    PSECURITY_DESCRIPTOR sd;
    NTSTATUS status;
    ULONG n1, n2;
    BOOL present, defaulted;

    status = NtQuerySecurityObject(hObject, SecurityInfo, NULL, 0, &n1);
    if (status != STATUS_BUFFER_TOO_SMALL && status != STATUS_SUCCESS)
        return RtlNtStatusToDosError(status);

    sd = LocalAlloc(0, n1);
    if (!sd)
        return ERROR_NOT_ENOUGH_MEMORY;

    status = NtQuerySecurityObject(hObject, SecurityInfo, sd, n1, &n2);
    if (status != STATUS_SUCCESS)
    {
        LocalFree(sd);
        return RtlNtStatusToDosError(status);
    }

    if (ppsidOwner)
    {
        *ppsidOwner = NULL;
        GetSecurityDescriptorOwner(sd, ppsidOwner, &defaulted);
    }
    if (ppsidGroup)
    {
        *ppsidGroup = NULL;
        GetSecurityDescriptorGroup(sd, ppsidGroup, &defaulted);
    }
    if (ppDacl)
    {
        *ppDacl = NULL;
        GetSecurityDescriptorDacl(sd, &present, ppDacl, &defaulted);
    }
    if (ppSacl)
    {
        *ppSacl = NULL;
        GetSecurityDescriptorSacl(sd, &present, ppSacl, &defaulted);
    }
    if (ppSecurityDescriptor)
        *ppSecurityDescriptor = sd;
3135 3136 3137 3138 3139

    /* The security descriptor (sd) cannot be freed if ppSecurityDescriptor is
     * NULL, because native happily returns the SIDs and ACLs that are requested
     * in this case.
     */
3140 3141

    return ERROR_SUCCESS;
3142 3143
}

3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157
/******************************************************************************
 * GetSecurityInfoExA [ADVAPI32.@]
 */
DWORD WINAPI GetSecurityInfoExA(
	HANDLE hObject, SE_OBJECT_TYPE ObjectType,
	SECURITY_INFORMATION SecurityInfo, LPCSTR lpProvider,
	LPCSTR lpProperty, PACTRL_ACCESSA *ppAccessList,
	PACTRL_AUDITA *ppAuditList, LPSTR *lppOwner, LPSTR *lppGroup
)
{
  FIXME("stub!\n");
  return ERROR_BAD_PROVIDER;
}

3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170
/******************************************************************************
 * GetSecurityInfoExW [ADVAPI32.@]
 */
DWORD WINAPI GetSecurityInfoExW(
	HANDLE hObject, SE_OBJECT_TYPE ObjectType, 
	SECURITY_INFORMATION SecurityInfo, LPCWSTR lpProvider,
	LPCWSTR lpProperty, PACTRL_ACCESSW *ppAccessList, 
	PACTRL_AUDITW *ppAuditList, LPWSTR *lppOwner, LPWSTR *lppGroup
)
{
  FIXME("stub!\n");
  return ERROR_BAD_PROVIDER; 
}
3171

3172 3173 3174 3175 3176 3177 3178
/******************************************************************************
 * BuildExplicitAccessWithNameA [ADVAPI32.@]
 */
VOID WINAPI BuildExplicitAccessWithNameA( PEXPLICIT_ACCESSA pExplicitAccess,
                                          LPSTR pTrusteeName, DWORD AccessPermissions,
                                          ACCESS_MODE AccessMode, DWORD Inheritance )
{
3179
    TRACE("%p %s 0x%08x 0x%08x 0x%08x\n", pExplicitAccess, debugstr_a(pTrusteeName),
3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199
          AccessPermissions, AccessMode, Inheritance);

    pExplicitAccess->grfAccessPermissions = AccessPermissions;
    pExplicitAccess->grfAccessMode = AccessMode;
    pExplicitAccess->grfInheritance = Inheritance;

    pExplicitAccess->Trustee.pMultipleTrustee = NULL;
    pExplicitAccess->Trustee.MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE;
    pExplicitAccess->Trustee.TrusteeForm = TRUSTEE_IS_NAME;
    pExplicitAccess->Trustee.TrusteeType = TRUSTEE_IS_UNKNOWN;
    pExplicitAccess->Trustee.ptstrName = pTrusteeName;
}

/******************************************************************************
 * BuildExplicitAccessWithNameW [ADVAPI32.@]
 */
VOID WINAPI BuildExplicitAccessWithNameW( PEXPLICIT_ACCESSW pExplicitAccess,
                                          LPWSTR pTrusteeName, DWORD AccessPermissions,
                                          ACCESS_MODE AccessMode, DWORD Inheritance )
{
3200
    TRACE("%p %s 0x%08x 0x%08x 0x%08x\n", pExplicitAccess, debugstr_w(pTrusteeName),
3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220
          AccessPermissions, AccessMode, Inheritance);

    pExplicitAccess->grfAccessPermissions = AccessPermissions;
    pExplicitAccess->grfAccessMode = AccessMode;
    pExplicitAccess->grfInheritance = Inheritance;

    pExplicitAccess->Trustee.pMultipleTrustee = NULL;
    pExplicitAccess->Trustee.MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE;
    pExplicitAccess->Trustee.TrusteeForm = TRUSTEE_IS_NAME;
    pExplicitAccess->Trustee.TrusteeType = TRUSTEE_IS_UNKNOWN;
    pExplicitAccess->Trustee.ptstrName = pTrusteeName;
}

/******************************************************************************
 * BuildTrusteeWithObjectsAndNameA [ADVAPI32.@]
 */
VOID WINAPI BuildTrusteeWithObjectsAndNameA( PTRUSTEEA pTrustee, POBJECTS_AND_NAME_A pObjName,
                                             SE_OBJECT_TYPE ObjectType, LPSTR ObjectTypeName,
                                             LPSTR InheritedObjectTypeName, LPSTR Name )
{
3221 3222
    DWORD ObjectsPresent = 0;

3223 3224 3225
    TRACE("%p %p 0x%08x %p %p %s\n", pTrustee, pObjName,
          ObjectType, ObjectTypeName, InheritedObjectTypeName, debugstr_a(Name));

3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242
    /* Fill the OBJECTS_AND_NAME structure */
    pObjName->ObjectType = ObjectType;
    if (ObjectTypeName != NULL)
    {
        ObjectsPresent |= ACE_OBJECT_TYPE_PRESENT;
    }

    pObjName->InheritedObjectTypeName = InheritedObjectTypeName;
    if (InheritedObjectTypeName != NULL)
    {
        ObjectsPresent |= ACE_INHERITED_OBJECT_TYPE_PRESENT;
    }

    pObjName->ObjectsPresent = ObjectsPresent;
    pObjName->ptstrName = Name;

    /* Fill the TRUSTEE structure */
3243 3244 3245 3246
    pTrustee->pMultipleTrustee = NULL;
    pTrustee->MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE;
    pTrustee->TrusteeForm = TRUSTEE_IS_OBJECTS_AND_NAME;
    pTrustee->TrusteeType = TRUSTEE_IS_UNKNOWN;
3247
    pTrustee->ptstrName = (LPSTR)pObjName;
3248 3249 3250 3251 3252 3253 3254 3255 3256
}

/******************************************************************************
 * BuildTrusteeWithObjectsAndNameW [ADVAPI32.@]
 */
VOID WINAPI BuildTrusteeWithObjectsAndNameW( PTRUSTEEW pTrustee, POBJECTS_AND_NAME_W pObjName,
                                             SE_OBJECT_TYPE ObjectType, LPWSTR ObjectTypeName,
                                             LPWSTR InheritedObjectTypeName, LPWSTR Name )
{
3257 3258
    DWORD ObjectsPresent = 0;

3259 3260 3261
    TRACE("%p %p 0x%08x %p %p %s\n", pTrustee, pObjName,
          ObjectType, ObjectTypeName, InheritedObjectTypeName, debugstr_w(Name));

3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278
    /* Fill the OBJECTS_AND_NAME structure */
    pObjName->ObjectType = ObjectType;
    if (ObjectTypeName != NULL)
    {
        ObjectsPresent |= ACE_OBJECT_TYPE_PRESENT;
    }

    pObjName->InheritedObjectTypeName = InheritedObjectTypeName;
    if (InheritedObjectTypeName != NULL)
    {
        ObjectsPresent |= ACE_INHERITED_OBJECT_TYPE_PRESENT;
    }

    pObjName->ObjectsPresent = ObjectsPresent;
    pObjName->ptstrName = Name;

    /* Fill the TRUSTEE structure */
3279 3280 3281 3282
    pTrustee->pMultipleTrustee = NULL;
    pTrustee->MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE;
    pTrustee->TrusteeForm = TRUSTEE_IS_OBJECTS_AND_NAME;
    pTrustee->TrusteeType = TRUSTEE_IS_UNKNOWN;
3283
    pTrustee->ptstrName = (LPWSTR)pObjName;
3284 3285
}

3286 3287 3288
/******************************************************************************
 * BuildTrusteeWithObjectsAndSidA [ADVAPI32.@]
 */
3289 3290 3291
VOID WINAPI BuildTrusteeWithObjectsAndSidA( PTRUSTEEA pTrustee, POBJECTS_AND_SID pObjSid,
                                            GUID* pObjectGuid, GUID* pInheritedObjectGuid, PSID pSid )
{
3292 3293
    DWORD ObjectsPresent = 0;

3294 3295
    TRACE("%p %p %p %p %p\n", pTrustee, pObjSid, pObjectGuid, pInheritedObjectGuid, pSid);

3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322
    /* Fill the OBJECTS_AND_SID structure */
    if (pObjectGuid != NULL)
    {
        pObjSid->ObjectTypeGuid = *pObjectGuid;
        ObjectsPresent |= ACE_OBJECT_TYPE_PRESENT;
    }
    else
    {
        ZeroMemory(&pObjSid->ObjectTypeGuid,
                   sizeof(GUID));
    }

    if (pInheritedObjectGuid != NULL)
    {
        pObjSid->InheritedObjectTypeGuid = *pInheritedObjectGuid;
        ObjectsPresent |= ACE_INHERITED_OBJECT_TYPE_PRESENT;
    }
    else
    {
        ZeroMemory(&pObjSid->InheritedObjectTypeGuid,
                   sizeof(GUID));
    }

    pObjSid->ObjectsPresent = ObjectsPresent;
    pObjSid->pSid = pSid;

    /* Fill the TRUSTEE structure */
3323 3324 3325 3326
    pTrustee->pMultipleTrustee = NULL;
    pTrustee->MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE;
    pTrustee->TrusteeForm = TRUSTEE_IS_OBJECTS_AND_SID;
    pTrustee->TrusteeType = TRUSTEE_IS_UNKNOWN;
3327
    pTrustee->ptstrName = (LPSTR) pObjSid;
3328 3329
}

3330 3331 3332
/******************************************************************************
 * BuildTrusteeWithObjectsAndSidW [ADVAPI32.@]
 */
3333 3334 3335
VOID WINAPI BuildTrusteeWithObjectsAndSidW( PTRUSTEEW pTrustee, POBJECTS_AND_SID pObjSid,
                                            GUID* pObjectGuid, GUID* pInheritedObjectGuid, PSID pSid )
{
3336 3337
    DWORD ObjectsPresent = 0;

3338 3339
    TRACE("%p %p %p %p %p\n", pTrustee, pObjSid, pObjectGuid, pInheritedObjectGuid, pSid);

3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366
    /* Fill the OBJECTS_AND_SID structure */
    if (pObjectGuid != NULL)
    {
        pObjSid->ObjectTypeGuid = *pObjectGuid;
        ObjectsPresent |= ACE_OBJECT_TYPE_PRESENT;
    }
    else
    {
        ZeroMemory(&pObjSid->ObjectTypeGuid,
                   sizeof(GUID));
    }

    if (pInheritedObjectGuid != NULL)
    {
        pObjSid->InheritedObjectTypeGuid = *pInheritedObjectGuid;
        ObjectsPresent |= ACE_INHERITED_OBJECT_TYPE_PRESENT;
    }
    else
    {
        ZeroMemory(&pObjSid->InheritedObjectTypeGuid,
                   sizeof(GUID));
    }

    pObjSid->ObjectsPresent = ObjectsPresent;
    pObjSid->pSid = pSid;

    /* Fill the TRUSTEE structure */
3367 3368 3369 3370
    pTrustee->pMultipleTrustee = NULL;
    pTrustee->MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE;
    pTrustee->TrusteeForm = TRUSTEE_IS_OBJECTS_AND_SID;
    pTrustee->TrusteeType = TRUSTEE_IS_UNKNOWN;
3371
    pTrustee->ptstrName = (LPWSTR) pObjSid;
3372 3373
}

3374 3375 3376 3377 3378
/******************************************************************************
 * BuildTrusteeWithSidA [ADVAPI32.@]
 */
VOID WINAPI BuildTrusteeWithSidA(PTRUSTEEA pTrustee, PSID pSid)
{
3379 3380 3381 3382
    TRACE("%p %p\n", pTrustee, pSid);

    pTrustee->pMultipleTrustee = NULL;
    pTrustee->MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE;
3383
    pTrustee->TrusteeForm = TRUSTEE_IS_SID;
3384
    pTrustee->TrusteeType = TRUSTEE_IS_UNKNOWN;
3385
    pTrustee->ptstrName = pSid;
3386 3387 3388 3389 3390 3391 3392
}

/******************************************************************************
 * BuildTrusteeWithSidW [ADVAPI32.@]
 */
VOID WINAPI BuildTrusteeWithSidW(PTRUSTEEW pTrustee, PSID pSid)
{
3393 3394 3395 3396
    TRACE("%p %p\n", pTrustee, pSid);

    pTrustee->pMultipleTrustee = NULL;
    pTrustee->MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE;
3397
    pTrustee->TrusteeForm = TRUSTEE_IS_SID;
3398
    pTrustee->TrusteeType = TRUSTEE_IS_UNKNOWN;
3399
    pTrustee->ptstrName = pSid;
3400
}
3401

3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429
/******************************************************************************
 * BuildTrusteeWithNameA [ADVAPI32.@]
 */
VOID WINAPI BuildTrusteeWithNameA(PTRUSTEEA pTrustee, LPSTR name)
{
    TRACE("%p %s\n", pTrustee, debugstr_a(name) );

    pTrustee->pMultipleTrustee = NULL;
    pTrustee->MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE;
    pTrustee->TrusteeForm = TRUSTEE_IS_NAME;
    pTrustee->TrusteeType = TRUSTEE_IS_UNKNOWN;
    pTrustee->ptstrName = name;
}

/******************************************************************************
 * BuildTrusteeWithNameW [ADVAPI32.@]
 */
VOID WINAPI BuildTrusteeWithNameW(PTRUSTEEW pTrustee, LPWSTR name)
{
    TRACE("%p %s\n", pTrustee, debugstr_w(name) );

    pTrustee->pMultipleTrustee = NULL;
    pTrustee->MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE;
    pTrustee->TrusteeForm = TRUSTEE_IS_NAME;
    pTrustee->TrusteeType = TRUSTEE_IS_UNKNOWN;
    pTrustee->ptstrName = name;
}

3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507
/****************************************************************************** 
 * GetTrusteeFormA [ADVAPI32.@] 
 */ 
TRUSTEE_FORM WINAPI GetTrusteeFormA(PTRUSTEEA pTrustee) 
{  
    TRACE("(%p)\n", pTrustee); 
  
    if (!pTrustee) 
        return TRUSTEE_BAD_FORM; 
  
    return pTrustee->TrusteeForm; 
}  
  
/****************************************************************************** 
 * GetTrusteeFormW [ADVAPI32.@] 
 */ 
TRUSTEE_FORM WINAPI GetTrusteeFormW(PTRUSTEEW pTrustee) 
{  
    TRACE("(%p)\n", pTrustee); 
  
    if (!pTrustee) 
        return TRUSTEE_BAD_FORM; 
  
    return pTrustee->TrusteeForm; 
}  
  
/****************************************************************************** 
 * GetTrusteeNameA [ADVAPI32.@] 
 */ 
LPSTR WINAPI GetTrusteeNameA(PTRUSTEEA pTrustee) 
{  
    TRACE("(%p)\n", pTrustee); 
  
    if (!pTrustee) 
        return NULL; 
  
    return pTrustee->ptstrName; 
}  
  
/****************************************************************************** 
 * GetTrusteeNameW [ADVAPI32.@] 
 */ 
LPWSTR WINAPI GetTrusteeNameW(PTRUSTEEW pTrustee) 
{  
    TRACE("(%p)\n", pTrustee); 
  
    if (!pTrustee) 
        return NULL; 
  
    return pTrustee->ptstrName; 
}  
  
/****************************************************************************** 
 * GetTrusteeTypeA [ADVAPI32.@] 
 */ 
TRUSTEE_TYPE WINAPI GetTrusteeTypeA(PTRUSTEEA pTrustee) 
{  
    TRACE("(%p)\n", pTrustee); 
  
    if (!pTrustee) 
        return TRUSTEE_IS_UNKNOWN; 
  
    return pTrustee->TrusteeType; 
}  
  
/****************************************************************************** 
 * GetTrusteeTypeW [ADVAPI32.@] 
 */ 
TRUSTEE_TYPE WINAPI GetTrusteeTypeW(PTRUSTEEW pTrustee) 
{  
    TRACE("(%p)\n", pTrustee); 
  
    if (!pTrustee) 
        return TRUSTEE_IS_UNKNOWN; 
  
    return pTrustee->TrusteeType; 
} 
 
3508 3509 3510 3511
BOOL WINAPI SetAclInformation( PACL pAcl, LPVOID pAclInformation,
                               DWORD nAclInformationLength,
                               ACL_INFORMATION_CLASS dwAclInformationClass )
{
3512
    FIXME("%p %p 0x%08x 0x%08x - stub\n", pAcl, pAclInformation,
3513 3514 3515 3516 3517
          nAclInformationLength, dwAclInformationClass);

    return TRUE;
}

3518 3519 3520 3521 3522 3523
/******************************************************************************
 * SetEntriesInAclA [ADVAPI32.@]
 */
DWORD WINAPI SetEntriesInAclA( ULONG count, PEXPLICIT_ACCESSA pEntries,
                               PACL OldAcl, PACL* NewAcl )
{
3524
    FIXME("%d %p %p %p\n",count,pEntries,OldAcl,NewAcl);
3525 3526
    if (NewAcl)
         *NewAcl = NULL;
3527
    return ERROR_SUCCESS;
3528 3529 3530 3531 3532 3533 3534 3535
}

/******************************************************************************
 * SetEntriesInAclW [ADVAPI32.@]
 */
DWORD WINAPI SetEntriesInAclW( ULONG count, PEXPLICIT_ACCESSW pEntries,
                               PACL OldAcl, PACL* NewAcl )
{
3536 3537 3538 3539 3540 3541 3542 3543
    ULONG i;
    PSID *ppsid;
    DWORD ret = ERROR_SUCCESS;
    DWORD acl_size = sizeof(ACL);
    NTSTATUS status;

    TRACE("%d %p %p %p\n", count, pEntries, OldAcl, NewAcl);

3544
    *NewAcl = NULL;
3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565

    if (!count && !OldAcl)
        return ERROR_SUCCESS;

    /* allocate array of maximum sized sids allowed */
    ppsid = HeapAlloc(GetProcessHeap(), 0, count * (sizeof(SID *) + FIELD_OFFSET(SID, SubAuthority[SID_MAX_SUB_AUTHORITIES])));
    if (!ppsid)
        return ERROR_OUTOFMEMORY;

    for (i = 0; i < count; i++)
    {
        ppsid[i] = (char *)&ppsid[count] + i * FIELD_OFFSET(SID, SubAuthority[SID_MAX_SUB_AUTHORITIES]);

        TRACE("[%d]:\n\tgrfAccessPermissions = 0x%x\n\tgrfAccessMode = %d\n\tgrfInheritance = 0x%x\n\t"
              "Trustee.pMultipleTrustee = %p\n\tMultipleTrusteeOperation = %d\n\tTrusteeForm = %d\n\t"
              "Trustee.TrusteeType = %d\n\tptstrName = %p\n", i,
              pEntries[i].grfAccessPermissions, pEntries[i].grfAccessMode, pEntries[i].grfInheritance,
              pEntries[i].Trustee.pMultipleTrustee, pEntries[i].Trustee.MultipleTrusteeOperation,
              pEntries[i].Trustee.TrusteeForm, pEntries[i].Trustee.TrusteeType,
              pEntries[i].Trustee.ptstrName);

3566
        if (pEntries[i].Trustee.MultipleTrusteeOperation == TRUSTEE_IS_IMPERSONATE)
3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586
        {
            WARN("bad multiple trustee operation %d for trustee %d\n", pEntries[i].Trustee.MultipleTrusteeOperation, i);
            ret = ERROR_INVALID_PARAMETER;
            goto exit;
        }

        switch (pEntries[i].Trustee.TrusteeForm)
        {
        case TRUSTEE_IS_SID:
            if (!CopySid(FIELD_OFFSET(SID, SubAuthority[SID_MAX_SUB_AUTHORITIES]),
                         ppsid[i], pEntries[i].Trustee.ptstrName))
            {
                WARN("bad sid %p for trustee %d\n", pEntries[i].Trustee.ptstrName, i);
                ret = ERROR_INVALID_PARAMETER;
                goto exit;
            }
            break;
        case TRUSTEE_IS_NAME:
        {
            DWORD sid_size = FIELD_OFFSET(SID, SubAuthority[SID_MAX_SUB_AUTHORITIES]);
3587
            DWORD domain_size = MAX_COMPUTERNAME_LENGTH + 1;
3588
            SID_NAME_USE use;
3589 3590 3591 3592 3593 3594 3595 3596 3597
            if (!strcmpW( pEntries[i].Trustee.ptstrName, CURRENT_USER ))
            {
                if (!lookup_user_account_name( ppsid[i], &sid_size, NULL, &domain_size, &use ))
                {
                    ret = GetLastError();
                    goto exit;
                }
            }
            else if (!LookupAccountNameW(NULL, pEntries[i].Trustee.ptstrName, ppsid[i], &sid_size, NULL, &domain_size, &use))
3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789
            {
                WARN("bad user name %s for trustee %d\n", debugstr_w(pEntries[i].Trustee.ptstrName), i);
                ret = ERROR_INVALID_PARAMETER;
                goto exit;
            }
            break;
        }
        case TRUSTEE_IS_OBJECTS_AND_SID:
            FIXME("TRUSTEE_IS_OBJECTS_AND_SID unimplemented\n");
            break;
        case TRUSTEE_IS_OBJECTS_AND_NAME:
            FIXME("TRUSTEE_IS_OBJECTS_AND_NAME unimplemented\n");
            break;
        default:
            WARN("bad trustee form %d for trustee %d\n", pEntries[i].Trustee.TrusteeForm, i);
            ret = ERROR_INVALID_PARAMETER;
            goto exit;
        }

        /* Note: we overestimate the ACL size here as a tradeoff between
         * instructions (simplicity) and memory */
        switch (pEntries[i].grfAccessMode)
        {
        case GRANT_ACCESS:
        case SET_ACCESS:
            acl_size += FIELD_OFFSET(ACCESS_ALLOWED_ACE, SidStart) + GetLengthSid(ppsid[i]);
            break;
        case DENY_ACCESS:
            acl_size += FIELD_OFFSET(ACCESS_DENIED_ACE, SidStart) + GetLengthSid(ppsid[i]);
            break;
        case SET_AUDIT_SUCCESS:
        case SET_AUDIT_FAILURE:
            acl_size += FIELD_OFFSET(SYSTEM_AUDIT_ACE, SidStart) + GetLengthSid(ppsid[i]);
            break;
        case REVOKE_ACCESS:
            break;
        default:
            WARN("bad access mode %d for trustee %d\n", pEntries[i].grfAccessMode, i);
            ret = ERROR_INVALID_PARAMETER;
            goto exit;
        }
    }

    if (OldAcl)
    {
        ACL_SIZE_INFORMATION size_info;

        status = RtlQueryInformationAcl(OldAcl, &size_info, sizeof(size_info), AclSizeInformation);
        if (status != STATUS_SUCCESS)
        {
            ret = RtlNtStatusToDosError(status);
            goto exit;
        }
        acl_size += size_info.AclBytesInUse - sizeof(ACL);
    }

    *NewAcl = LocalAlloc(0, acl_size);
    if (!*NewAcl)
    {
        ret = ERROR_OUTOFMEMORY;
        goto exit;
    }

    status = RtlCreateAcl( *NewAcl, acl_size, ACL_REVISION );
    if (status != STATUS_SUCCESS)
    {
        ret = RtlNtStatusToDosError(status);
        goto exit;
    }

    for (i = 0; i < count; i++)
    {
        switch (pEntries[i].grfAccessMode)
        {
        case GRANT_ACCESS:
            status = RtlAddAccessAllowedAceEx(*NewAcl, ACL_REVISION,
                                              pEntries[i].grfInheritance,
                                              pEntries[i].grfAccessPermissions,
                                              ppsid[i]);
            break;
        case SET_ACCESS:
        {
            ULONG j;
            BOOL add = TRUE;
            if (OldAcl)
            {
                for (j = 0; ; j++)
                {
                    const ACE_HEADER *existing_ace_header;
                    status = RtlGetAce(OldAcl, j, (LPVOID *)&existing_ace_header);
                    if (status != STATUS_SUCCESS)
                        break;
                    if (pEntries[i].grfAccessMode == SET_ACCESS &&
                        existing_ace_header->AceType == ACCESS_ALLOWED_ACE_TYPE &&
                        EqualSid(ppsid[i], &((ACCESS_ALLOWED_ACE *)existing_ace_header)->SidStart))
                    {
                        add = FALSE;
                        break;
                    }
                }
            }
            if (add)
                status = RtlAddAccessAllowedAceEx(*NewAcl, ACL_REVISION,
                                                  pEntries[i].grfInheritance,
                                                  pEntries[i].grfAccessPermissions,
                                                  ppsid[i]);
            break;
        }
        case DENY_ACCESS:
            status = RtlAddAccessDeniedAceEx(*NewAcl, ACL_REVISION,
                                             pEntries[i].grfInheritance,
                                             pEntries[i].grfAccessPermissions,
                                             ppsid[i]);
            break;
        case SET_AUDIT_SUCCESS:
            status = RtlAddAuditAccessAceEx(*NewAcl, ACL_REVISION,
                                            pEntries[i].grfInheritance,
                                            pEntries[i].grfAccessPermissions,
                                            ppsid[i], TRUE, FALSE);
            break;
        case SET_AUDIT_FAILURE:
            status = RtlAddAuditAccessAceEx(*NewAcl, ACL_REVISION,
                                            pEntries[i].grfInheritance,
                                            pEntries[i].grfAccessPermissions,
                                            ppsid[i], FALSE, TRUE);
            break;
        default:
            FIXME("unhandled access mode %d\n", pEntries[i].grfAccessMode);
        }
    }

    if (OldAcl)
    {
        for (i = 0; ; i++)
        {
            BOOL add = TRUE;
            ULONG j;
            const ACE_HEADER *old_ace_header;
            status = RtlGetAce(OldAcl, i, (LPVOID *)&old_ace_header);
            if (status != STATUS_SUCCESS) break;
            for (j = 0; j < count; j++)
            {
                if (pEntries[j].grfAccessMode == SET_ACCESS &&
                    old_ace_header->AceType == ACCESS_ALLOWED_ACE_TYPE &&
                    EqualSid(ppsid[j], &((ACCESS_ALLOWED_ACE *)old_ace_header)->SidStart))
                {
                    status = RtlAddAccessAllowedAceEx(*NewAcl, ACL_REVISION, pEntries[j].grfInheritance, pEntries[j].grfAccessPermissions, ppsid[j]);
                    add = FALSE;
                    break;
                }
                else if (pEntries[j].grfAccessMode == REVOKE_ACCESS)
                {
                    switch (old_ace_header->AceType)
                    {
                    case ACCESS_ALLOWED_ACE_TYPE:
                        if (EqualSid(ppsid[j], &((ACCESS_ALLOWED_ACE *)old_ace_header)->SidStart))
                            add = FALSE;
                        break;
                    case ACCESS_DENIED_ACE_TYPE:
                        if (EqualSid(ppsid[j], &((ACCESS_DENIED_ACE *)old_ace_header)->SidStart))
                            add = FALSE;
                        break;
                    case SYSTEM_AUDIT_ACE_TYPE:
                        if (EqualSid(ppsid[j], &((SYSTEM_AUDIT_ACE *)old_ace_header)->SidStart))
                            add = FALSE;
                        break;
                    case SYSTEM_ALARM_ACE_TYPE:
                        if (EqualSid(ppsid[j], &((SYSTEM_ALARM_ACE *)old_ace_header)->SidStart))
                            add = FALSE;
                        break;
                    default:
                        FIXME("unhandled ace type %d\n", old_ace_header->AceType);
                    }

                    if (!add)
                        break;
                }
            }
            if (add)
                status = RtlAddAce(*NewAcl, ACL_REVISION, 1, (PACE_HEADER)old_ace_header, old_ace_header->AceSize);
            if (status != STATUS_SUCCESS)
            {
                WARN("RtlAddAce failed with error 0x%08x\n", status);
                ret = RtlNtStatusToDosError(status);
                break;
            }
        }
    }

exit:
    HeapFree(GetProcessHeap(), 0, ppsid);
    return ret;
3790 3791 3792 3793 3794 3795 3796 3797 3798
}

/******************************************************************************
 * SetNamedSecurityInfoA [ADVAPI32.@]
 */
DWORD WINAPI SetNamedSecurityInfoA(LPSTR pObjectName,
        SE_OBJECT_TYPE ObjectType, SECURITY_INFORMATION SecurityInfo,
        PSID psidOwner, PSID psidGroup, PACL pDacl, PACL pSacl)
{
3799 3800 3801 3802
    DWORD len;
    LPWSTR wstr = NULL;
    DWORD r;

3803
    TRACE("%s %d %d %p %p %p %p\n", debugstr_a(pObjectName), ObjectType,
3804
           SecurityInfo, psidOwner, psidGroup, pDacl, pSacl);
3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815

    if( pObjectName )
    {
        len = MultiByteToWideChar( CP_ACP, 0, pObjectName, -1, NULL, 0 );
        wstr = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR));
        MultiByteToWideChar( CP_ACP, 0, pObjectName, -1, wstr, len );
    }

    r = SetNamedSecurityInfoW( wstr, ObjectType, SecurityInfo, psidOwner,
                           psidGroup, pDacl, pSacl );

3816
    HeapFree( GetProcessHeap(), 0, wstr );
3817 3818

    return r;
3819 3820
}

3821 3822 3823 3824 3825 3826
BOOL WINAPI SetPrivateObjectSecurity( SECURITY_INFORMATION SecurityInformation,
    PSECURITY_DESCRIPTOR ModificationDescriptor,
    PSECURITY_DESCRIPTOR* ObjectsSecurityDescriptor,
    PGENERIC_MAPPING GenericMapping,
    HANDLE Token )
{
3827
    FIXME("0x%08x %p %p %p %p - stub\n", SecurityInformation, ModificationDescriptor,
3828 3829 3830 3831 3832
          ObjectsSecurityDescriptor, GenericMapping, Token);

    return TRUE;
}

3833 3834 3835 3836 3837
BOOL WINAPI AreAllAccessesGranted( DWORD GrantedAccess, DWORD DesiredAccess )
{
    return RtlAreAllAccessesGranted( GrantedAccess, DesiredAccess );
}

3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854
/******************************************************************************
 * AreAnyAccessesGranted [ADVAPI32.@]
 *
 * Determines whether or not any of a set of specified access permissions have
 * been granted or not.
 *
 * PARAMS
 *   GrantedAccess [I] The permissions that have been granted.
 *   DesiredAccess [I] The permissions that you want to have.
 *
 * RETURNS
 *   Nonzero if any of the permissions have been granted, zero if none of the
 *   permissions have been granted.
 */

BOOL WINAPI AreAnyAccessesGranted( DWORD GrantedAccess, DWORD DesiredAccess )
{
3855
    return RtlAreAnyAccessesGranted( GrantedAccess, DesiredAccess );
3856 3857
}

3858 3859 3860 3861 3862 3863 3864
/******************************************************************************
 * SetNamedSecurityInfoW [ADVAPI32.@]
 */
DWORD WINAPI SetNamedSecurityInfoW(LPWSTR pObjectName,
        SE_OBJECT_TYPE ObjectType, SECURITY_INFORMATION SecurityInfo,
        PSID psidOwner, PSID psidGroup, PACL pDacl, PACL pSacl)
{
3865
    FIXME("%s %d %d %p %p %p %p\n", debugstr_w(pObjectName), ObjectType,
3866
           SecurityInfo, psidOwner, psidGroup, pDacl, pSacl);
3867
    return ERROR_SUCCESS;
3868
}
3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888

/******************************************************************************
 * GetExplicitEntriesFromAclA [ADVAPI32.@]
 */
DWORD WINAPI GetExplicitEntriesFromAclA( PACL pacl, PULONG pcCountOfExplicitEntries,
        PEXPLICIT_ACCESSA* pListOfExplicitEntries)
{
    FIXME("%p %p %p\n",pacl, pcCountOfExplicitEntries, pListOfExplicitEntries);
    return ERROR_CALL_NOT_IMPLEMENTED;
}

/******************************************************************************
 * GetExplicitEntriesFromAclW [ADVAPI32.@]
 */
DWORD WINAPI GetExplicitEntriesFromAclW( PACL pacl, PULONG pcCountOfExplicitEntries,
        PEXPLICIT_ACCESSW* pListOfExplicitEntries)
{
    FIXME("%p %p %p\n",pacl, pcCountOfExplicitEntries, pListOfExplicitEntries);
    return ERROR_CALL_NOT_IMPLEMENTED;
}
3889

3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910
/******************************************************************************
 * GetAuditedPermissionsFromAclA [ADVAPI32.@]
 */
DWORD WINAPI GetAuditedPermissionsFromAclA( PACL pacl, PTRUSTEEA pTrustee, PACCESS_MASK pSuccessfulAuditedRights,
        PACCESS_MASK pFailedAuditRights)
{
    FIXME("%p %p %p %p\n",pacl, pTrustee, pSuccessfulAuditedRights, pFailedAuditRights);
    return ERROR_CALL_NOT_IMPLEMENTED;

}

/******************************************************************************
 * GetAuditedPermissionsFromAclW [ADVAPI32.@]
 */
DWORD WINAPI GetAuditedPermissionsFromAclW( PACL pacl, PTRUSTEEW pTrustee, PACCESS_MASK pSuccessfulAuditedRights,
        PACCESS_MASK pFailedAuditRights)
{
    FIXME("%p %p %p %p\n",pacl, pTrustee, pSuccessfulAuditedRights, pFailedAuditRights);
    return ERROR_CALL_NOT_IMPLEMENTED;

}
3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943

/******************************************************************************
 * ParseAclStringFlags
 */
static DWORD ParseAclStringFlags(LPCWSTR* StringAcl)
{
    DWORD flags = 0;
    LPCWSTR szAcl = *StringAcl;

    while (*szAcl != '(')
    {
        if (*szAcl == 'P')
	{
            flags |= SE_DACL_PROTECTED;
	}
        else if (*szAcl == 'A')
        {
            szAcl++;
            if (*szAcl == 'R')
                flags |= SE_DACL_AUTO_INHERIT_REQ;
	    else if (*szAcl == 'I')
                flags |= SE_DACL_AUTO_INHERITED;
        }
        szAcl++;
    }

    *StringAcl = szAcl;
    return flags;
}

/******************************************************************************
 * ParseAceStringType
 */
3944
static const ACEFLAG AceType[] =
3945 3946 3947
{
    { SDDL_ALARM,          SYSTEM_ALARM_ACE_TYPE },
    { SDDL_AUDIT,          SYSTEM_AUDIT_ACE_TYPE },
3948
    { SDDL_ACCESS_ALLOWED, ACCESS_ALLOWED_ACE_TYPE },
3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962
    { SDDL_ACCESS_DENIED,  ACCESS_DENIED_ACE_TYPE },
    /*
    { SDDL_OBJECT_ACCESS_ALLOWED, ACCESS_ALLOWED_OBJECT_ACE_TYPE },
    { SDDL_OBJECT_ACCESS_DENIED,  ACCESS_DENIED_OBJECT_ACE_TYPE },
    { SDDL_OBJECT_ALARM,          SYSTEM_ALARM_OBJECT_ACE_TYPE },
    { SDDL_OBJECT_AUDIT,          SYSTEM_AUDIT_OBJECT_ACE_TYPE },
    */
    { NULL, 0 },
};

static BYTE ParseAceStringType(LPCWSTR* StringAcl)
{
    UINT len = 0;
    LPCWSTR szAcl = *StringAcl;
3963
    const ACEFLAG *lpaf = AceType;
3964

3965 3966 3967
    while (*szAcl == ' ')
        szAcl++;

3968 3969 3970 3971 3972 3973 3974 3975
    while (lpaf->wstr &&
        (len = strlenW(lpaf->wstr)) &&
        strncmpW(lpaf->wstr, szAcl, len))
        lpaf++;

    if (!lpaf->wstr)
        return 0;

3976
    *StringAcl = szAcl + len;
3977 3978 3979 3980 3981 3982 3983
    return lpaf->value;
}


/******************************************************************************
 * ParseAceStringFlags
 */
3984
static const ACEFLAG AceFlags[] =
3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001
{
    { SDDL_CONTAINER_INHERIT, CONTAINER_INHERIT_ACE },
    { SDDL_AUDIT_FAILURE,     FAILED_ACCESS_ACE_FLAG },
    { SDDL_INHERITED,         INHERITED_ACE },
    { SDDL_INHERIT_ONLY,      INHERIT_ONLY_ACE },
    { SDDL_NO_PROPAGATE,      NO_PROPAGATE_INHERIT_ACE },
    { SDDL_OBJECT_INHERIT,    OBJECT_INHERIT_ACE },
    { SDDL_AUDIT_SUCCESS,     SUCCESSFUL_ACCESS_ACE_FLAG },
    { NULL, 0 },
};

static BYTE ParseAceStringFlags(LPCWSTR* StringAcl)
{
    UINT len = 0;
    BYTE flags = 0;
    LPCWSTR szAcl = *StringAcl;

4002 4003 4004
    while (*szAcl == ' ')
        szAcl++;

4005 4006
    while (*szAcl != ';')
    {
4007
        const ACEFLAG *lpaf = AceFlags;
4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028

        while (lpaf->wstr &&
               (len = strlenW(lpaf->wstr)) &&
               strncmpW(lpaf->wstr, szAcl, len))
            lpaf++;

        if (!lpaf->wstr)
            return 0;

	flags |= lpaf->value;
        szAcl += len;
    }

    *StringAcl = szAcl;
    return flags;
}


/******************************************************************************
 * ParseAceStringRights
 */
4029
static const ACEFLAG AceRights[] =
4030 4031 4032 4033 4034
{
    { SDDL_GENERIC_ALL,     GENERIC_ALL },
    { SDDL_GENERIC_READ,    GENERIC_READ },
    { SDDL_GENERIC_WRITE,   GENERIC_WRITE },
    { SDDL_GENERIC_EXECUTE, GENERIC_EXECUTE },
4035

4036 4037 4038 4039
    { SDDL_READ_CONTROL,    READ_CONTROL },
    { SDDL_STANDARD_DELETE, DELETE },
    { SDDL_WRITE_DAC,       WRITE_DAC },
    { SDDL_WRITE_OWNER,     WRITE_OWNER },
4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059

    { SDDL_READ_PROPERTY,   ADS_RIGHT_DS_READ_PROP},
    { SDDL_WRITE_PROPERTY,  ADS_RIGHT_DS_WRITE_PROP},
    { SDDL_CREATE_CHILD,    ADS_RIGHT_DS_CREATE_CHILD},
    { SDDL_DELETE_CHILD,    ADS_RIGHT_DS_DELETE_CHILD},
    { SDDL_LIST_CHILDREN,   ADS_RIGHT_ACTRL_DS_LIST},
    { SDDL_SELF_WRITE,      ADS_RIGHT_DS_SELF},
    { SDDL_LIST_OBJECT,     ADS_RIGHT_DS_LIST_OBJECT},
    { SDDL_DELETE_TREE,     ADS_RIGHT_DS_DELETE_TREE},
    { SDDL_CONTROL_ACCESS,  ADS_RIGHT_DS_CONTROL_ACCESS},

    { SDDL_FILE_ALL,        FILE_ALL_ACCESS },
    { SDDL_FILE_READ,       FILE_GENERIC_READ },
    { SDDL_FILE_WRITE,      FILE_GENERIC_WRITE },
    { SDDL_FILE_EXECUTE,    FILE_GENERIC_EXECUTE },

    { SDDL_KEY_ALL,         KEY_ALL_ACCESS },
    { SDDL_KEY_READ,        KEY_READ },
    { SDDL_KEY_WRITE,       KEY_WRITE },
    { SDDL_KEY_EXECUTE,     KEY_EXECUTE },
4060 4061 4062 4063 4064 4065 4066 4067 4068
    { NULL, 0 },
};

static DWORD ParseAceStringRights(LPCWSTR* StringAcl)
{
    UINT len = 0;
    DWORD rights = 0;
    LPCWSTR szAcl = *StringAcl;

4069 4070 4071
    while (*szAcl == ' ')
        szAcl++;

4072 4073 4074 4075 4076 4077 4078
    if ((*szAcl == '0') && (*(szAcl + 1) == 'x'))
    {
        LPCWSTR p = szAcl;

	while (*p && *p != ';')
            p++;

4079
	if (p - szAcl <= 10 /* 8 hex digits + "0x" */ )
4080 4081
	{
	    rights = strtoulW(szAcl, NULL, 16);
4082
	    szAcl = p;
4083 4084 4085 4086 4087 4088 4089 4090
	}
	else
            WARN("Invalid rights string format: %s\n", debugstr_wn(szAcl, p - szAcl));
    }
    else
    {
        while (*szAcl != ';')
        {
4091
            const ACEFLAG *lpaf = AceRights;
4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123

            while (lpaf->wstr &&
               (len = strlenW(lpaf->wstr)) &&
               strncmpW(lpaf->wstr, szAcl, len))
	    {
               lpaf++;
	    }

            if (!lpaf->wstr)
                return 0;

	    rights |= lpaf->value;
            szAcl += len;
        }
    }

    *StringAcl = szAcl;
    return rights;
}


/******************************************************************************
 * ParseStringAclToAcl
 * 
 * dacl_flags(string_ace1)(string_ace2)... (string_acen) 
 */
static BOOL ParseStringAclToAcl(LPCWSTR StringAcl, LPDWORD lpdwFlags, 
    PACL pAcl, LPDWORD cBytes)
{
    DWORD val;
    DWORD sidlen;
    DWORD length = sizeof(ACL);
4124 4125
    DWORD acesize = 0;
    DWORD acecount = 0;
4126
    PACCESS_ALLOWED_ACE pAce = NULL; /* pointer to current ACE */
4127
    DWORD error = ERROR_INVALID_ACL;
4128 4129 4130 4131 4132 4133 4134

    TRACE("%s\n", debugstr_w(StringAcl));

    if (!StringAcl)
	return FALSE;

    if (pAcl) /* pAce is only useful if we're setting values */
4135
        pAce = (PACCESS_ALLOWED_ACE) (pAcl + 1);
4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149

    /* Parse ACL flags */
    *lpdwFlags = ParseAclStringFlags(&StringAcl);

    /* Parse ACE */
    while (*StringAcl == '(')
    {
        StringAcl++;

        /* Parse ACE type */
        val = ParseAceStringType(&StringAcl);
	if (pAce)
            pAce->Header.AceType = (BYTE) val;
        if (*StringAcl != ';')
4150 4151
        {
            error = RPC_S_INVALID_STRING_UUID;
4152
            goto lerr;
4153
        }
4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172
        StringAcl++;

        /* Parse ACE flags */
	val = ParseAceStringFlags(&StringAcl);
	if (pAce)
            pAce->Header.AceFlags = (BYTE) val;
        if (*StringAcl != ';')
            goto lerr;
        StringAcl++;

        /* Parse ACE rights */
	val = ParseAceStringRights(&StringAcl);
	if (pAce)
            pAce->Mask = val;
        if (*StringAcl != ';')
            goto lerr;
        StringAcl++;

        /* Parse ACE object guid */
4173 4174
        while (*StringAcl == ' ')
            StringAcl++;
4175 4176
        if (*StringAcl != ';')
        {
4177
            FIXME("Support for *_OBJECT_ACE_TYPE not implemented\n");
4178 4179 4180 4181 4182
            goto lerr;
        }
        StringAcl++;

        /* Parse ACE inherit object guid */
4183 4184
        while (*StringAcl == ' ')
            StringAcl++;
4185 4186
        if (*StringAcl != ';')
        {
4187
            FIXME("Support for *_OBJECT_ACE_TYPE not implemented\n");
4188 4189 4190 4191 4192
            goto lerr;
        }
        StringAcl++;

        /* Parse ACE account sid */
4193
        if (ParseStringSidToSid(StringAcl, pAce ? &pAce->SidStart : NULL, &sidlen))
4194 4195 4196 4197 4198 4199 4200 4201 4202
	{
            while (*StringAcl && *StringAcl != ')')
                StringAcl++;
	}

        if (*StringAcl != ')')
            goto lerr;
        StringAcl++;

4203 4204 4205 4206 4207 4208 4209 4210
        acesize = sizeof(ACCESS_ALLOWED_ACE) - sizeof(DWORD) + sidlen;
        length += acesize;
        if (pAce)
        {
            pAce->Header.AceSize = acesize;
            pAce = (PACCESS_ALLOWED_ACE)((LPBYTE)pAce + acesize);
        }
        acecount++;
4211 4212 4213
    }

    *cBytes = length;
4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228

    if (length > 0xffff)
    {
        ERR("ACL too large\n");
        goto lerr;
    }

    if (pAcl)
    {
        pAcl->AclRevision = ACL_REVISION;
        pAcl->Sbz1 = 0;
        pAcl->AclSize = length;
        pAcl->AceCount = acecount++;
        pAcl->Sbz2 = 0;
    }
4229 4230 4231
    return TRUE;

lerr:
4232
    SetLastError(error);
4233 4234 4235 4236 4237 4238 4239 4240 4241 4242
    WARN("Invalid ACE string format\n");
    return FALSE;
}


/******************************************************************************
 * ParseStringSecurityDescriptorToSecurityDescriptor
 */
static BOOL ParseStringSecurityDescriptorToSecurityDescriptor(
    LPCWSTR StringSecurityDescriptor,
4243
    SECURITY_DESCRIPTOR_RELATIVE* SecurityDescriptor,
4244 4245 4246 4247 4248 4249 4250
    LPDWORD cBytes)
{
    BOOL bret = FALSE;
    WCHAR toktype;
    WCHAR tok[MAX_PATH];
    LPCWSTR lptoken;
    LPBYTE lpNext = NULL;
4251
    DWORD len;
4252

4253
    *cBytes = sizeof(SECURITY_DESCRIPTOR);
4254 4255

    if (SecurityDescriptor)
4256
        lpNext = (LPBYTE)(SecurityDescriptor + 1);
4257

4258 4259 4260
    while (*StringSecurityDescriptor == ' ')
        StringSecurityDescriptor++;

4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281
    while (*StringSecurityDescriptor)
    {
        toktype = *StringSecurityDescriptor;

	/* Expect char identifier followed by ':' */
	StringSecurityDescriptor++;
        if (*StringSecurityDescriptor != ':')
        {
            SetLastError(ERROR_INVALID_PARAMETER);
            goto lend;
        }
	StringSecurityDescriptor++;

	/* Extract token */
	lptoken = StringSecurityDescriptor;
	while (*lptoken && *lptoken != ':')
            lptoken++;

	if (*lptoken)
            lptoken--;

4282 4283 4284
        len = lptoken - StringSecurityDescriptor;
        memcpy( tok, StringSecurityDescriptor, len * sizeof(WCHAR) );
        tok[len] = 0;
4285 4286 4287 4288 4289 4290 4291

        switch (toktype)
	{
            case 'O':
            {
                DWORD bytes;

4292
                if (!ParseStringSidToSid(tok, lpNext, &bytes))
4293 4294 4295 4296
                    goto lend;

                if (SecurityDescriptor)
                {
4297
                    SecurityDescriptor->Owner = lpNext - (LPBYTE)SecurityDescriptor;
4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309
                    lpNext += bytes; /* Advance to next token */
                }

		*cBytes += bytes;

                break;
            }

            case 'G':
            {
                DWORD bytes;

4310
                if (!ParseStringSidToSid(tok, lpNext, &bytes))
4311 4312 4313 4314
                    goto lend;

                if (SecurityDescriptor)
                {
4315
                    SecurityDescriptor->Group = lpNext - (LPBYTE)SecurityDescriptor;
4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334
                    lpNext += bytes; /* Advance to next token */
                }

		*cBytes += bytes;

                break;
            }

            case 'D':
	    {
                DWORD flags;
                DWORD bytes;

                if (!ParseStringAclToAcl(tok, &flags, (PACL)lpNext, &bytes))
                    goto lend;

                if (SecurityDescriptor)
                {
                    SecurityDescriptor->Control |= SE_DACL_PRESENT | flags;
4335
                    SecurityDescriptor->Dacl = lpNext - (LPBYTE)SecurityDescriptor;
4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354
                    lpNext += bytes; /* Advance to next token */
		}

		*cBytes += bytes;

		break;
            }

            case 'S':
            {
                DWORD flags;
                DWORD bytes;

                if (!ParseStringAclToAcl(tok, &flags, (PACL)lpNext, &bytes))
                    goto lend;

                if (SecurityDescriptor)
                {
                    SecurityDescriptor->Control |= SE_SACL_PRESENT | flags;
4355
                    SecurityDescriptor->Sacl = lpNext - (LPBYTE)SecurityDescriptor;
4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378
                    lpNext += bytes; /* Advance to next token */
		}

		*cBytes += bytes;

		break;
            }

            default:
                FIXME("Unknown token\n");
                SetLastError(ERROR_INVALID_PARAMETER);
		goto lend;
	}

        StringSecurityDescriptor = lptoken;
    }

    bret = TRUE;

lend:
    return bret;
}

4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392
/******************************************************************************
 * ConvertStringSecurityDescriptorToSecurityDescriptorA [ADVAPI32.@]
 */
BOOL WINAPI ConvertStringSecurityDescriptorToSecurityDescriptorA(
        LPCSTR StringSecurityDescriptor,
        DWORD StringSDRevision,
        PSECURITY_DESCRIPTOR* SecurityDescriptor,
        PULONG SecurityDescriptorSize)
{
    UINT len;
    BOOL ret = FALSE;
    LPWSTR StringSecurityDescriptorW;

    len = MultiByteToWideChar(CP_ACP, 0, StringSecurityDescriptor, -1, NULL, 0);
4393
    StringSecurityDescriptorW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407

    if (StringSecurityDescriptorW)
    {
        MultiByteToWideChar(CP_ACP, 0, StringSecurityDescriptor, -1, StringSecurityDescriptorW, len);

        ret = ConvertStringSecurityDescriptorToSecurityDescriptorW(StringSecurityDescriptorW,
                                                                   StringSDRevision, SecurityDescriptor,
                                                                   SecurityDescriptorSize);
        HeapFree(GetProcessHeap(), 0, StringSecurityDescriptorW);
    }

    return ret;
}

4408 4409 4410 4411 4412 4413 4414 4415 4416 4417
/******************************************************************************
 * ConvertStringSecurityDescriptorToSecurityDescriptorW [ADVAPI32.@]
 */
BOOL WINAPI ConvertStringSecurityDescriptorToSecurityDescriptorW(
        LPCWSTR StringSecurityDescriptor,
        DWORD StringSDRevision,
        PSECURITY_DESCRIPTOR* SecurityDescriptor,
        PULONG SecurityDescriptorSize)
{
    DWORD cBytes;
4418
    SECURITY_DESCRIPTOR* psd;
4419 4420 4421 4422 4423 4424 4425 4426 4427
    BOOL bret = FALSE;

    TRACE("%s\n", debugstr_w(StringSecurityDescriptor));

    if (GetVersion() & 0x80000000)
    {
        SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
        goto lend;
    }
4428 4429 4430 4431 4432
    else if (!StringSecurityDescriptor || !SecurityDescriptor)
    {
        SetLastError(ERROR_INVALID_PARAMETER);
        goto lend;
    }
4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443
    else if (StringSDRevision != SID_REVISION)
    {
        SetLastError(ERROR_UNKNOWN_REVISION);
	goto lend;
    }

    /* Compute security descriptor length */
    if (!ParseStringSecurityDescriptorToSecurityDescriptor(StringSecurityDescriptor,
        NULL, &cBytes))
	goto lend;

4444
    psd = *SecurityDescriptor = LocalAlloc(GMEM_ZEROINIT, cBytes);
4445
    if (!psd) goto lend;
4446 4447 4448 4449 4450

    psd->Revision = SID_REVISION;
    psd->Control |= SE_SELF_RELATIVE;

    if (!ParseStringSecurityDescriptorToSecurityDescriptor(StringSecurityDescriptor,
4451
             (SECURITY_DESCRIPTOR_RELATIVE *)psd, &cBytes))
4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466
    {
        LocalFree(psd);
	goto lend;
    }

    if (SecurityDescriptorSize)
        *SecurityDescriptorSize = cBytes;

    bret = TRUE;
 
lend:
    TRACE(" ret=%d\n", bret);
    return bret;
}

4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522
static void DumpString(LPCWSTR string, int cch, WCHAR **pwptr, ULONG *plen)
{
    if (cch == -1)
        cch = strlenW(string);

    if (plen)
        *plen += cch;

    if (pwptr)
    {
        memcpy(*pwptr, string, sizeof(WCHAR)*cch);
        *pwptr += cch;
    }
}

static BOOL DumpSidNumeric(PSID psid, WCHAR **pwptr, ULONG *plen)
{
    DWORD i;
    WCHAR fmt[] = { 'S','-','%','u','-','%','d',0 };
    WCHAR subauthfmt[] = { '-','%','u',0 };
    WCHAR buf[26];
    SID *pisid = psid;

    if( !IsValidSid( psid ) || pisid->Revision != SDDL_REVISION)
    {
        SetLastError(ERROR_INVALID_SID);
        return FALSE;
    }

    if (pisid->IdentifierAuthority.Value[0] ||
     pisid->IdentifierAuthority.Value[1])
    {
        FIXME("not matching MS' bugs\n");
        SetLastError(ERROR_INVALID_SID);
        return FALSE;
    }

    sprintfW( buf, fmt, pisid->Revision,
        MAKELONG(
            MAKEWORD( pisid->IdentifierAuthority.Value[5],
                    pisid->IdentifierAuthority.Value[4] ),
            MAKEWORD( pisid->IdentifierAuthority.Value[3],
                    pisid->IdentifierAuthority.Value[2] )
        ) );
    DumpString(buf, -1, pwptr, plen);

    for( i=0; i<pisid->SubAuthorityCount; i++ )
    {
        sprintfW( buf, subauthfmt, pisid->SubAuthority[i] );
        DumpString(buf, -1, pwptr, plen);
    }
    return TRUE;
}

static BOOL DumpSid(PSID psid, WCHAR **pwptr, ULONG *plen)
{
4523
    size_t i;
4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535
    for (i = 0; i < sizeof(WellKnownSids) / sizeof(WellKnownSids[0]); i++)
    {
        if (WellKnownSids[i].wstr[0] && EqualSid(psid, (PSID)&(WellKnownSids[i].Sid.Revision)))
        {
            DumpString(WellKnownSids[i].wstr, 2, pwptr, plen);
            return TRUE;
        }
    }

    return DumpSidNumeric(psid, pwptr, plen);
}

4536
static const LPCWSTR AceRightBitNames[32] = {
4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572
        SDDL_CREATE_CHILD,        /*  0 */
        SDDL_DELETE_CHILD,
        SDDL_LIST_CHILDREN,
        SDDL_SELF_WRITE,
        SDDL_READ_PROPERTY,       /*  4 */
        SDDL_WRITE_PROPERTY,
        SDDL_DELETE_TREE,
        SDDL_LIST_OBJECT,
        SDDL_CONTROL_ACCESS,      /*  8 */
        NULL,
        NULL,
        NULL,
        NULL,                     /* 12 */
        NULL,
        NULL,
        NULL,
        SDDL_STANDARD_DELETE,     /* 16 */
        SDDL_READ_CONTROL,
        SDDL_WRITE_DAC,
        SDDL_WRITE_OWNER,
        NULL,                     /* 20 */
        NULL,
        NULL,
        NULL,
        NULL,                     /* 24 */
        NULL,
        NULL,
        NULL,
        SDDL_GENERIC_ALL,         /* 28 */
        SDDL_GENERIC_EXECUTE,
        SDDL_GENERIC_WRITE,
        SDDL_GENERIC_READ
};

static void DumpRights(DWORD mask, WCHAR **pwptr, ULONG *plen)
{
4573
    static const WCHAR fmtW[] = {'0','x','%','x',0};
4574
    WCHAR buf[15];
4575
    size_t i;
4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612

    if (mask == 0)
        return;

    /* first check if the right have name */
    for (i = 0; i < sizeof(AceRights)/sizeof(AceRights[0]); i++)
    {
        if (AceRights[i].wstr == NULL)
            break;
        if (mask == AceRights[i].value)
        {
            DumpString(AceRights[i].wstr, -1, pwptr, plen);
            return;
        }
    }

    /* then check if it can be built from bit names */
    for (i = 0; i < 32; i++)
    {
        if ((mask & (1 << i)) && (AceRightBitNames[i] == NULL))
        {
            /* can't be built from bit names */
            sprintfW(buf, fmtW, mask);
            DumpString(buf, -1, pwptr, plen);
            return;
        }
    }

    /* build from bit names */
    for (i = 0; i < 32; i++)
        if (mask & (1 << i))
            DumpString(AceRightBitNames[i], -1, pwptr, plen);
}

static BOOL DumpAce(LPVOID pace, WCHAR **pwptr, ULONG *plen)
{
    ACCESS_ALLOWED_ACE *piace; /* all the supported ACEs have the same memory layout */
4613 4614 4615
    static const WCHAR openbr = '(';
    static const WCHAR closebr = ')';
    static const WCHAR semicolon = ';';
4616 4617 4618 4619 4620 4621 4622

    if (((PACE_HEADER)pace)->AceType > SYSTEM_ALARM_ACE_TYPE || ((PACE_HEADER)pace)->AceSize < sizeof(ACCESS_ALLOWED_ACE))
    {
        SetLastError(ERROR_INVALID_ACL);
        return FALSE;
    }

4623
    piace = pace;
4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662
    DumpString(&openbr, 1, pwptr, plen);
    switch (piace->Header.AceType)
    {
        case ACCESS_ALLOWED_ACE_TYPE:
            DumpString(SDDL_ACCESS_ALLOWED, -1, pwptr, plen);
            break;
        case ACCESS_DENIED_ACE_TYPE:
            DumpString(SDDL_ACCESS_DENIED, -1, pwptr, plen);
            break;
        case SYSTEM_AUDIT_ACE_TYPE:
            DumpString(SDDL_AUDIT, -1, pwptr, plen);
            break;
        case SYSTEM_ALARM_ACE_TYPE:
            DumpString(SDDL_ALARM, -1, pwptr, plen);
            break;
    }
    DumpString(&semicolon, 1, pwptr, plen);

    if (piace->Header.AceFlags & OBJECT_INHERIT_ACE)
        DumpString(SDDL_OBJECT_INHERIT, -1, pwptr, plen);
    if (piace->Header.AceFlags & CONTAINER_INHERIT_ACE)
        DumpString(SDDL_CONTAINER_INHERIT, -1, pwptr, plen);
    if (piace->Header.AceFlags & NO_PROPAGATE_INHERIT_ACE)
        DumpString(SDDL_NO_PROPAGATE, -1, pwptr, plen);
    if (piace->Header.AceFlags & INHERIT_ONLY_ACE)
        DumpString(SDDL_INHERIT_ONLY, -1, pwptr, plen);
    if (piace->Header.AceFlags & INHERITED_ACE)
        DumpString(SDDL_INHERITED, -1, pwptr, plen);
    if (piace->Header.AceFlags & SUCCESSFUL_ACCESS_ACE_FLAG)
        DumpString(SDDL_AUDIT_SUCCESS, -1, pwptr, plen);
    if (piace->Header.AceFlags & FAILED_ACCESS_ACE_FLAG)
        DumpString(SDDL_AUDIT_FAILURE, -1, pwptr, plen);
    DumpString(&semicolon, 1, pwptr, plen);
    DumpRights(piace->Mask, pwptr, plen);
    DumpString(&semicolon, 1, pwptr, plen);
    /* objects not supported */
    DumpString(&semicolon, 1, pwptr, plen);
    /* objects not supported */
    DumpString(&semicolon, 1, pwptr, plen);
4663
    if (!DumpSid(&piace->SidStart, pwptr, plen))
4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701
        return FALSE;
    DumpString(&closebr, 1, pwptr, plen);
    return TRUE;
}

static BOOL DumpAcl(PACL pacl, WCHAR **pwptr, ULONG *plen, BOOL protected, BOOL autoInheritReq, BOOL autoInherited)
{
    WORD count;
    int i;

    if (protected)
        DumpString(SDDL_PROTECTED, -1, pwptr, plen);
    if (autoInheritReq)
        DumpString(SDDL_AUTO_INHERIT_REQ, -1, pwptr, plen);
    if (autoInherited)
        DumpString(SDDL_AUTO_INHERITED, -1, pwptr, plen);

    if (pacl == NULL)
        return TRUE;

    if (!IsValidAcl(pacl))
        return FALSE;

    count = pacl->AceCount;
    for (i = 0; i < count; i++)
    {
        LPVOID ace;
        if (!GetAce(pacl, i, &ace))
            return FALSE;
        if (!DumpAce(ace, pwptr, plen))
            return FALSE;
    }

    return TRUE;
}

static BOOL DumpOwner(PSECURITY_DESCRIPTOR SecurityDescriptor, WCHAR **pwptr, ULONG *plen)
{
4702
    static const WCHAR prefix[] = {'O',':',0};
4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719
    BOOL bDefaulted;
    PSID psid;

    if (!GetSecurityDescriptorOwner(SecurityDescriptor, &psid, &bDefaulted))
        return FALSE;

    if (psid == NULL)
        return TRUE;

    DumpString(prefix, -1, pwptr, plen);
    if (!DumpSid(psid, pwptr, plen))
        return FALSE;
    return TRUE;
}

static BOOL DumpGroup(PSECURITY_DESCRIPTOR SecurityDescriptor, WCHAR **pwptr, ULONG *plen)
{
4720
    static const WCHAR prefix[] = {'G',':',0};
4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784
    BOOL bDefaulted;
    PSID psid;

    if (!GetSecurityDescriptorGroup(SecurityDescriptor, &psid, &bDefaulted))
        return FALSE;

    if (psid == NULL)
        return TRUE;

    DumpString(prefix, -1, pwptr, plen);
    if (!DumpSid(psid, pwptr, plen))
        return FALSE;
    return TRUE;
}

static BOOL DumpDacl(PSECURITY_DESCRIPTOR SecurityDescriptor, WCHAR **pwptr, ULONG *plen)
{
    static const WCHAR dacl[] = {'D',':',0};
    SECURITY_DESCRIPTOR_CONTROL control;
    BOOL present, defaulted;
    DWORD revision;
    PACL pacl;

    if (!GetSecurityDescriptorDacl(SecurityDescriptor, &present, &pacl, &defaulted))
        return FALSE;

    if (!GetSecurityDescriptorControl(SecurityDescriptor, &control, &revision))
        return FALSE;

    if (!present)
        return TRUE;

    DumpString(dacl, 2, pwptr, plen);
    if (!DumpAcl(pacl, pwptr, plen, control & SE_DACL_PROTECTED, control & SE_DACL_AUTO_INHERIT_REQ, control & SE_DACL_AUTO_INHERITED))
        return FALSE;
    return TRUE;
}

static BOOL DumpSacl(PSECURITY_DESCRIPTOR SecurityDescriptor, WCHAR **pwptr, ULONG *plen)
{
    static const WCHAR sacl[] = {'S',':',0};
    SECURITY_DESCRIPTOR_CONTROL control;
    BOOL present, defaulted;
    DWORD revision;
    PACL pacl;

    if (!GetSecurityDescriptorSacl(SecurityDescriptor, &present, &pacl, &defaulted))
        return FALSE;

    if (!GetSecurityDescriptorControl(SecurityDescriptor, &control, &revision))
        return FALSE;

    if (!present)
        return TRUE;

    DumpString(sacl, 2, pwptr, plen);
    if (!DumpAcl(pacl, pwptr, plen, control & SE_SACL_PROTECTED, control & SE_SACL_AUTO_INHERIT_REQ, control & SE_SACL_AUTO_INHERITED))
        return FALSE;
    return TRUE;
}

/******************************************************************************
 * ConvertSecurityDescriptorToStringSecurityDescriptorA [ADVAPI32.@]
 */
4785
BOOL WINAPI ConvertSecurityDescriptorToStringSecurityDescriptorW(PSECURITY_DESCRIPTOR SecurityDescriptor, DWORD SDRevision, SECURITY_INFORMATION RequestedInformation, LPWSTR *OutputString, PULONG OutputLen)
4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835
{
    ULONG len;
    WCHAR *wptr, *wstr;

    if (SDRevision != SDDL_REVISION_1)
    {
        ERR("Pogram requested unknown SDDL revision %d\n", SDRevision);
        SetLastError(ERROR_UNKNOWN_REVISION);
        return FALSE;
    }

    len = 0;
    if (RequestedInformation & OWNER_SECURITY_INFORMATION)
        if (!DumpOwner(SecurityDescriptor, NULL, &len))
            return FALSE;
    if (RequestedInformation & GROUP_SECURITY_INFORMATION)
        if (!DumpGroup(SecurityDescriptor, NULL, &len))
            return FALSE;
    if (RequestedInformation & DACL_SECURITY_INFORMATION)
        if (!DumpDacl(SecurityDescriptor, NULL, &len))
            return FALSE;
    if (RequestedInformation & SACL_SECURITY_INFORMATION)
        if (!DumpSacl(SecurityDescriptor, NULL, &len))
            return FALSE;

    wstr = wptr = LocalAlloc(0, (len + 1)*sizeof(WCHAR));
    if (RequestedInformation & OWNER_SECURITY_INFORMATION)
        if (!DumpOwner(SecurityDescriptor, &wptr, NULL))
            return FALSE;
    if (RequestedInformation & GROUP_SECURITY_INFORMATION)
        if (!DumpGroup(SecurityDescriptor, &wptr, NULL))
            return FALSE;
    if (RequestedInformation & DACL_SECURITY_INFORMATION)
        if (!DumpDacl(SecurityDescriptor, &wptr, NULL))
            return FALSE;
    if (RequestedInformation & SACL_SECURITY_INFORMATION)
        if (!DumpSacl(SecurityDescriptor, &wptr, NULL))
            return FALSE;
    *wptr = 0;

    TRACE("ret: %s, %d\n", wine_dbgstr_w(wstr), len);
    *OutputString = wstr;
    if (OutputLen)
        *OutputLen = strlenW(*OutputString)+1;
    return TRUE;
}

/******************************************************************************
 * ConvertSecurityDescriptorToStringSecurityDescriptorA [ADVAPI32.@]
 */
4836
BOOL WINAPI ConvertSecurityDescriptorToStringSecurityDescriptorA(PSECURITY_DESCRIPTOR SecurityDescriptor, DWORD SDRevision, SECURITY_INFORMATION Information, LPSTR *OutputString, PULONG OutputLen)
4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861
{
    LPWSTR wstr;
    ULONG len;
    if (ConvertSecurityDescriptorToStringSecurityDescriptorW(SecurityDescriptor, SDRevision, Information, &wstr, &len))
    {
        int lenA;

        lenA = WideCharToMultiByte(CP_ACP, 0, wstr, len, NULL, 0, NULL, NULL);
        *OutputString = HeapAlloc(GetProcessHeap(), 0, lenA);
        WideCharToMultiByte(CP_ACP, 0, wstr, len, *OutputString, lenA, NULL, NULL);
        LocalFree(wstr);

        if (OutputLen != NULL)
            *OutputLen = lenA;
        return TRUE;
    }
    else
    {
        *OutputString = NULL;
        if (OutputLen)
            *OutputLen = 0;
        return FALSE;
    }
}

4862 4863 4864 4865 4866 4867 4868 4869
/******************************************************************************
 * ConvertStringSidToSidW [ADVAPI32.@]
 */
BOOL WINAPI ConvertStringSidToSidW(LPCWSTR StringSid, PSID* Sid)
{
    BOOL bret = FALSE;
    DWORD cBytes;

4870
    TRACE("%s, %p\n", debugstr_w(StringSid), Sid);
4871 4872
    if (GetVersion() & 0x80000000)
        SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
4873 4874
    else if (!StringSid || !Sid)
        SetLastError(ERROR_INVALID_PARAMETER);
4875 4876
    else if (ParseStringSidToSid(StringSid, NULL, &cBytes))
    {
4877
        PSID pSid = *Sid = LocalAlloc(0, cBytes);
4878 4879 4880 4881 4882

        bret = ParseStringSidToSid(StringSid, pSid, &cBytes);
        if (!bret)
            LocalFree(*Sid); 
    }
4883 4884 4885 4886 4887 4888 4889 4890 4891
    return bret;
}

/******************************************************************************
 * ConvertStringSidToSidA [ADVAPI32.@]
 */
BOOL WINAPI ConvertStringSidToSidA(LPCSTR StringSid, PSID* Sid)
{
    BOOL bret = FALSE;
4892

4893 4894 4895 4896 4897 4898 4899 4900
    TRACE("%s, %p\n", debugstr_a(StringSid), Sid);
    if (GetVersion() & 0x80000000)
        SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
    else if (!StringSid || !Sid)
        SetLastError(ERROR_INVALID_PARAMETER);
    else
    {
        UINT len = MultiByteToWideChar(CP_ACP, 0, StringSid, -1, NULL, 0);
4901
        LPWSTR wStringSid = HeapAlloc(GetProcessHeap(), 0,
4902 4903 4904 4905 4906 4907
         len * sizeof(WCHAR));

        MultiByteToWideChar(CP_ACP, 0, StringSid, -1, wStringSid, len);
        bret = ConvertStringSidToSidW(wStringSid, Sid);
        HeapFree(GetProcessHeap(), 0, wStringSid);
    }
4908 4909 4910
    return bret;
}

4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922
/******************************************************************************
 * ConvertSidToStringSidW [ADVAPI32.@]
 *
 *  format of SID string is:
 *    S-<count>-<auth>-<subauth1>-<subauth2>-<subauth3>...
 *  where
 *    <rev> is the revision of the SID encoded as decimal
 *    <auth> is the identifier authority encoded as hex
 *    <subauthN> is the subauthority id encoded as decimal
 */
BOOL WINAPI ConvertSidToStringSidW( PSID pSid, LPWSTR *pstr )
{
4923 4924
    DWORD len = 0;
    LPWSTR wstr, wptr;
4925 4926 4927

    TRACE("%p %p\n", pSid, pstr );

4928 4929
    len = 0;
    if (!DumpSidNumeric(pSid, NULL, &len))
4930
        return FALSE;
4931 4932 4933
    wstr = wptr = LocalAlloc(0, (len+1) * sizeof(WCHAR));
    DumpSidNumeric(pSid, &wptr, NULL);
    *wptr = 0;
4934

4935
    *pstr = wstr;
4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962
    return TRUE;
}

/******************************************************************************
 * ConvertSidToStringSidA [ADVAPI32.@]
 */
BOOL WINAPI ConvertSidToStringSidA(PSID pSid, LPSTR *pstr)
{
    LPWSTR wstr = NULL;
    LPSTR str;
    UINT len;

    TRACE("%p %p\n", pSid, pstr );

    if( !ConvertSidToStringSidW( pSid, &wstr ) )
        return FALSE;

    len = WideCharToMultiByte( CP_ACP, 0, wstr, -1, NULL, 0, NULL, NULL );
    str = LocalAlloc( 0, len );
    WideCharToMultiByte( CP_ACP, 0, wstr, -1, str, len, NULL, NULL );
    LocalFree( wstr );

    *pstr = str;

    return TRUE;
}

4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975
BOOL WINAPI ConvertToAutoInheritPrivateObjectSecurity(
        PSECURITY_DESCRIPTOR pdesc,
        PSECURITY_DESCRIPTOR cdesc,
        PSECURITY_DESCRIPTOR* ndesc,
        GUID* objtype,
        BOOL isdir,
        PGENERIC_MAPPING genmap )
{
    FIXME("%p %p %p %p %d %p - stub\n", pdesc, cdesc, ndesc, objtype, isdir, genmap);

    return FALSE;
}

4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009
BOOL WINAPI CreatePrivateObjectSecurity(
        PSECURITY_DESCRIPTOR ParentDescriptor,
        PSECURITY_DESCRIPTOR CreatorDescriptor,
        PSECURITY_DESCRIPTOR* NewDescriptor,
        BOOL IsDirectoryObject,
        HANDLE Token,
        PGENERIC_MAPPING GenericMapping )
{
    FIXME("%p %p %p %d %p %p - stub\n", ParentDescriptor, CreatorDescriptor,
          NewDescriptor, IsDirectoryObject, Token, GenericMapping);

    return FALSE;
}

BOOL WINAPI DestroyPrivateObjectSecurity( PSECURITY_DESCRIPTOR* ObjectDescriptor )
{
    FIXME("%p - stub\n", ObjectDescriptor);

    return TRUE;
}

BOOL WINAPI CreateProcessAsUserA(
        HANDLE hToken,
        LPCSTR lpApplicationName,
        LPSTR lpCommandLine,
        LPSECURITY_ATTRIBUTES lpProcessAttributes,
        LPSECURITY_ATTRIBUTES lpThreadAttributes,
        BOOL bInheritHandles,
        DWORD dwCreationFlags,
        LPVOID lpEnvironment,
        LPCSTR lpCurrentDirectory,
        LPSTARTUPINFOA lpStartupInfo,
        LPPROCESS_INFORMATION lpProcessInformation )
{
5010
    FIXME("%p %s %s %p %p %d 0x%08x %p %s %p %p - stub\n", hToken, debugstr_a(lpApplicationName),
5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029
          debugstr_a(lpCommandLine), lpProcessAttributes, lpThreadAttributes, bInheritHandles,
          dwCreationFlags, lpEnvironment, debugstr_a(lpCurrentDirectory), lpStartupInfo, lpProcessInformation);

    return FALSE;
}

BOOL WINAPI CreateProcessAsUserW(
        HANDLE hToken,
        LPCWSTR lpApplicationName,
        LPWSTR lpCommandLine,
        LPSECURITY_ATTRIBUTES lpProcessAttributes,
        LPSECURITY_ATTRIBUTES lpThreadAttributes,
        BOOL bInheritHandles,
        DWORD dwCreationFlags,
        LPVOID lpEnvironment,
        LPCWSTR lpCurrentDirectory,
        LPSTARTUPINFOW lpStartupInfo,
        LPPROCESS_INFORMATION lpProcessInformation )
{
5030
    FIXME("%p %s %s %p %p %d 0x%08x %p %s %p %p - semi- stub\n", hToken, 
5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048
          debugstr_w(lpApplicationName), debugstr_w(lpCommandLine), lpProcessAttributes,
          lpThreadAttributes, bInheritHandles, dwCreationFlags, lpEnvironment, 
          debugstr_w(lpCurrentDirectory), lpStartupInfo, lpProcessInformation);

    /* We should create the process with a suspended main thread */
    if (!CreateProcessW (lpApplicationName,
                         lpCommandLine,
                         lpProcessAttributes,
                         lpThreadAttributes,
                         bInheritHandles,
                         dwCreationFlags, /* CREATE_SUSPENDED */
                         lpEnvironment,
                         lpCurrentDirectory,
                         lpStartupInfo,
                         lpProcessInformation))
    {
      return FALSE;
    }
5049

5050
    return TRUE;
5051 5052
}

5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067
/******************************************************************************
 * CreateProcessWithLogonW
 */
BOOL WINAPI CreateProcessWithLogonW( LPCWSTR lpUsername, LPCWSTR lpDomain, LPCWSTR lpPassword, DWORD dwLogonFlags,
    LPCWSTR lpApplicationName, LPWSTR lpCommandLine, DWORD dwCreationFlags, LPVOID lpEnvironment,
    LPCWSTR lpCurrentDirectory, LPSTARTUPINFOW lpStartupInfo, LPPROCESS_INFORMATION lpProcessInformation )
{
    FIXME("%s %s %s 0x%08x %s %s 0x%08x %p %s %p %p stub\n", debugstr_w(lpUsername), debugstr_w(lpDomain),
    debugstr_w(lpPassword), dwLogonFlags, debugstr_w(lpApplicationName),
    debugstr_w(lpCommandLine), dwCreationFlags, lpEnvironment, debugstr_w(lpCurrentDirectory),
    lpStartupInfo, lpProcessInformation);

    return FALSE;
}

5068 5069 5070
/******************************************************************************
 * DuplicateTokenEx [ADVAPI32.@]
 */
5071 5072 5073 5074 5075 5076 5077
BOOL WINAPI DuplicateTokenEx(
        HANDLE ExistingTokenHandle, DWORD dwDesiredAccess,
        LPSECURITY_ATTRIBUTES lpTokenAttributes,
        SECURITY_IMPERSONATION_LEVEL ImpersonationLevel,
        TOKEN_TYPE TokenType,
        PHANDLE DuplicateTokenHandle )
{
5078 5079
    OBJECT_ATTRIBUTES ObjectAttributes;

5080
    TRACE("%p 0x%08x 0x%08x 0x%08x %p\n", ExistingTokenHandle, dwDesiredAccess,
5081 5082
          ImpersonationLevel, TokenType, DuplicateTokenHandle);

5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095
    InitializeObjectAttributes(
        &ObjectAttributes,
        NULL,
        (lpTokenAttributes && lpTokenAttributes->bInheritHandle) ? OBJ_INHERIT : 0,
        NULL,
        lpTokenAttributes ? lpTokenAttributes->lpSecurityDescriptor : NULL );

    return set_ntstatus( NtDuplicateToken( ExistingTokenHandle,
                                           dwDesiredAccess,
                                           &ObjectAttributes,
                                           ImpersonationLevel,
                                           TokenType,
                                           DuplicateTokenHandle ) );
5096 5097 5098 5099 5100 5101 5102
}

BOOL WINAPI DuplicateToken(
        HANDLE ExistingTokenHandle,
        SECURITY_IMPERSONATION_LEVEL ImpersonationLevel,
        PHANDLE DuplicateTokenHandle )
{
5103 5104 5105
    return DuplicateTokenEx( ExistingTokenHandle, TOKEN_IMPERSONATE | TOKEN_QUERY,
                             NULL, ImpersonationLevel, TokenImpersonation,
                             DuplicateTokenHandle );
5106 5107
}

5108 5109 5110 5111 5112
/******************************************************************************
 * ComputeStringSidSize
 */
static DWORD ComputeStringSidSize(LPCWSTR StringSid)
{
5113
    if (StringSid[0] == 'S' && StringSid[1] == '-') /* S-R-I(-S)+ */
5114 5115 5116 5117 5118 5119 5120 5121 5122
    {
        int ctok = 0;
        while (*StringSid)
        {
            if (*StringSid == '-')
                ctok++;
            StringSid++;
        }

5123 5124
        if (ctok >= 3)
            return GetSidLengthRequired(ctok - 2);
5125 5126 5127
    }
    else /* String constant format  - Only available in winxp and above */
    {
5128
        unsigned int i;
5129 5130 5131

        for (i = 0; i < sizeof(WellKnownSids)/sizeof(WellKnownSids[0]); i++)
            if (!strncmpW(WellKnownSids[i].wstr, StringSid, 2))
5132
                return GetSidLengthRequired(WellKnownSids[i].Sid.SubAuthorityCount);
5133 5134
    }

5135
    return GetSidLengthRequired(0);
5136 5137
}

5138 5139 5140 5141 5142 5143
/******************************************************************************
 * ParseStringSidToSid
 */
static BOOL ParseStringSidToSid(LPCWSTR StringSid, PSID pSid, LPDWORD cBytes)
{
    BOOL bret = FALSE;
5144
    SID* pisid=pSid;
5145

5146
    TRACE("%s, %p, %p\n", debugstr_w(StringSid), pSid, cBytes);
5147 5148 5149
    if (!StringSid)
    {
        SetLastError(ERROR_INVALID_PARAMETER);
5150
        TRACE("StringSid is NULL, returning FALSE\n");
5151
        return FALSE;
5152 5153
    }

5154 5155 5156
    while (*StringSid == ' ')
        StringSid++;

5157
    *cBytes = ComputeStringSidSize(StringSid);
5158
    if (!pisid) /* Simply compute the size */
5159 5160
    {
        TRACE("only size requested, returning TRUE\n");
5161
        return TRUE;
5162
    }
5163

5164
    if (StringSid[0] == 'S' && StringSid[1] == '-') /* S-R-I-S-S */
5165
    {
5166
        DWORD i = 0, identAuth;
5167
        DWORD csubauth = ((*cBytes - GetSidLengthRequired(0)) / sizeof(DWORD));
5168 5169

        StringSid += 2; /* Advance to Revision */
5170
        pisid->Revision = atoiW(StringSid);
5171

5172
        if (pisid->Revision != SDDL_REVISION)
5173 5174 5175 5176 5177 5178 5179 5180 5181
        {
            TRACE("Revision %d is unknown\n", pisid->Revision);
            goto lend; /* ERROR_INVALID_SID */
        }
        if (csubauth == 0)
        {
            TRACE("SubAuthorityCount is 0\n");
            goto lend; /* ERROR_INVALID_SID */
        }
5182

5183
        pisid->SubAuthorityCount = csubauth;
5184

5185
        /* Advance to identifier authority */
5186
        while (*StringSid && *StringSid != '-')
5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206
            StringSid++;
        if (*StringSid == '-')
            StringSid++;

        /* MS' implementation can't handle values greater than 2^32 - 1, so
         * we don't either; assume most significant bytes are always 0
         */
        pisid->IdentifierAuthority.Value[0] = 0;
        pisid->IdentifierAuthority.Value[1] = 0;
        identAuth = atoiW(StringSid);
        pisid->IdentifierAuthority.Value[5] = identAuth & 0xff;
        pisid->IdentifierAuthority.Value[4] = (identAuth & 0xff00) >> 8;
        pisid->IdentifierAuthority.Value[3] = (identAuth & 0xff0000) >> 16;
        pisid->IdentifierAuthority.Value[2] = (identAuth & 0xff000000) >> 24;

        /* Advance to first sub authority */
        while (*StringSid && *StringSid != '-')
            StringSid++;
        if (*StringSid == '-')
            StringSid++;
5207 5208

        while (*StringSid)
5209
        {
5210 5211
            pisid->SubAuthority[i++] = atoiW(StringSid);

5212
            while (*StringSid && *StringSid != '-')
5213
                StringSid++;
5214 5215
            if (*StringSid == '-')
                StringSid++;
5216 5217
        }

5218
        if (i != pisid->SubAuthorityCount)
5219 5220 5221 5222 5223 5224
            goto lend; /* ERROR_INVALID_SID */

        bret = TRUE;
    }
    else /* String constant format  - Only available in winxp and above */
    {
5225
        unsigned int i;
5226
        pisid->Revision = SDDL_REVISION;
5227

5228 5229 5230 5231
        for (i = 0; i < sizeof(WellKnownSids)/sizeof(WellKnownSids[0]); i++)
            if (!strncmpW(WellKnownSids[i].wstr, StringSid, 2))
            {
                DWORD j;
5232 5233 5234 5235
                pisid->SubAuthorityCount = WellKnownSids[i].Sid.SubAuthorityCount;
                pisid->IdentifierAuthority = WellKnownSids[i].Sid.IdentifierAuthority;
                for (j = 0; j < WellKnownSids[i].Sid.SubAuthorityCount; j++)
                    pisid->SubAuthority[j] = WellKnownSids[i].Sid.SubAuthority[j];
5236 5237
                bret = TRUE;
            }
5238

5239 5240
        if (!bret)
            FIXME("String constant not supported: %s\n", debugstr_wn(StringSid, 2));
5241 5242 5243 5244 5245 5246
    }

lend:
    if (!bret)
        SetLastError(ERROR_INVALID_SID);

5247
    TRACE("returning %s\n", bret ? "TRUE" : "FALSE");
5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258
    return bret;
}

/******************************************************************************
 * GetNamedSecurityInfoA [ADVAPI32.@]
 */
DWORD WINAPI GetNamedSecurityInfoA(LPSTR pObjectName,
        SE_OBJECT_TYPE ObjectType, SECURITY_INFORMATION SecurityInfo,
        PSID* ppsidOwner, PSID* ppsidGroup, PACL* ppDacl, PACL* ppSacl,
        PSECURITY_DESCRIPTOR* ppSecurityDescriptor)
{
5259 5260 5261 5262
    DWORD len;
    LPWSTR wstr = NULL;
    DWORD r;

5263
    TRACE("%s %d %d %p %p %p %p %p\n", pObjectName, ObjectType, SecurityInfo,
5264
        ppsidOwner, ppsidGroup, ppDacl, ppSacl, ppSecurityDescriptor);
5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275

    if( pObjectName )
    {
        len = MultiByteToWideChar( CP_ACP, 0, pObjectName, -1, NULL, 0 );
        wstr = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR));
        MultiByteToWideChar( CP_ACP, 0, pObjectName, -1, wstr, len );
    }

    r = GetNamedSecurityInfoW( wstr, ObjectType, SecurityInfo, ppsidOwner,
                           ppsidGroup, ppDacl, ppSacl, ppSecurityDescriptor );

5276
    HeapFree( GetProcessHeap(), 0, wstr );
5277 5278

    return r;
5279 5280 5281 5282 5283
}

/******************************************************************************
 * GetNamedSecurityInfoW [ADVAPI32.@]
 */
5284 5285 5286
DWORD WINAPI GetNamedSecurityInfoW( LPWSTR name, SE_OBJECT_TYPE type,
    SECURITY_INFORMATION info, PSID* owner, PSID* group, PACL* dacl,
    PACL* sacl, PSECURITY_DESCRIPTOR* descriptor )
5287
{
5288
    DWORD needed, offset;
5289
    SECURITY_DESCRIPTOR_RELATIVE *relative = NULL;
5290 5291
    BYTE *buffer;

5292
    TRACE( "%s %d %d %p %p %p %p %p\n", debugstr_w(name), type, info, owner,
5293 5294
           group, dacl, sacl, descriptor );

5295 5296
    /* A NULL descriptor is allowed if any one of the other pointers is not NULL */
    if (!name || !(owner||group||dacl||sacl||descriptor) ) return ERROR_INVALID_PARAMETER;
5297

5298 5299 5300 5301 5302 5303 5304 5305 5306
    /* If no descriptor, we have to check that there's a pointer for the requested information */
    if( !descriptor && (
        ((info & OWNER_SECURITY_INFORMATION) && !owner)
    ||  ((info & GROUP_SECURITY_INFORMATION) && !group)
    ||  ((info & DACL_SECURITY_INFORMATION)  && !dacl)
    ||  ((info & SACL_SECURITY_INFORMATION)  && !sacl)  ))
        return ERROR_INVALID_PARAMETER;

    needed = !descriptor ? 0 : sizeof(SECURITY_DESCRIPTOR_RELATIVE);
5307 5308 5309 5310 5311 5312 5313 5314 5315
    if (info & OWNER_SECURITY_INFORMATION)
        needed += sizeof(sidWorld);
    if (info & GROUP_SECURITY_INFORMATION)
        needed += sizeof(sidWorld);
    if (info & DACL_SECURITY_INFORMATION)
        needed += WINE_SIZE_OF_WORLD_ACCESS_ACL;
    if (info & SACL_SECURITY_INFORMATION)
        needed += WINE_SIZE_OF_WORLD_ACCESS_ACL;

5316 5317 5318 5319 5320
    if(descriptor)
    {
        /* must be freed by caller */
        *descriptor = HeapAlloc( GetProcessHeap(), 0, needed );
        if (!*descriptor) return ERROR_NOT_ENOUGH_MEMORY;
5321

5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334
        if (!InitializeSecurityDescriptor( *descriptor, SECURITY_DESCRIPTOR_REVISION ))
        {
            HeapFree( GetProcessHeap(), 0, *descriptor );
            return ERROR_INVALID_SECURITY_DESCR;
        }

        relative = *descriptor;
        relative->Control |= SE_SELF_RELATIVE;

        buffer = (BYTE *)relative;
        offset = sizeof(SECURITY_DESCRIPTOR_RELATIVE);
    }
    else
5335
    {
5336 5337 5338
        buffer = HeapAlloc( GetProcessHeap(), 0, needed );
        if (!buffer) return ERROR_NOT_ENOUGH_MEMORY;
        offset = 0;
5339 5340
    }

5341
    if (info & OWNER_SECURITY_INFORMATION)
5342 5343
    {
        memcpy( buffer + offset, &sidWorld, sizeof(sidWorld) );
5344 5345
        if(relative)
            relative->Owner = offset;
5346 5347
        if (owner)
            *owner = buffer + offset;
5348 5349
        offset += sizeof(sidWorld);
    }
5350
    if (info & GROUP_SECURITY_INFORMATION)
5351 5352
    {
        memcpy( buffer + offset, &sidWorld, sizeof(sidWorld) );
5353 5354
        if(relative)
            relative->Group = offset;
5355 5356
        if (group)
            *group = buffer + offset;
5357 5358
        offset += sizeof(sidWorld);
    }
5359
    if (info & DACL_SECURITY_INFORMATION)
5360 5361
    {
        GetWorldAccessACL( (PACL)(buffer + offset) );
5362 5363 5364 5365 5366
        if(relative)
        {
            relative->Control |= SE_DACL_PRESENT;
            relative->Dacl = offset;
        }
5367 5368
        if (dacl)
            *dacl = (PACL)(buffer + offset);
5369 5370
        offset += WINE_SIZE_OF_WORLD_ACCESS_ACL;
    }
5371
    if (info & SACL_SECURITY_INFORMATION)
5372 5373
    {
        GetWorldAccessACL( (PACL)(buffer + offset) );
5374 5375 5376 5377 5378
        if(relative)
        {
            relative->Control |= SE_SACL_PRESENT;
            relative->Sacl = offset;
        }
5379 5380
        if (sacl)
            *sacl = (PACL)(buffer + offset);
5381
    }
5382

5383
    return ERROR_SUCCESS;
5384
}
5385 5386 5387 5388 5389 5390

/******************************************************************************
 * DecryptFileW [ADVAPI32.@]
 */
BOOL WINAPI DecryptFileW(LPCWSTR lpFileName, DWORD dwReserved)
{
5391
    FIXME("%s %08x\n", debugstr_w(lpFileName), dwReserved);
5392 5393 5394 5395 5396 5397 5398 5399
    return TRUE;
}

/******************************************************************************
 * DecryptFileA [ADVAPI32.@]
 */
BOOL WINAPI DecryptFileA(LPCSTR lpFileName, DWORD dwReserved)
{
5400
    FIXME("%s %08x\n", debugstr_a(lpFileName), dwReserved);
5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420
    return TRUE;
}

/******************************************************************************
 * EncryptFileW [ADVAPI32.@]
 */
BOOL WINAPI EncryptFileW(LPCWSTR lpFileName)
{
    FIXME("%s\n", debugstr_w(lpFileName));
    return TRUE;
}

/******************************************************************************
 * EncryptFileA [ADVAPI32.@]
 */
BOOL WINAPI EncryptFileA(LPCSTR lpFileName)
{
    FIXME("%s\n", debugstr_a(lpFileName));
    return TRUE;
}
5421

5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445
/******************************************************************************
 * FileEncryptionStatusW [ADVAPI32.@]
 */
BOOL WINAPI FileEncryptionStatusW(LPCWSTR lpFileName, LPDWORD lpStatus)
{
    FIXME("(%s %p): stub\n", debugstr_w(lpFileName), lpStatus);
    if (!lpStatus)
        return FALSE;
    *lpStatus = FILE_SYSTEM_NOT_SUPPORT;
    return TRUE;
}

/******************************************************************************
 * FileEncryptionStatusA [ADVAPI32.@]
 */
BOOL WINAPI FileEncryptionStatusA(LPCSTR lpFileName, LPDWORD lpStatus)
{
    FIXME("(%s %p): stub\n", debugstr_a(lpFileName), lpStatus);
    if (!lpStatus)
        return FALSE;
    *lpStatus = FILE_SYSTEM_NOT_SUPPORT;
    return TRUE;
}

5446 5447 5448
/******************************************************************************
 * SetSecurityInfo [ADVAPI32.@]
 */
5449
DWORD WINAPI SetSecurityInfo(HANDLE handle, SE_OBJECT_TYPE ObjectType, 
5450 5451 5452 5453 5454
                      SECURITY_INFORMATION SecurityInfo, PSID psidOwner,
                      PSID psidGroup, PACL pDacl, PACL pSacl) {
    FIXME("stub\n");
    return ERROR_SUCCESS;
}
5455 5456 5457 5458 5459 5460 5461 5462

/******************************************************************************
 * SaferCreateLevel   [ADVAPI32.@]
 */
BOOL WINAPI SaferCreateLevel(DWORD ScopeId, DWORD LevelId, DWORD OpenFlags,
                             SAFER_LEVEL_HANDLE* LevelHandle, LPVOID lpReserved)
{
    FIXME("(%u, %x, %u, %p, %p) stub\n", ScopeId, LevelId, OpenFlags, LevelHandle, lpReserved);
5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486

    *LevelHandle = (SAFER_LEVEL_HANDLE)0xdeadbeef;
    return TRUE;
}

/******************************************************************************
 * SaferComputeTokenFromLevel   [ADVAPI32.@]
 */
BOOL WINAPI SaferComputeTokenFromLevel(SAFER_LEVEL_HANDLE handle, HANDLE token, PHANDLE access_token,
                                       DWORD flags, LPVOID reserved)
{
    FIXME("(%p, %p, %p, %x, %p) stub\n", handle, token, access_token, flags, reserved);

    *access_token = (HANDLE)0xdeadbeef;
    return TRUE;
}

/******************************************************************************
 * SaferCloseLevel   [ADVAPI32.@]
 */
BOOL WINAPI SaferCloseLevel(SAFER_LEVEL_HANDLE handle)
{
    FIXME("(%p) stub\n", handle);
    return TRUE;
5487
}
5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500

DWORD WINAPI TreeResetNamedSecurityInfoW( LPWSTR pObjectName,
                SE_OBJECT_TYPE ObjectType, SECURITY_INFORMATION SecurityInfo,
                PSID pOwner, PSID pGroup, PACL pDacl, PACL pSacl,
                BOOL KeepExplicit, FN_PROGRESS fnProgress,
                PROG_INVOKE_SETTING ProgressInvokeSetting, PVOID Args)
{
    FIXME("(%s, %i, %i, %p, %p, %p, %p, %i, %p, %i, %p  Stub\n",
        debugstr_w(pObjectName), ObjectType, SecurityInfo, pOwner, pGroup,
        pDacl, pSacl, KeepExplicit, fnProgress, ProgressInvokeSetting, Args);

    return ERROR_SUCCESS;
}
5501 5502 5503 5504 5505 5506 5507 5508 5509 5510

/******************************************************************************
 * SaferGetPolicyInformation   [ADVAPI32.@]
 */
BOOL WINAPI SaferGetPolicyInformation(DWORD scope, SAFER_POLICY_INFO_CLASS class, DWORD size,
                                      PVOID buffer, PDWORD required, LPVOID lpReserved)
{
    FIXME("(%u %u %u %p %p %p) stub\n", scope, class, size, buffer, required, lpReserved);
    return FALSE;
}