Solved

How can I run a vb.net application as a "startup script" before logon with an administrator account?

Posted on 2009-04-06
10
756 Views
Last Modified: 2012-08-14
Hi,

I'm working on a VB.Net application that runs before the logon. The application visualizes and configures the behaviour of a service. For certain reasons it should run before logon (as well as after).
At the moment the application runs as "Local System". The application should read the registry of remote PCs and also check the state of a service of remote PCs. Therefore administrator priviledges are needed.

I tried to restart the application with "CreateProcessWithLogonW" from "Advapi32" and the System.Diagnostics.Process class. But without success.
If logged in it works.

To start my application a batch file is registered in the GPO.

What is the best way to do this?
It should work on all OperatingSystems after XP and Server 2003

Thanks
0
Comment
Question by:Andreas9
10 Comments
 
LVL 14

Expert Comment

by:theras2000
Comment Utility
I dond't know how to get it to run before login, but if you don't get a good answer, you could probably just set the service to manual starting mode, and then use a 'net start' command in your batch file to start it after your script.
0
 
LVL 15

Expert Comment

by:spprivate
Comment Utility
You can use Autoexec.bat to put in a command line

Also you can create a service and make it run  under the local system account.
Here are few tips

http://www.tech-recipes.com/rx/1288/how-to-run-applications-in-the-local-system-account-lsa/
0
 
LVL 17

Expert Comment

by:Jared Luker
Comment Utility
Creating a startup script via GPO is the best way to make this happen.  This is the way that  do many things pre-login here at the site that I support.

Create a GPO that establishes a startup script.  Use that startup script to call your vb.net application and it will run in the context of the system account wth full admin rights.

Enjoy!
0
 

Author Comment

by:Andreas9
Comment Utility
Dear jared_luker

Thanks. I need access rights on remote computers (registry, service status). Therefore I need my application to run as a certain user account (Administrator). With the system account it does not work.
0
Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

 
LVL 17

Expert Comment

by:Jared Luker
Comment Utility
I can't say for sure, but I bet it would still work in a startup script.  The system account is domain based if I remember correctly.
0
 

Author Comment

by:Andreas9
Comment Utility
The system account has only local administrative rights. No network access is possible.
The target computer is normaly not in a domain.

Is impersonation a possibility? How does this work?
0
 

Author Comment

by:Andreas9
Comment Utility
I found out how to do the impersonation and it works.

I found an example in the Internet that I could use. See attachment


Code Snippet

Public Class AliasAccount
 

Private _username, _password, _domainname As String
 

Private _tokenHandle As New IntPtr(0)
 

Private _dupeTokenHandle As New IntPtr(0)
 

Private _impersonatedUser As System.Security.Principal.WindowsImpersonationContext
 

 
 

Public Sub New(ByVal username As String, ByVal password As String)
 

