473,750 Members | 2,265 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

LsaOpenPolicy : Attempted to read or write protected memory

Hello,

I'm trying to call LsaOpenPolicy, but get the error
'System.AccessV iolationExcepti on'.

I originally tried a conversion from working VB6 code and I've compared
the code with working C# code and cannot see where the problem lies -
can anyone help to point out the problem please:

Structure LSA_UNICODE_STR ING
Dim Length As Short
Dim MaximumLength As Short
Dim Buffer As String
End Structure
Structure LSA_OBJECT_ATTR IBUTES
Dim Length As Integer
Dim RootDirectory As IntPtr
Dim ObjectName As IntPtr
Dim Attributes As Integer
Dim SecurityDescrip tor As IntPtr
Dim SecurityQuality OfService As IntPtr
End Structure
Declare Unicode Function LsaOpenPolicy Lib "advapi32.d ll" (ByRef
SystemName() As LSA_UNICODE_STR ING, ByRef ObjectAttribute s As
LSA_OBJECT_ATTR IBUTES, ByVal DesiredAccess As Int32, ByRef PolicyHandle
As IntPtr) As Int32
Private POLICY_ALL_ACCE SS As Integer = &HF0FFF

Private Sub Form1_Load(ByVa l sender As Object, ByVal e As
System.EventArg s) Handles Me.Load
Dim SystemName(0) As LSA_UNICODE_STR ING
SystemName(0) = New LSA_UNICODE_STR ING
'initialize a pointer for the policy handle
Dim PolicyHandle As IntPtr = IntPtr.Zero
'these attributes are not used, but LsaOpenPolicy wants them to
exists
Dim ObjectAttribute s As New LSA_OBJECT_ATTR IBUTES
ObjectAttribute s.RootDirectory = IntPtr.Zero
ObjectAttribute s.ObjectName = IntPtr.Zero
ObjectAttribute s.Attributes = 0
ObjectAttribute s.SecurityDescr iptor = IntPtr.Zero
ObjectAttribute s.SecurityQuali tyOfService = IntPtr.Zero
ObjectAttribute s.Length = 24 ' IN C# :
Marshal.SizeOf( typeof(LSA_OBJE CT_ATTRIBUTES)) ;
'get a policy handle
SystemName(0).L ength = "192.168.1.1".L ength * 2 ' Can't get
UnicodeEncoding .CharSize to work? How to declare?
SystemName(0).M aximumLength = ("192.168.1.1". Length + 1) * 2 '
Can't get UnicodeEncoding .CharSize to work? How to declare?
SystemName(0).B uffer = "192.168.1. 1"
Dim ResultPolicy As UInteger
Dim Access = POLICY_ALL_ACCE SS
ResultPolicy = LsaOpenPolicy(S ystemName, ObjectAttribute s,
Access, PolicyHandle)

Many thanks
Adrian

Nov 6 '06 #1
4 5244
Adrian,
Declare Unicode Function LsaOpenPolicy Lib "advapi32.d ll" (ByRef
SystemName() As LSA_UNICODE_STR ING, ByRef ObjectAttribute s As
LSA_OBJECT_ATT RIBUTES, ByVal DesiredAccess As Int32, ByRef PolicyHandle
As IntPtr) As Int32
The first parameter shouldn't be an array, just a single
LSA_UNICODE_STR ING.

'these attributes are not used, but LsaOpenPolicy wants them to
exists
Dim ObjectAttribute s As New LSA_OBJECT_ATTR IBUTES
ObjectAttribute s.RootDirectory = IntPtr.Zero
ObjectAttribute s.ObjectName = IntPtr.Zero
ObjectAttribute s.Attributes = 0
ObjectAttribute s.SecurityDescr iptor = IntPtr.Zero
ObjectAttribute s.SecurityQuali tyOfService = IntPtr.Zero
ObjectAttribute s.Length = 24 ' IN C# :
Marshal.SizeOf (typeof(LSA_OBJ ECT_ATTRIBUTES) );
FYI, all members are initialized to zero by default so doing it
explicitly isn't really needed.

And you can use Marshal.SizeOf from VB as well.
Mattias

