forum.vdsworld.com Forum Index forum.vdsworld.com
Visit VDSWORLD.com
 
 FAQFAQ   SearchSearch   MemberlistMemberlist   UsergroupsUsergroups   RegisterRegister 
 ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 


run as
Goto page 1, 2  Next
 
Post new topic   Reply to topic    forum.vdsworld.com Forum Index -> General Help
View previous topic :: View next topic  
Author Message
bornsoft
Contributor
Contributor


Joined: 19 Feb 2009
Posts: 113
Location: Germany

PostPosted: Mon Feb 22, 2010 9:07 pm    Post subject: Reply with quote

hello everybody,

i know this thread is a little older but i'd be interested if this solution is working on Vista and Win7 too.

What I'm planning to do is to let the user which downloads my proggies decide if he takes a runtime-integrated exe or to copy the runtime dll to the system path. Therefore i made a little tool - that needs admin-access of course.

By the way, whats the best way i can let the program test if the logged in user has admin-rights?

I thought about writing to Reg.Local or to save a dummy file to sysdir: and then test if it's there but then i read about virtualization somewere here and if i understood right, this would give false positive results.

greetings

marcus
Back to top
View user's profile Send private message Visit poster's website
Aslan
Valued Contributor
Valued Contributor


Joined: 31 May 2001
Posts: 589
Location: Memphis, TN USA

PostPosted: Tue Feb 23, 2010 12:17 am    Post subject: Reply with quote

This will check for Admin rights on VDS5 or 6

Code:
REM Check if user has admin rights
 LOADLIB advpack.dll
  %x = @lib(advpack.dll,IsNTAdmin,BOOL:,0,0)
 FREELIB advpack.dll
 If @unequal(%x,1)
  warn This application requires administrator rights to run!@cr()@cr()The application will now close.
  exit
 end


In VDS6 if you specify "RequireAdministrator" in the "Application Manifest" settings of your project, it will not run without admin rights. I can't remember if VDS 5 has this option.

I have yet to see the runas script work as advertised and I don't think it's an option in Vista or Win7.
Back to top
View user's profile Send private message Send e-mail
bornsoft
Contributor
Contributor


Joined: 19 Feb 2009
Posts: 113
Location: Germany

PostPosted: Tue Feb 23, 2010 3:24 am    Post subject: Reply with quote

thank you aslan,

what i found about advpack.dll seems that it is part of the .net framwork 2.0, so i'm not sure if this api-function is available on machines that have not installed the .net framework.?

i know about the "require administrator-manifest-thing" but i would not like to see the users beeing asked for admin-privileges before they not even see the program-window itself to read the reason for this query. thats why i was interested in CodeScripts solution to elevate priviliges if the program is already running.

Probably the most vista- and 7 users are that much annoyed about the amount of requests for higher privilegs that they turned off their UAC anyway Wink

I just wanted to make a very little tool for unexperienced users to just copy the vds-runtime to the system-dir that they dont have to download a one-megabyte-exe for every under-10-kilobyte-commandline-tool i wrote, but this seems to become a hard job on the new windows-versions ...
Back to top
View user's profile Send private message Visit poster's website
Aslan
Valued Contributor
Valued Contributor


Joined: 31 May 2001
Posts: 589
Location: Memphis, TN USA

PostPosted: Tue Feb 23, 2010 4:27 am    Post subject: Reply with quote

I've use advpack.dll since XP so it shouldn't be a problem. I believe it's installed with the OS.

Even when it works, runas will still ask the user for a password. The only utility that I have found works is CPAU (Google it) not for Vista and up though.

bornsoft wrote:
i know about the "require administrator-manifest-thing" but i would not like to see the users beeing asked for admin-privileges before they not even see the program-window itself to read the reason for this query..
How will they see your app without the runtime? Either way you will probably still have to include it. Maybe you could just create a runtime installer that the user could choose to install if they want smaller downloads in the future.

As annoying as UAC is, Users that turn it off are seriously jeopardizing security. I can't tell you how many times a client tells me "I don't know how that spyware or key-logger got on my PC". I seldom get calls from Users that leave it turned on.