Dim nameparts() As String = username.Split("\"c)
 

If nameparts.Length > 1 Then
 

_domainname = nameparts(0)
 

_username = nameparts(1)
 

Else
 

_username = username
 

End If
 

_password = password
 

End Sub
 

Public Sub New(ByVal username As String, ByVal password As String, ByVal domainname As String)
 

_username = username
 

_password = password
 

_domainname = domainname
 

End Sub
 

 
 

Public Sub BeginImpersonation()
 

Const LOGON32_PROVIDER_DEFAULT As Integer = 0
 

Const LOGON32_LOGON_INTERACTIVE As Integer = 2
 

Const SecurityImpersonation As Integer = 2
 

Dim win32ErrorNumber As Integer
 

_tokenHandle = IntPtr.Zero
 

_dupeTokenHandle = IntPtr.Zero
 

If Not LogonUser(_username, _domainname, _password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, _tokenHandle) Then
 

win32ErrorNumber = System.Runtime.InteropServices.Marshal.GetLastWin32Error()
 

Throw New ImpersonationException(win32ErrorNumber, GetErrorMessage(win32ErrorNumber), _username, _domainname)
 

End If
 

If Not DuplicateToken(_tokenHandle, SecurityImpersonation, _dupeTokenHandle) Then
 

win32ErrorNumber = System.Runtime.InteropServices.Marshal.GetLastWin32Error()
 

CloseHandle(_tokenHandle)
 

Throw New ImpersonationException(win32ErrorNumber, "Unable to duplicate token!", _username, _domainname)
 

End If
 

Dim newId As New System.Security.Principal.WindowsIdentity(_dupeTokenHandle)
 

_impersonatedUser = newId.Impersonate()
 

End Sub
 

 
 

Public Sub EndImpersonation()
 

If Not _impersonatedUser Is Nothing Then
 

_impersonatedUser.Undo()
 

_impersonatedUser = Nothing
 

If Not System.IntPtr.op_Equality(_tokenHandle, IntPtr.Zero) Then
 

CloseHandle(_tokenHandle)
 

End If
 

If Not System.IntPtr.op_Equality(_dupeTokenHandle, IntPtr.Zero) Then
 

CloseHandle(_dupeTokenHandle)
 

End If
 

End If
 

End Sub
 

 
 

Public ReadOnly Property username() As String
 

Get
 

Return _username
 

End Get
 

End Property
 

Public ReadOnly Property domainname() As String
 

Get
 

Return _domainname
 

End Get
 

End Property
 

 
 

Public ReadOnly Property currentWindowsUsername() As String
 

Get
 

Return System.Security.Principal.WindowsIdentity.GetCurrent().Name
 

End Get
 

End Property
 

 
 

#Region "Exception Class"
 

Public Class ImpersonationException
 

Inherits System.Exception
 

Public ReadOnly win32ErrorNumber As Integer
 

Public Sub New(ByVal win32ErrorNumber As Integer, ByVal msg As String, ByVal username As String, ByVal domainname As String)
 

MyBase.New(String.Format("Impersonation of {1}\{0} failed! [{2}] {3}", username, domainname, win32ErrorNumber, msg))
 

Me.win32ErrorNumber = win32ErrorNumber
 

End Sub
 

End Class
 

#End Region
 

 
 

#Region "External Declarations and Helpers"
 

Private Declare Auto Function LogonUser Lib "advapi32.dll" (ByVal lpszUsername As [String], _
 

ByVal lpszDomain As [String], ByVal lpszPassword As [String], _
 

ByVal dwLogonType As Integer, ByVal dwLogonProvider As Integer, _
 

ByRef phToken As IntPtr) As Boolean
 

 
 

Private Declare Auto Function DuplicateToken Lib "advapi32.dll" (ByVal ExistingTokenHandle As IntPtr, _
 

ByVal SECURITY_IMPERSONATION_LEVEL As Integer, _
 

ByRef DuplicateTokenHandle As IntPtr) As Boolean
 

 
 

Private Declare Auto Function CloseHandle Lib "kernel32.dll" (ByVal handle As IntPtr) As Boolean
 

 
 

_
 

Private Shared Function FormatMessage(ByVal dwFlags As Integer, ByRef lpSource As IntPtr, _
 

ByVal dwMessageId As Integer, ByVal dwLanguageId As Integer, ByRef lpBuffer As [String], _
 

ByVal nSize As Integer, ByRef Arguments As IntPtr) As Integer
 

End Function
 

 
 

Private Function GetErrorMessage(ByVal errorCode As Integer) As String
 

Dim FORMAT_MESSAGE_ALLOCATE_BUFFER As Integer = &H100
 

Dim FORMAT_MESSAGE_IGNORE_INSERTS As Integer = &H200
 

Dim FORMAT_MESSAGE_FROM_SYSTEM As Integer = &H1000
 

Dim messageSize As Integer = 255
 

Dim lpMsgBuf As String
 

Dim dwFlags As Integer = FORMAT_MESSAGE_ALLOCATE_BUFFER Or FORMAT_MESSAGE_FROM_SYSTEM Or FORMAT_MESSAGE_IGNORE_INSERTS
 

Dim ptrlpSource As IntPtr = IntPtr.Zero
 

Dim prtArguments As IntPtr = IntPtr.Zero
 

Dim retVal As Integer = FormatMessage(dwFlags, ptrlpSource, errorCode, 0, lpMsgBuf, messageSize, prtArguments)
 

If 0 = retVal Then
 

Throw New System.Exception("Failed to format message for error code " + errorCode.ToString() + ". ")
 

End If
 

Return lpMsgBuf
 

End Function
 

#End Region
 

End Class
 

 
 

Then to use it:
 

 
 
 

Code Snippet

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
 

Dim Act As New Impersonation.AliasAccount("TestImpersonate", "password")
 

Act.BeginImpersonation()
 

Try
 

Dim Key As Microsoft.Win32.RegistryKey = Microsoft.Win32.Registry.CurrentUser
 

Dim SvrKey As Microsoft.Win32.RegistryKey
 

'If SvrKey Is Nothing Then
 

SvrKey = Key.CreateSubKey("Software\Microsoft\Windows\CurrentVersion\Internet Settings\ZoneMap\Domains\hidi-server2")
 

SvrKey.SetValue("*", 1)
 

SvrKey.Close()
 

Key.Close()
 

Catch ex As Exception
 

MessageBox.Show(ex.Message)
 

End Try
 

Act.EndImpersonation()
 

End Sub

Open in new window

0
 

Expert Comment

by:carlnys
Comment Utility
I'd make it a part of group policy and disable Apply Group Policy for users asynchronously during logon, however in your case does it need to be applied before the user authenticates, or actually gets presented with explorer?

Carl
0
 

Accepted Solution

by:
ee_auto earned 0 total points
Comment Utility
Question PAQ'd, 500 points refunded, and stored in the solution database.
0

Featured Post

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

Windows 10 is here and for most admins this means frustration and challenges getting that first working Windows 10 image. As in my previous sysprep articles, I've put together a simple help guide to get you through this process. The aim is to achiev…
When you start your Windows 10 PC and got an "Operating system not found" error or just saw  "Auto repair for startup". After a while, you have entered a loop for Auto repair which does not fix anything and you will be in a  panic as all your work w…
It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

763 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

10 Experts available now in Live!

Get 1:1 Help Now