Solved

I want the code do actions as another user

Posted on 2007-12-05
3
183 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

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

IP addresses can be stored in a database in any of several ways.  These ways may vary based on the volume of the data.  I was dealing with quite a large amount of data for user authentication purpose, and needed a way to minimize the storage.   …
It seems a simple enough task, yet I see repeated questions asking how to do it: how to pass data between two forms. In this article, I will show you the different mechanisms available for you to do just that. This article is directed towards the .N…
This Micro Tutorial will teach you how to censor certain areas of your screen. The example in this video will show a little boy's face being blurred. This will be demonstrated using Adobe Premiere Pro CS6.
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…

895 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

16 Experts available now in Live!

Get 1:1 Help Now