Although, I do make a lot of money fixing their issues. Wink
Back to top
View user's profile Send private message Send e-mail
bornsoft
Contributor
Contributor


Joined: 19 Feb 2009
Posts: 113
Location: Germany

PostPosted: Tue Feb 23, 2010 5:09 am    Post subject: Reply with quote

Of course the runtime-installer contains the runtime, i have two versions - 1.) a zip-file containing the installer and the runtime and 2.) an integrated exe that writes the runtime from a resource to disk.

After the user is prepared that the runtime needs to be saved to the system-dir, i have no problem if UAC asks for admin-pass.

I know about the intention of UAC, but i guess that many unexperienced users turn it off.

But not only for this program - for most of what i'll write in the future i need to deal with UAC. So I need to find a way to elevate privilegs for certain parts of code and don't want my programs starting every time with a security-warning.
Back to top
View user's profile Send private message Visit poster's website
PGWARE
Web Host


Joined: 29 Dec 2001
Posts: 1565

PostPosted: Tue Feb 23, 2010 6:57 am    Post subject: Reply with quote

I've split these replies into a new post.

Quote:
Probably the most vista- and 7 users are that much annoyed about the amount of requests for higher privilegs that they turned off their UAC anyway



UAC is actually very useful and most users dont either know how to turn it off or just dont bother, it is a security mechanism to help protect the system from malware taking over the system and prevents elevated exes from running at start up - something malware does often. UAC prompts typically only happen when you are changing system level information/data. I have UAC on and don't get UAC prompts that often, in fact its very rare. Don't assume users have turned off UAC, especially if you feel they dont bother installing .NET, installing a Windows update (.net) is much easier than going into the control panel and actively turning off UAC.


The only way to elevate a user up is through UAC if UAC is enabled which means using a manifest file.

You should follow the Windows guidelines, if you want to copy a file to the system you should prompt with a UAC. The reason many XP applications have problems running under Vista/7 is because many developers decided not to follow the windows developer guidelines and assume the logged in user is running in administrator user mode. UAC is not a bother, I find it very informative if an application needs system access and I know that program may have changed something in the system directories or the registry.


VDS doesnt have the ability to have tasks run elevated during runtime - you have to include a manifest and make the entire exe elevated at the beggining. In Delphi you can write your app so it is running under low security rights then when a user clicks a button or you need elevation you request it with a UAC prompt. It requires COM which is something VDS can't do, you can prompt anytime and it then elevates the entire running exe.

One way to achieve and simulate this in vds is include an elevated exe inside of your non-elevated exe, you can have the user click a button to 'copy vdsrun50/vdsrun60.dll to the system. Extract the elevated exe and then run it, the uac prompt will appear and you can write the dll to the system from inside the elevated exe. In fact this is one method recommeded by Microsoft. Your main application runs non-elevated and you have several smaller exe's included with your program each which requires elevation and is only run when needed.

This method allows your user to run your exe without having to elevate at start of your program, but then click a button to allow it to run the elevated exe.

You can use the Windows api:

SendMessage(Handle, BCM_SETSHIELD, 0, 1);

Handle can be @win(~BUTTON1) or the name of the button.
replace BCM_SETSHIELD with $160C

That puts a UAC shield icon on the button letting the user know it requires elevation. Thats just to show the user elevation is needed (visual), it doesnt do any elevation. You see this shield icon in many parts of Windows control panel/settings to show that the action requires elevation. Microsoft recommends using this method of painting a button, this allows your app to always use the current shield icon. The shield icon appearance changed in Windows 7 from the way it looked in Vista and this api allows your app to always use the current image built into Windows. This api is also backwards compatible, in older versions of Windows it doesnt change the appearance of the button at all.

%A = @sendmsg(@winexists(~BUTTON1), @sum($1600, $000C), 0)



