Solved

I want the code do actions as another user

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

Resolve Critical IT Incidents Fast

If your data, services or processes become compromised, your organization can suffer damage in just minutes and how fast you communicate during a major IT incident is everything. Learn how to immediately identify incidents & best practices to resolve them quickly and effectively.

Question has a verified solution.

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

In my previous article (http://www.experts-exchange.com/Programming/Languages/.NET/.NET_Framework_3.x/A_4362-Serialization-in-NET-1.html) we saw the basics of serialization and how types/objects can be serialized to Binary format. In this blog we wi…
This document covers how to connect to SQL Server and browse its contents.  It is meant for those new to Visual Studio and/or working with Microsoft SQL Server.  It is not a guide to building SQL Server database connections in your code.  This is mo…
Two types of users will appreciate AOMEI Backupper Pro: 1 - Those with PCIe drives (and haven't found cloning software that works on them). 2 - Those who want a fast clone of their boot drive (no re-boots needed) and it can clone your drive wh…
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…

789 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