--
Mattias Sjögren [C# MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Nov 6 '06 #2
Thanks for that, the problem appears to be with the LSA_UNICODE_STR ING
part.

If I set pass it as NOTHING it works fine and gets a handle to local
machine, the problem comes when I try to use it on a remote computer.

Having stepped through the C# version and the VB.NET version I cannot
see any differences in what is being passed, or how it's being passed.

I'm totallay stumped as to what's causing the error.
Mattias Sjögren wrote:
Adrian,
Declare Unicode Function LsaOpenPolicy Lib "advapi32.d ll" (ByRef
SystemName() As LSA_UNICODE_STR ING, ByRef ObjectAttribute s As
LSA_OBJECT_ATTR IBUTES, ByVal DesiredAccess As Int32, ByRef PolicyHandle
As IntPtr) As Int32

The first parameter shouldn't be an array, just a single
LSA_UNICODE_STR ING.

'these attributes are not used, but LsaOpenPolicy wants them to
exists
Dim ObjectAttribute s As New LSA_OBJECT_ATTR IBUTES
ObjectAttribute s.RootDirectory = IntPtr.Zero
ObjectAttribute s.ObjectName = IntPtr.Zero
ObjectAttribute s.Attributes = 0
ObjectAttribute s.SecurityDescr iptor = IntPtr.Zero
ObjectAttribute s.SecurityQuali tyOfService = IntPtr.Zero
ObjectAttribute s.Length = 24 ' IN C# :
Marshal.SizeOf( typeof(LSA_OBJE CT_ATTRIBUTES)) ;

FYI, all members are initialized to zero by default so doing it
explicitly isn't really needed.

And you can use Marshal.SizeOf from VB as well.
Mattias

--
Mattias Sjögren [C# MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Nov 7 '06 #3
I've managed to fix the first error with the following code:

Dim SystemName As LSA_UNICODE_STR ING
SystemName = New LSA_UNICODE_STR ING
UserAccount = "tenyas\zwa n"
Dim ObjectAttribute s As New LSA_OBJECT_ATTR IBUTES
'get a policy handle
SystemName = InitLSAString(" ")
Dim ResultPolicy As Integer
Dim Access = POLICY_ALL_ACCE SS
ResultPolicy = LsaOpenPolicy(S ystemName, ObjectAttribute s,
Access, PolicyHandle)
If ResultPolicy <0 Then
Debug.Print(Lsa NtStatusToWinEr ror(ResultPolic y))
End If

which works fine. As soon as I add a remote machine name though, it
fails with error 1722 (RPC Server unavailable), I know this isn't the
case as it happens against any machine. I can only assume that the name
isn't being passed correctly as unicode?

Please help someone - it's driving me crazy.

Thanks
Adrian

Adrian Wallis wrote:
Thanks for that, the problem appears to be with the LSA_UNICODE_STR ING
part.

If I set pass it as NOTHING it works fine and gets a handle to local
machine, the problem comes when I try to use it on a remote computer.

Having stepped through the C# version and the VB.NET version I cannot
see any differences in what is being passed, or how it's being passed.

I'm totallay stumped as to what's causing the error.
Mattias Sjögren wrote:
Adrian,
Declare Unicode Function LsaOpenPolicy Lib "advapi32.d ll" (ByRef
>SystemName() As LSA_UNICODE_STR ING, ByRef ObjectAttribute s As
>LSA_OBJECT_ATT RIBUTES, ByVal DesiredAccess As Int32, ByRef PolicyHandle
>As IntPtr) As Int32
The first parameter shouldn't be an array, just a single
LSA_UNICODE_STR ING.

'these attributes are not used, but LsaOpenPolicy wants them to
>exists
Dim ObjectAttribute s As New LSA_OBJECT_ATTR IBUTES
ObjectAttribute s.RootDirectory = IntPtr.Zero
ObjectAttribute s.ObjectName = IntPtr.Zero
ObjectAttribute s.Attributes = 0
ObjectAttribute s.SecurityDescr iptor = IntPtr.Zero
ObjectAttribute s.SecurityQuali tyOfService = IntPtr.Zero
ObjectAttribute s.Length = 24 ' IN C# :
>Marshal.SizeOf (typeof(LSA_OBJ ECT_ATTRIBUTES) );
FYI, all members are initialized to zero by default so doing it
explicitly isn't really needed.

And you can use Marshal.SizeOf from VB as well.
Mattias

--
Mattias Sjögren [C# MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Nov 7 '06 #4
I've managed to fix the problem by changing the structure slightly:

Structure LSA_UNICODE_STR ING
Dim Length As Short
Dim MaximumLength As Short

<System.Runtime .InteropService s.MarshalAs(Run time.InteropSer vices.Unmanaged Type.LPWStr)>
Dim buffer As String
End Structure

The full code if anyone wants is :

Structure LSA_UNICODE_STR ING
Dim Length As Short
Dim MaximumLength As Short

<System.Runtime .InteropService s.MarshalAs(Run time.InteropSer vices.Unmanaged Type.LPWStr)>
Dim buffer As String
End Structure
Public Enum SID_NAME_USE
SidTypeUser = 1
SidTypeGroup = 2
SidTypeDomain = 3
SidTypeAlias = 4
SidTypeWellKnow nGroup = 5
SidTypeDeletedA ccount = 6
SidTypeInvalid = 7
SidTypeUnknown = 8
End Enum
Structure LSA_OBJECT_ATTR IBUTES
Dim Length As Integer
Dim RootDirectory As IntPtr
Dim ObjectName As IntPtr
Dim Attributes As Integer
Dim SecurityDescrip tor As IntPtr
Dim SecurityQuality OfService As IntPtr
End Structure
Structure LSA_translated_ sid
Dim use As SID_NAME_USE
Dim RelativeID As ULong
Dim DomainIndex As Long
End Structure
Public UserAccount As String
Dim PolicyHandle As IntPtr = IntPtr.Zero
Private Declare Function LsaNtStatusToWi nError Lib "advapi32.d ll"
(ByVal NTStatus As Int32) As Int32
Declare Unicode Function LsaOpenPolicy Lib "advapi32.d ll" (ByRef
SystemName As LSA_UNICODE_STR ING, ByRef ObjectAttribute s As
LSA_OBJECT_ATTR IBUTES, ByVal DesiredAccess As Int32, ByRef PolicyHandle
As IntPtr) As Int32
Private POLICY_ALL_ACCE SS As Integer = &HF0FFF
Private Declare Auto Function LookupAccountNa me Lib "advapi32.d ll"
(ByVal lpSystemName As String, ByVal lpAccountName As String, ByVal Sid
As IntPtr, ByRef cbSid As Integer, ByVal lpReferenceDoma inName As
String, ByRef cchReferencedDo mainName As Integer, ByRef peUse As
Integer) As Boolean
Private Declare Unicode Function LsaAddAccountRi ghts Lib
"advapi32.d ll" (ByVal PolicyHandle As IntPtr, ByVal AccountSid As
IntPtr, ByRef UserRights As LSA_UNICODE_STR ING, ByVal CountOfRights As
Int32) As Int32
Private Sub Form1_Load(ByVa l sender As Object, ByVal e As
System.EventArg s) Handles Me.Load
Dim SystemName As LSA_UNICODE_STR ING
SystemName = New LSA_UNICODE_STR ING
UserAccount = "domain\use r"
Dim ObjectAttribute s As New LSA_OBJECT_ATTR IBUTES
'get a policy handle
SystemName = InitLSAString(" 192.168.1.1")
Dim ResultPolicy As Integer
Dim Access = POLICY_ALL_ACCE SS
ResultPolicy = LsaOpenPolicy(S ystemName, ObjectAttribute s,
Access, PolicyHandle)
If ResultPolicy <0 Then
Debug.Print(Lsa NtStatusToWinEr ror(ResultPolic y))
End If
Dim tSID As IntPtr
Dim lngUse As Int32 = 0
tSID = fncLookupAccoun tName("192.168. 1.1", "domain\use r", tSID,
Nothing, lngUse)
Dim Privileges As LSA_UNICODE_STR ING = New LSA_UNICODE_STR ING
Privileges = InitLSAString(" SeServiceLogonR ight")
Dim test As Integer
test = LsaAddAccountRi ghts(PolicyHand le, tSID, Privileges, 1)
Debug.Print(Lsa NtStatusToWinEr ror(test))
End Sub
Public Function fncLookupAccoun tName(ByVal strSystemName As String,
ByVal strName As String, ByVal tSID As IntPtr, ByRef
strReferencedDo mainName As String, ByRef lngUse As Long) As Long
Dim ret As Boolean
Dim ptrSid As IntPtr
Dim cbSid As Integer
Dim refDomainName As New System.Text.Str ingBuilder
Dim cbRefDomainName As Integer
Dim peUse As SID_NAME_USE
'First get the buffer sizes
ret = LookupAccountNa me(strSystemNam e, strName, Nothing, cbSid,
Nothing, cbRefDomainName , peUse)
'Adjust the buffers to the needed size
ptrSid =
System.Runtime. InteropServices .Marshal.AllocH Global(cbSid)
refDomainName.E nsureCapacity(c bRefDomainName)
'Get the data again, now with the changed buffers
ret = LookupAccountNa me(strSystemNam e, strName, ptrSid, cbSid,
refDomainName.T oString, cbRefDomainName , peUse)
If ret Then
Return ptrSid
End If
End Function
Public Function InitLSAString(B yVal Input As String) As
LSA_UNICODE_STR ING
Dim LSAString As New LSA_UNICODE_STR ING
LSAString.Lengt h = Input.Length *
System.Text.Uni codeEncoding.Ch arSize
LSAString.Maxim umLength = (Input.Length + 1) *
System.Text.Uni codeEncoding.Ch arSize
LSAString.buffe r = Input
Return LSAString
End Function

I hope this helps someone.
Adrian

Nov 7 '06 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
21352
by: hiralparikh | last post by:
Hi, I am using .NET 2.0 and trying to use a function from a native DLL file. Here is the syntax that I am using: definition: public static extern String getPwd(String strServerName, String strUserId);
4
7288
by: Seok Bee | last post by:
Dear Experts, I have created a script to extract the Event Logs from the system into an excel sheet. The logs are separated into 2 worksheets (Application Log and System Log). After this excel file being created, it will be sent out via email to the list of recipients. I run the script on my notebook (also developed on th same machine) it works fine. However, when I copy all the programs into the server which running on Windows 2000...
3
11941
by: XJ | last post by:
Hi experts, i try to use vb.net 2005 call dll, then give me "Attempted to read or write protected memory.This is often an indication that other memory is corrupt". i have chk some message others people posted, but since still cannot, pls give me some commnet.(this dll run smoothly at vb 6 ) module: ' example Declare Function TwTsxInitPar Lib "TSDKVC.DLL" _
1
3172
by: ianyian | last post by:
Hi experts, i try to use vb.net 2005 call C++ dll, then give me "Attempted to read or write protected memory.This is often an indication that other memory is corrupt". i have chk some message others people posted, but since still cannot, pls give me some commnet.(this dll run smoothly at vb 6 ) module: ' example
2
21977
by: Ilkka | last post by:
I have created an C++ application with Windows Forms, ADO and SQL server 2005. Now I need to change something and started debugging the code. Then suddenly I receive an error. "An unhandled exception of type 'System.AccessViolationException' occurred in mscorlib.dll Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt." The progran ends on a windows form designer...
2
4186
by: Pieter | last post by:
Hi, Since 10 days (the first time was the 10th of november) I have some weird exception happening in an application here: All (except 1 of the total of 5) users had this error now 1 of 2 times during the last 10 days. It happens mostly during startup or closing of the application, but sometimes just in the middle of nowhere. It doesn't point to anyting special. I don't get a clue... It's a Windows Forms VB.NET 2005 application. I roll...
2
20740
by: adypoly | last post by:
Hi guys... I am having a typical problem in using one of the native dll in C# I'll explain what am trying to do, I've a dll written in C language which i am trying to include in my C# project, the solutions builds fine but once i try to run the program it gives an exception as "Attempted to read or write protected memory. This is often an indication that other memory is corrupt" I am passing two integer pointer variables as the...
6
49910
by: Sugandh Jain | last post by:
Hi, I am getting the error message Attempted to read or write protected memory. This is often an indication that other memory is corrupt. It was not coming until yet, for around 2 months. Now, may be the records have increased and so i am getting this. anyone has any idea why and when do we get this. Its a windows based application with c# 2.0 and .Net Framework 2.0.
3
6947
by: sriram347 | last post by:
Hi I am a newbie to ASP.NET. I developed a web page (project type is web application) and I keep getting this error. B]Error message : "System.AccessViolation Exception attempted to read or write protected memory. this is often an indication that other memory is corrupt.... " These are all the platform info : Visual Studio 2005 (VB.NET) and ASP.NET 2.0.
0
9577
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9396
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9339
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9256
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8260
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6804
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4713
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4887
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3322
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.