> User runs non-elevated exe
> User clicks button to 'extract runtime to system'
> Your program extracts an embedded elevated exe to windows/temp dir
> Your program runs elevated exe (use run with WAIT)
> Elevated exe prompts user with UAC
> Elevated exe extracts runtime dll to system dir
> Elevated exe notifies user the dll has been copied with a dialog box, after user clicks OK the exe closes down.
> Your non-elevated program then deletes elevated exe from windows/temp folder.


To be honest this UAC system has made it much easier for developers not harder, because now you know every user runs as a limited user and requires elevation for system writes. Under XP and others some users could be limited accounts or system accounts, you cant assume and you have to check if the user logged in is an admin under XP and lower. In Vista/7 you simply include a manifest in your elevated exe and if the user requires elevation it shows the UAC or it doesnt (Windows 2008 doesnt show the UAC).


Last edited by PGWARE on Tue Feb 23, 2010 8:10 am; edited 9 times in total
Back to top
View user's profile Send private message
PGWARE
Web Host


Joined: 29 Dec 2001
Posts: 1565

PostPosted: Tue Feb 23, 2010 7:29 am    Post subject: Reply with quote

Anyone that is willing to translate this code into vds or gadgetx please feel free, it is a delphi function to determine if the user logged into windows is in the administrators group.

Code:

function IsAdmin: Boolean;
var
  hAccessToken: THandle;
  ptgGroups: PTokenGroups;
  dwInfoBufferSize: DWORD;
  psidAdministrators: PSID;
  x: Integer;
  bSuccess: BOOL;
begin
  try
    Result := False;
    bSuccess := OpenThreadToken(GetCurrentThread, TOKEN_QUERY, True, hAccessToken);
    if (not(bSuccess)) then
    begin
      if (GetLastError = ERROR_NO_TOKEN) then
      bSuccess := OpenProcessToken(GetCurrentProcess, TOKEN_QUERY, hAccessToken);
    end;
    if (bSuccess) then
    begin
      GetMem(ptgGroups, 1024);
      bSuccess := GetTokenInformation(hAccessToken, TokenGroups, ptgGroups, 1024, dwInfoBufferSize);
      CloseHandle(hAccessToken);
      if (bSuccess) then
      begin
        AllocateAndInitializeSid(SECURITY_NT_AUTHORITY, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, psidAdministrators);
        {$R-}
        for x := 0 to ptgGroups.GroupCount - 1 do
          if (EqualSid(psidAdministrators, ptgGroups.Groups[x].Sid)) then
          begin
            Result := True;
            Break;
          end;
        {$R+}
        FreeSid(psidAdministrators);
      end;
      FreeMem(ptgGroups);
    end;
  except
    Result := False;
  end;
end;


*update* This actually checks if the exe/process running is running under administrator privileges not if the user logged in is an admin.


Last edited by PGWARE on Tue Feb 23, 2010 11:40 pm; edited 1 time in total
Back to top
View user's profile Send private message
vdsalchemist
Admin Team


Joined: 23 Oct 2001
Posts: 1448
Location: Florida, USA

PostPosted: Tue Feb 23, 2010 5:19 pm    Post subject: Reply with quote

Here ya go have fun.

Code:


#DEFINE FUNCTION,IsAdmin
#DEFINE COMMAND,RUNASADMIN

%%cmdline = @CmdLine()
If @Equal(@Pos(runasadmin,%%cmdline),0)
  If @IsAdmin()
    Info Drop through and run your application
  Else
    If @Ask(Would you like to run this program as administrator?)
      RunAsAdmin %0
    End
  End
End


stop

