Solved

I want the code do actions as another user

Posted on 2007-12-05
3
182 Views
Last Modified: 2013-11-26
To prevent accidental creation or deletetios of folders I restricted some rights to the users.
I want that the user could create a directory only via the application that I'm making.

How to do :  

IO.Directory.CreateDirectory("T:\temp\")

but in administrators rights.
Can I put somewere the user name and the password in the code to execute the code like it was the administrator?
0
Comment
Question by:cpx_Support
  • 2
3 Comments
 
LVL 9

Expert Comment

by:sognoct
ID: 20410165
remember to set   _userName, _password, _domain

here it is a script that should help you



using System.Security.Principal;
using System.Runtime.InteropServices;


//the following code executed before you perform your task

if ( ! ImpersonationUtil.Impersonate( _userName, _password, _domain ) )

{
MessageBox.Show("Impersonation failed.");
return;
}

//Perform task as this user here...

//After your task, do this:
ImpersonationUtil.UnImpersonate();


Here is the code for the ImpersonationUtil class:

/// <summary>
/// Impersonate a windows logon.
/// </summary>
public class ImpersonationUtil {

/// <summary>
/// Impersonate given logon information.
/// </summary>
/// <param name="logon">Windows logon name.</param>
/// <param name="password">password</param>
/// <param name="domain">domain name</param>
/// <returns></returns>
public static bool Impersonate( string logon, string password, string
domain ) {
WindowsIdentity tempWindowsIdentity;
IntPtr token = IntPtr.Zero;
IntPtr tokenDuplicate = IntPtr.Zero;

if( LogonUser( logon, domain, password, LOGON32_LOGON_INTERACTIVE,
LOGON32_PROVIDER_DEFAULT, ref token) != 0 ) {

if ( DuplicateToken( token, 2, ref tokenDuplicate ) != 0 ) {
tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
impersonationContext = tempWindowsIdentity.Impersonate();
if ( null != impersonationContext ) return true;
}
}

return false;
}

/// <summary>
/// Unimpersonate.
/// </summary>
public static void UnImpersonate() {
impersonationContext.Undo();
}

[DllImport("advapi32.dll", CharSet=CharSet.Auto)]
public static extern int LogonUser(
string lpszUserName,
String lpszDomain,
String lpszPassword,
int dwLogonType,
int dwLogonProvider,
ref IntPtr phToken );

[DllImport("advapi32.dll",
CharSet=System.Runtime.InteropServices.CharSet.Aut o,
SetLastError=true)]
public extern static int DuplicateToken(
IntPtr hToken,
int impersonationLevel,
ref IntPtr hNewToken );

private const int LOGON32_LOGON_INTERACTIVE = 2;
private const int LOGON32_LOGON_NETWORK_CLEARTEXT = 4;
private const int LOGON32_PROVIDER_DEFAULT = 0;
private static WindowsImpersonationContext impersonationContext;
}
0
 

Author Comment

by:cpx_Support
ID: 20410253
Could you translate to VB?
0
 
LVL 9

Accepted Solution

by:
sognoct earned 500 total points
ID: 20418789
Imports System
Imports System.Security.Principal
Imports System.Security.Permissions
Imports System.Runtime.InteropServices

Public Class clsIMP

  <DllImport("advapi32.dll")> _
  Private Shared Function LogonUser(ByVal lpszUsername As String, _
                             ByVal lpszDomain As String, _
                             ByVal lpszPassword As String, _
                             ByVal dwLogonType As Integer, _
                             ByVal dwLogonProvider As Integer, _
                             ByRef phToken As Integer) As Boolean
  End Function


  <DllImport("Kernel32.dll")> _
  Private Shared Function GetLastError() As Integer
  End Function

  Private Enum Logon
    Interactive = 2
    Network = 3
    Batch = 4
    Service = 5
    Unlock = 7
    NetworkCleartext = 8
    NewCredentials = 9
  End Enum

  Private Enum Provider
    UserDefault = 0
    WindowsNT35 = 1
    WindowsNT40 = 2
    Windows2000 = 3
  End Enum

  Private NewContext As WindowsImpersonationContext

  <SecurityPermission(SecurityAction.Demand, ControlPrincipal:=True, UnmanagedCode:=True)> _
  Private Shared Function GetWindowsIdentity(ByVal Username As String, _
                                      ByVal Domain As String, _
                                      ByVal Password As String) As WindowsIdentity
    Dim SecurityToken As Integer
    Dim Success As Boolean

    'possible to extend program to allow changes to the logon type and provider
    'as Ineractive is slower and caches the information compared to the Logon.Network type.
    'Though that leaves open the private enumeration information.
    Success = LogonUser(Username, Domain, Password, _
                        Logon.Network, Provider.UserDefault, _
                        SecurityToken)

    If Not Success Then
      Throw New System.Exception("Logon Failed. Error: " & GetLastError())
      Err.Clear()
    Else
      GetWindowsIdentity = New WindowsIdentity(New IntPtr(SecurityToken))
    End If
  End Function

  Public Function ImpersonateUser(ByVal username As String, _
                  ByVal domain As String, ByVal pwd As String) As Boolean
    Dim NewIdentity As WindowsIdentity
    Dim CurIdentity As WindowsIdentity

    Try
      NewIdentity = GetWindowsIdentity(username, domain, pwd)

      If Not NewIdentity Is Nothing Then
        NewContext = NewIdentity.Impersonate
        CurIdentity = WindowsIdentity.GetCurrent

        Debug.WriteLine("Impersonated ID: " & CurIdentity.Name) 'used for demo/example

        RemoveImpersonation()

        'just removing impersonation for demo/example
        'would comment out for actual use and call the
        'the RemoveImpersonation() method if all went well
        'else it gets called upon error event

        CurIdentity = WindowsIdentity.GetCurrent 'used for demo/example
        Debug.WriteLine("Logon ID: " & CurIdentity.Name) 'used for demo/example

        ImpersonateUser = True
      Else
        Err.Raise(7000, ImpersonateUser)
      End If

    Catch ex As Exception
      'during any error be sure to remove any implimented impersonation
      'failure to do so, could leave computer/program still executing code
      'under guise of higher authority, possible for exploitation.
      RemoveImpersonation()
      ImpersonateUser = False
      Throw New System.Exception("IM Error: " & ex.Message)
      Err.Clear()
    End Try

    Return ImpersonateUser
  End Function

  'NOTE: Be sure to call this function as soon as you've completed whatever
  'task needing impersonation is completed. As leaving your program running
  'under higher authority is vunerable to exploitation from malious users.
  Public Function RemoveImpersonation() As Boolean
    Try
      If Not NewContext Is Nothing Then 'test if object was ever created/referenced
        NewContext.Undo() 'if so, then undo impersonation.
        RemoveImpersonation = True
      Else
        RemoveImpersonation = True 'never created object, so no impersonation to revert.
      End If
    Catch ex As Exception 'something happened during removal, so warn calling app to handle
      RemoveImpersonation = False
      Throw New System.Exception("Removal Failure: " & ex.Message)
      Err.Clear()
    End Try
    Return RemoveImpersonation
  End Function

End Class
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

A basic question.. “What is the Garbage Collector?” The usual answer given back: “Garbage collector is a background thread run by the CLR for freeing up the memory space used by the objects which are no longer used by the program.” I wondered …
For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
This video discusses moving either the default database or any database to a new volume.
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…

706 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now