:IsAdmin
  # %R will be hold the return
  %R =
 
  # Fixed at this size for comfort. Could be bigger or made dynamic.
  %%ANYSIZE_ARRAY = 100
 
  # Security APIs
  %%TokenUser = 1
  %%TokenGroups = 2
  %%TokenPrivileges = 3
  %%TokenOwner = 4
  %%TokenPrimaryGroup = 5
  %%TokenDefaultDacl = 6
  %%TokenSource = 7
  %%TokenType = 8
  %%TokenImpersonationLevel = 9
  %%TokenStatistics = 10
 
  # Token Specific Access Rights
  %%TOKEN_ASSIGN_PRIMARY = $1
  %%TOKEN_DUPLICATE = $2
  %%TOKEN_IMPERSONATE = $4
  %%TOKEN_QUERY = $8
  %%TOKEN_QUERY_SOURCE = $10
  %%TOKEN_ADJUST_PRIVILEGES = $20
  %%TOKEN_ADJUST_GROUPS = $40
  %%TOKEN_ADJUST_DEFAULT = $80
 
  # NT well-known SIDs
  %%SECURITY_DIALUP_RID = $1
  %%SECURITY_NETWORK_RID = $2
  %%SECURITY_BATCH_RID = $3
  %%SECURITY_INTERACTIVE_RID = $4
  %%SECURITY_SERVICE_RID = $6
  %%SECURITY_ANONYMOUS_LOGON_RID = $7
  %%SECURITY_LOGON_IDS_RID = $5
  %%SECURITY_LOCAL_SYSTEM_RID = $12
  %%SECURITY_NT_NON_UNIQUE = $15
  %%SECURITY_BUILTIN_DOMAIN_RID = $20
 
  # Well-known domain relative sub-authority values (RIDs)
  %%DOMAIN_ALIAS_RID_ADMINS = $220
  %%DOMAIN_ALIAS_RID_USERS = $221
  %%DOMAIN_ALIAS_RID_GUESTS = $222
  %%DOMAIN_ALIAS_RID_POWER_USERS = $223
  %%DOMAIN_ALIAS_RID_ACCOUNT_OPS = $224
  %%DOMAIN_ALIAS_RID_SYSTEM_OPS = $225
  %%DOMAIN_ALIAS_RID_PRINT_OPS = $226
  %%DOMAIN_ALIAS_RID_BACKUP_OPS = $227
  %%DOMAIN_ALIAS_RID_REPLICATOR = $228
 
  %%SECURITY_NT_AUTHORITY = $5
 
  %%SID_AND_ATTRIBUTES = @BINARY(DWORD,0)@BINARY(DWORD,0)
  %%TOKEN_GROUPS = @BINARY(DWORD,0)@FILL(@SUM(%%ANYSIZE_ARRY,@LEN(%%SID_AND_ATTRIBUTES)),,Z)
  %%SID_IDENTIFIER_AUTHORITY = @BINARY(BYTE,0)@BINARY(BYTE,0)@BINARY(BYTE,0)@BINARY(BYTE,0)@BINARY(BYTE,0)@BINARY(BYTE,%%SECURITY_NT_AUTHORITY)
 
  LoadLib advapi32.dll
  LoadLib kernel32.dll
  %p = @BINARY(DWORD,0)
  %b = @BINARY(DWORD,0)
  %%Ret = @lib(advapi32,OpenThreadToken,BOOL:,INT:@lib(kernel32,GetCurrentThread,INT:,NIL:),INT:%%TOKEN_QUERY,BOOL:True,INT:@addr("%p"))
  If @Not(%%Ret)
    %%Ret = @lib(advapi32,OpenProcessToken,BOOL:,INT:@lib(kernel32,GetCurrentProcess,INT:,NIL:),INT:%%TOKEN_QUERY,INT:@addr("%p"))
  End
  If %%Ret
     %p = @val(@substr(%p,1,4))
    %%RetVal = @lib(advapi32,GetTokenInformation,BOOL:,INT:%p,INT:%%TokenGroups,INT:0,INT:0,INT:@addr("%b"))
    %%InfoBufferSize = @val(@substr(%b,1,4))
      # Info p is %p@CR()b is %B
    If @Greater(%%InfoBufferSize,0)
        %I = @fill(%%InfoBufferSize,,Z)
        %%RetVal = @lib(advapi32,GetTokenInformation,BOOL:,INT:%p,INT:%%TokenGroups,INT:@Addr("%I"),INT:%%InfoBufferSize,INT:@addr("%b"))
         If %%RetVal
           %N = @BINARY(BYTE,0)@BINARY(BYTE,0)@BINARY(BYTE,0)@BINARY(BYTE,0)@BINARY(BYTE,0)@BINARY(BYTE,%%SECURITY_NT_AUTHORITY)
            %A = @BINARY(DWORD,0)
           %%Ret1 = @lib(advapi32,AllocateAndInitializeSid,BOOL:,INT:@Addr("%N"),INT:2,INT:%%SECURITY_BUILTIN_DOMAIN_RID,INT:%%DOMAIN_ALIAS_RID_ADMINS,INT:0,INT:0,INT:0,INT:0,INT:0,INT:0,INT:@addr("%A"))
            If %%Ret1
              %%AdminSid = @val(@substr(%A,1,4))
              # loop through your token sid pointers to determine if they match the Admin sid
               %%count = @val(@substr(%I,1,4))
               %g = @substr(%I,5,8)
               %%cnt = 1
          %%startpos = 5
               Repeat
                 %%endpos = @sum(%%startpos,4)
                  %s = @substr(%I,%%startpos,@pred(%%endpos))
                  If @lib(advapi32,EqualSid,BOOL:,INT:@val(%s),INT:@val(%a))
                     %R = 1
                  End
                  %%startpos = @sum(%%endpos,4)
                  %%cnt = @succ(%%cnt)
               Until @Equal(%%cnt,%%count)
            End
         End
         %%Ret = @lib(advapi32,FreeSid,BOOL:,INT:@ADDR("%A"))
    End
      
    %%Ret = @lib(kernel32,CloseHandle,INT:,INT:%p)
  End
   FreeLib advapi32
   FreeLib kernel32
Exit %R

:RUNASADMIN
  shell runas,@chr(34)%1@chr(34),runasadmin,@chr(34)@Path(%1)@chr(34)
Exit


YMMV but I think this is working as the delphi code that PGWARE posted.

***UPDATED*** fixed some things that would have caused it to pass reguardless... Also I was not freeing the DLL's.

***UPDATED AGAIN *** For those trying to run your program elevated I have added something when the script above detects that the user is in the Administrators group it will try to run the application as admin. This is using the shell so it is going to ask everytime the user launches the application. On XP this prompts the user for an admin account to run the application under.

***UPDATED*** This update is for PGWARE he suggested that the runasadmin command should be if the current user is not an admin and you want your program to prompt the user to login as admin. For most programs I agree this would be the normal way however use your own judgment and determine how you want your program to manage the user access.

_________________
Home of

Give VDS a new purpose!


Last edited by vdsalchemist on Wed Feb 24, 2010 2:32 am; edited 3 times in total
Back to top
View user's profile Send private message Visit poster's website AIM Address Yahoo Messenger MSN Messenger
bornsoft
Contributor
Contributor


Joined: 19 Feb 2009
Posts: 113
Location: Germany

PostPosted: Tue Feb 23, 2010 7:32 pm    Post subject: Reply with quote

first thank you all,

@ PGWARE:

Of course you are right - my words about users who turn off UAC were not meant that much serious - thats why the smilie is there.

I like your idea to externalize the code that's doing the "hard stuff" and thanks for the BCM_SETSHIELD message.
(BTW where do you get the hex-codes for the api constants from? I know your "API Constant Reference" program - a reverse lookup to get the names from the hex-code would be great)

I can not test on Vista or 7 at the moment - so my question is:

What happens in the case the user has no admin-password? - Will the externalized program not run or will it produce an error?

@ vdsalchemist, @ PGWARE

What is the advantage of the IsAdmin function compared with the very short IsNTAdmin code that Aslan posted above?
Back to top
View user's profile Send private message Visit poster's website
vdsalchemist
Admin Team


Joined: 23 Oct 2001
Posts: 1448
Location: Florida, USA

PostPosted: Tue Feb 23, 2010 7:42 pm    Post subject: Reply with quote

Bornsoft,
I have seen posts that the IsNTAdmin function does not work under Vista and Windows 7. However that does not mean that it does not you could try it.

_________________
Home of

Give VDS a new purpose!
Back to top
View user's profile Send private message Visit poster's website AIM Address Yahoo Messenger MSN Messenger
bornsoft
Contributor
Contributor


Joined: 19 Feb 2009
Posts: 113
Location: Germany

PostPosted: Tue Feb 23, 2010 8:16 pm    Post subject: Reply with quote

If I understood PGWARE right, it is not nessesary to test for admin rights on Vista or Win7 because you need elevation to make system-changes anyway. Correct me if i'm wrong.
Back to top
View user's profile Send private message Visit poster's website
vdsalchemist
Admin Team


Joined: 23 Oct 2001
Posts: 1448
Location: Florida, USA

PostPosted: Tue Feb 23, 2010 8:32 pm    Post subject: Reply with quote

That is correct however your application does not know if the current user is capable of running as Administrator or does the user need to login as an admin. This is just a convience for the user. Lets say you as the user have 2 accounts. A admin account and a regular user account. Now you launch ABC.exe which has no knowledge of UAC what would ABC.exe do? Most likely it would not run. However if ABC.exe checks to user account to see if it is a administrator account then it can elevate itself by running with admin privileges or request the user to login with an administrator account. Really this is just to make things easy on the user so they don't keep trying to run a program that will fail just due to privileges. The reason PGWARE said it this way is because it makes your life easier. You can assume that your application is initially launched as a regular user then take steps to make the user launch the application with an account that has the rights to do what your program is wanting to do. Really you should try to build your applications where they do not need admin rights and can run happy without them. Wink
_________________
Home of

Give VDS a new purpose!
Back to top
View user's profile Send private message Visit poster's website AIM Address Yahoo Messenger MSN Messenger
PGWARE
Web Host


Joined: 29 Dec 2001
Posts: 1565

PostPosted: Tue Feb 23, 2010 9:31 pm    Post subject: Reply with quote

What vista/7 does is it just shows a UAC prompt asking if I want to run the program, I click YES or NO, if I click no it just closes and no program is opened, if I click YES it launches the program and runs in admin mode. No password box is ever shown if you are an admin user and uac prompt is shown - vista/7 recognize you are an admin so doesnt need the password. If you setup a standard user account it will ask for an admin username/password before it can elevate the exe (note I said an admin user/pass not the current users password - it must be the username/password for an ADMIN on the machine). While you can setup both as an admin and standard user account - both run in a limited access mode where system level changes cannot be made until elevation occurs which requires administrator approval.

Now the reason for the IsAdmin function is because I assume you plan to use this same program on Windows 2003 and XP, both of which need to know if the user running is an admin or not. While most times the user account is an admin in many cases it is not - for instance at a work place or school they may run XP but as a limited user account. Now you can see why Vista/7 uac is a better process, it automatically does the detection of account level and prompts for you. It's a unifed and very recognizable feature in Vista/7 - either the user can give permission to run the elevated code or nothing runs; thats pretty cut and clear for the enduser and lets them know why the program cannot continue on. It's actually a blessing for developers, in Windows XP if you cryptically just asked the user for the admin user/pass they might wonder wtf is going on. It's accepted in Vista/7 that UAC will prompt you if certain permissions are required - so while MS get's flack for this it does it's purpose. vdsalchemist rebuilt that delphi code to work in vds and he included the runas command which is pretty much like a UAC in that it elevates the code up to a user account that is capable of running the code - this should be used in Windows 2000, 2003, XP.


You don't really need to run the IsAdmin function in Vista or 7, its up to you but I suggest you do theres a certain case that you have to still check - its why I recommend DO NOT TURN OFF UAC.

*here is why you may need to run IsAdmin in 7/Vista* - You could run into the problem where someone is running Vista/7 and has turned UAC off and they are using a limited user account. This means no UAC prompt is shown to allow them to elevate up and the code simply wont run properly; it will execute the exe but the exe will be restricted from copying files to system dir or writing to hkey_local registry. Microsoft should never have allowed turning off the UAC for this reason. But here is where you have to assume a little - anyone that was 'smart' enough to turn off UAC likely is running as an admin anyway - the XP diehards. If the user is running as an admin with UAC off the program will work correctly. You should include the IsAdmin function inside your elevated exe to make sure it is in fact running elevated; put it at the top of your code; if the code is not running as an admin then display a messagebox to warn them they need to run the program as an administrator. Or better yet load this page into their browser http://blogs.technet.com/mcs-ireland-infrastructure/archive/2008/03/07/vista-uac-should-i-turn-it-off.aspx and tell them to stop trying to fix what isn't broken.

*update* - I have tested this, under Windows Vista if you have UAC off and are running as a limited user no uac prompt appears and the application runs without the proper rights to write to registry/system files. Under Windows 7 Microsoft changed this behavior, even if UAC is turned off the UAC prompts still appear for limited users to allow them to elevate up when programs require it.



The IsAdmin function is a little different in that it doesnt just check if the current logged in user to the computer is an admin; it actually checks the program process you are running is running under which user account type - as an administrator or not. This is checking the process of the program running and checks it's security token to see what level of user access it is allowed - either an admin level or not. Now I'm not sure but I believe the other function simply checks if the logged in user to the computer is within the adminstrators group or not; that is not what you want because in Vista/7 you can be a limited user account and then elevate up the current app as an admin - that function would still report the user logged in as not an admin but it would not tell you that the program running is actually running as an admin. IsAdmin function does since it loads the security token of the program process.

*update* - it appears impersonation of the admin user in fact does load the registry hive/settings of the admin so as noted later in this post/thread you can obtain if an admin is logged in using the registry.


A way to communicate between your non elevated exe and the elevated one to be sure the elevated exe did it's job is:

You can do something like write the runtime dll to the windows/temp before you launch the elevated program, then when the elevated exe runs it can copy the runtime to system dir and remove it from the windows/temp. That allows some basic communicate between the elevated exe and non-elevated one to acknowledge that the elevated exe ran and did its job, obviously if the runtime file still exists in windows/temp after the uac is closed that means the user did not have the rights to run the elevated exe or they chose not to run it. You can then warn with a message box letting them know the dll files were not written to disk. You certainly could use any other method where two apps can communicate like a shared ini file writing values to acknowledge the process has completed (do not use windows messages sent to window handles - elevated exe and non elevated cannot communicate bidirectional; only the elevated exe can send messages to elevated/nonelevated windows.). Also dont use hkey_local registry as it wont work at all since non elevated exe's cant write to it. *note* when I say windows/temp that really should be the users temporary directory - in early versions of Windows that was just the windows/temp dir but in Vista/7 its a different location.

vdsalchemist - is correct; you should try to run under a restricted user account as much as possible. Only elevate when needed by running a separate elevated exe launched from the non elevated one. I have a few apps that currently elevate on start of the program and I intend to fix them asap because it's just the wrong way to run a program. Most users should be cautious when running any program and seeing a UAC immediately before they even see the program; which you also did not want to do. This simply wasnt possible in XP under an admin account - once you ran the exe it did whatever it wanted to to destroy your OS; in vista/7 if you dont fully trust the exe and it immediately prompts for uac you can tell it NO and no harm done. This method should be the one you follow and it's absolutely recommended by Microsoft.


Of course a much easier method than all this madness is by using an installer program Smile But all of the methods described above still apply to Vista/7 since you still need to make sure the program running is under admin access rights at times when you need to make system changes.



-----

Heres some vista guidelines I wrote a few years back: http://forum.vdsworld.com/viewtopic.php?t=4082&highlight=vista

I wrote ways to bypass some security levels in there too, be very careful when using these, if you change the ACL permissions on a directory or registry make sure you do so keeping in mind of security. Don't change ACL's without knowing what you are doing and the security implications. Never change the ACL on an entire directory or any directory that has .exe's in it as it allows anyone to swap the exes in there.


Last edited by PGWARE on Wed Feb 24, 2010 1:34 am; edited 4 times in total
Back to top
View user's profile Send private message
bornsoft
Contributor
Contributor


Joined: 19 Feb 2009
Posts: 113
Location: Germany

PostPosted: Tue Feb 23, 2010 11:08 pm    Post subject: Reply with quote

I came up with a very simple non-API-solution to check for administrator privileges that should work on all windows-versions from win2k up.
I prefer this as I do not have to care about if any system dlls are present or not.

It reads the group memberships of the current user from the registry and if there is an entry for the admin-group the function returns "1".

Microsoft itself writes:

Quote:


A security identifier (SID) is a unique value of variable length that is used to identify a security principal or security group in Windows operating systems. Well-known SIDs are a group of SIDs that identify generic users or generic groups. Their values remain constant across all operating systems.


The most important is the last phrase ...

http://support.microsoft.com/default.aspx?scid=kb;EN-US;Q243330

Please test it under Vista, Win7, Server2003/2008, Win2k and NT and report if it's doing it's job correctly.

I'm pretty sure, it does.

Code:

#                                                                                         
#      Function bsAdminCheck - bornSoft                                                   
#      --------------------------------                                                   
#                                                                                         
#      The function Returns "1" or NULL depending if the logged in user                   
#      is a member of administrator group or not.                                         
#                                                                                         
#          Usage:    %x = @bsAdmin()                                                     
#                                                                                         
#                                                                                         

#DEFINE Function,bsAdminCheck

  if @bsAdminCheck()
    info "You are logged in as an administrator. "@tab()
   else
    info "You have no administration privileges. "@tab()
  end
  exit

:bsAdminCheck
  #  Constant security identifier for Admin group 
  %S = "S-1-5-32-544"
  %K = "Software\Microsoft\Windows\CurrentVersion\Group Policy\GroupMembership"
  %L = @new(list)
  list RegVals,%L,Curuser,%K
  repeat
    %n = @next(%L)
    if %n
      if @equal(@regread(Curuser,%K,%n),%S)
        %R = 1
      end
    end
  until %R @not(%n)
  list close,%L
  exit %R

Back to top
View user's profile Send private message Visit poster's website
PGWARE
Web Host


Joined: 29 Dec 2001
Posts: 1565

PostPosted: Tue Feb 23, 2010 11:24 pm    Post subject: Reply with quote

bornsoft I havent tested your code but I will, but I suspect a problem already. Let me explain.


In Vista/7 I can log in an a limited user account, I run your program and I allow it to elevate up to run as an admin.

Your function still checks and returns I am a limited user account, however the program I just gave access to has full admin rights to work properly. Your function is only checking if the user logged in is an admin, not if the exe running is running as an admin, once I elevated the exe it gave it admin rights so your program should have ran fine not warned me I'm not an admin.

The IsAdmin function is checking if the exe running has an administrator security token, it doesnt check if the logged in user is an admin - it checks the actual process running and its security rights. Maybe renaming this custom function to IsRunningAsAnAdmin would be more suitable.

This is one of the misconceptions of Windows Vista/7 and XP that people have. In XP you run the entire OS as an admin or not. In Vista/7 you can specifically have exes run as an admin by elevating up, while the rest of the system is running as a limited user. When you elevate it up it doesnt change which account the entire OS is logged into, it just gives the exe certain rights system wide.


Trust me this works for all versions of Windows; I use it in my apps which have thousands of customers. I am using it for Windows 2000, 2003, 2008, XP, Vista, and Windows 7, 64-bit versions of 2003, 2008, Vista and 7 as well.

The two dll's required have been distributed with Windows NT 4.0 and on, which means well since the mid 1990's. Kernel32.dll being part of the system since the beginning since its' the kernel. advapi32.dll is part of Windows, it is not part of .net.


*update* - I am updating this, the function bornsoft has posted does in fact work properly as I have found the registry hive does in fact load from the admin user that is elevated to.


Last edited by PGWARE on Wed Feb 24, 2010 1:24 am; edited 1 time in total
Back to top
View user's profile Send private message
Display posts from previous:   
Post new topic   Reply to topic    forum.vdsworld.com Forum Index -> General Help All times are GMT
Goto page 1, 2  Next
Page 1 of 2

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum
You can attach files in this forum
You can download files in this forum

Twitter@vdsworld       RSS

Powered by phpBB © 2001, 2005 phpBB Group