473,783 Members | 2,563 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Marshal.AllocHG lobal failure after calling GetTokenInforma tion

I have been banging my head against the wall for a while now, and can't
seem to id the problem. I've been through a ton of posts and the code
doesn't seem any different. Can anybody see it?

When I call to GetTokenInforma tion I receive a buffer size (see
//HERE... comment in code), but when I let the code continue, asp.net
just sits there returning nothing, apparently on the
Marshal.AllocHG lobal call.

Here's the library function:

// ~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ ~~~~~~~~~~
using System;
using System.Collecti ons.Specialized ;
using System.Director yServices;
using System.Runtime. InteropServices ;
using System.Security .Principal;
using System.Text.Reg ularExpressions ;
namespace foobar.Library
{
public class AdFunctions
{
enum TOKEN_INFORMATI ON_CLASS
{
TokenUser = 1,
TokenGroups,
TokenPrivileges ,
TokenOwner,
TokenPrimaryGro up,
TokenDefaultDac l,
TokenSource,
TokenType,
TokenImpersonat ionLevel,
TokenStatistics ,
TokenRestricted Sids,
TokenSessionId,
TokenGroupsAndP rivileges,
TokenSessionRef erence,
TokenSandBoxIne rt,
TokenAuditPolic y,
TokenOrigin
}

public struct TOKEN_USER
{
public SID_AND_ATTRIBU TES User; // a single SID_AND_ATTRIBU TES
struct
}

public struct TOKEN_GROUPS
{
public int GroupCount; // DWORD number of groups
public SID_AND_ATTRIBU TES[] Groups; // array of SID_AND_ATTRIBU TES
structs
}

public struct SID_AND_ATTRIBU TES
{
public IntPtr Sid; // pointer to a sid
public int Attributes; // DWORD attributes
}
//[DllImport("adva pi32.dll", CharSet=CharSet .Auto)]
//static extern bool ConvertSidToStr ingSid( IntPtr pSID,
[In,Out,MarshalA s(UnmanagedType .LPTStr)] ref string pStringSid);

// Using IntPtr for pSID insted of Byte[]
[DllImport("adva pi32.dll", CharSet=CharSet .Auto, SetLastError=tr ue)]
static extern bool ConvertSidToStr ingSid(IntPtr pSID, out IntPtr
pSid);

[DllImport("adva pi32.dll", CharSet=CharSet .Auto, SetLastError=tr ue)]
static extern bool ConvertStringSi dToSid( string sStringSid, out
IntPtr pSID );

[DllImport("adva pi32.dll", SetLastError=tr ue)]
static extern bool GetTokenInforma tion(
IntPtr TokenHandle,
TOKEN_INFORMATI ON_CLASS TokenInformatio nClass,
IntPtr TokenInformatio n,
int TokenInformatio nLength,
out int ReturnLength);

[DllImport("kern el32.dll")]
static extern IntPtr LocalFree(IntPt r hMem);

public int GetGroupSidsFro mToken(IntPtr pToken, ref string[] aSids)
{
int iTokenInfoLengt h = 0;
bool bResult = true;

// first call gets length of TokenInformatio n
bResult = GetTokenInforma tion( pToken,
TOKEN_INFORMATI ON_CLASS.TokenG roups, IntPtr.Zero, 0, out
iTokenInfoLengt h );

//HERE if I uncomment this, the call returns an integer rapidly
//return iTokenInfoLengt h;

// if we got a return, continue
if ( iTokenInfoLengt h > 0 )
{
// allocate a memory buffer for the TokenInformatio n
IntPtr pTokenInfo = Marshal.AllocHG lobal( iTokenInfoLengt h );

// get the TokenInformatio n
bResult = GetTokenInforma tion( pToken,
TOKEN_INFORMATI ON_CLASS.TokenG roups , pTokenInfo, iTokenInfoLengt h, out
iTokenInfoLengt h ) ;
if ( bResult == false ) { return 2; }

// convert the TokenInformatio n to a TOKEN_GROUPS struct
TOKEN_GROUPS TokenGroups = ( TOKEN_GROUPS )Marshal.PtrToS tructure(
pTokenInfo , typeof( TOKEN_GROUPS ) ) ;

// loop through the groups
for ( int i=0; i < TokenGroups.Gro upCount; i++ )
{
IntPtr pSid = IntPtr.Zero;

// get the string representation of the sid
bResult = ConvertSidToStr ingSid( TokenGroups.Gro ups[i].Sid, out
pSid );
if ( bResult == false ) { return 3; }

// put it into a c# string and free the memory
string sSid = Marshal.PtrToSt ringAuto( pSid );
LocalFree(pSid) ;

// add it to the array reference
aSids[i] = sSid;
}
}
else
{
// GetTokenInforma tion returned a 0 length
return 1;
}

// all set
return 0;
}


}
}

// ~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ ~~~~~~~~~~

Here's the code behind file that calls it:

// ~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ ~~~~~~~~~~

using System;
using System.Collecti ons;
using System.Componen tModel;
using System.Data;
using System.Drawing;
using System.Security .Principal;
using System.Web;
using System.Web.Sess ionState;
using System.Web.UI;
using System.Web.UI.W ebControls;
using System.Web.UI.H tmlControls;

using foobar.Library;

namespace Users
{
/// <summary>
/// Summary description for WebForm1.
/// </summary>
public class Default : System.Web.UI.P age
{
protected System.Web.UI.W ebControls.Labe l lblStatusLine;

private void Page_Load(objec t sender, System.EventArg s e)
{
Trace.Write("de bug", "Page_Load: entered function");
Trace.Write("de bug", "Page_Load: user id is " +
System.Web.Http Context.Current .User.Identity. Name.ToString() );
Trace.Write("de bug", "Page_Load: process id is " +
WindowsIdentity .GetCurrent().N ame.ToString() );

string[] aSids = new string[200];
Trace.Write("de bug", "Page_Load: created array" );

AdFunctions oAdFunctions = new AdFunctions();
Trace.Write("de bug", "Page_Load: created AdFunctions object" );

int iReturn =
oAdFunctions.Ge tGroupSidsFromT oken(WindowsIde ntity.GetCurren t().Token,
ref aSids);
Trace.Write("de bug", "Page_Load: AdFunctions.Get GroupSidsFromTo ken
returned " + iReturn.ToStrin g() );

if ( iReturn == 0 )
{
// TODO color the output
lblStatusLine.T ext = "ok...";
}
else
{
lblStatusLine.T ext = Application["ProductNam e"] + " could not
retrive your logon groups. Please contact your administrator
(GetGroupSidsFr omToken:" + iReturn.ToStrin g() + ").";
}
}

#region Web Form Designer generated code
override protected void OnInit(EventArg s e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeCompo nent();
base.OnInit(e);
}

/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeCompo nent()
{
this.Load += new System.EventHan dler(this.Page_ Load);

}
#endregion
}
}

// ~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ ~~~~~~~~~~

and finally the aspx page:

// ~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ ~~~~~~~~~~

<%@ Page language="c#" Codebehind="Def ault.aspx.cs"
AutoEventWireup ="false" Inherits="Users .Default" Trace="True"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>WebForm1 </title>
<meta name="GENERATOR " Content="Micros oft Visual Studio .NET 7.1">
<meta name="CODE_LANG UAGE" Content="C#">
<meta name="vs_defaul tClientScript" content="JavaSc ript">
<meta name="vs_target Schema"
content="http://schemas.microso ft.com/intellisense/ie5">
</HEAD>
<body MS_POSITIONING= "GridLayout ">
<form id="Form1" method="post" runat="server">
<asp:Label id="lblStatusLi ne" style="Z-INDEX: 101; LEFT: 160px;
POSITION: absolute; TOP: 760px"
runat="server" Width="872px"></asp:Label>
</form>
</body>
</HTML>

Nov 17 '05 #1
1 4219
I managed to fix this, the fixed code is below:

thanks to Mattias from the post "How to call Win32 Native API
GetTokenInforma tion() using C#?"

public class Misc
{

public Array redim(Array arrToResize, int length)
{
// from http://www.code101.com/Code101/Displ...le.aspx?cid=54
Type t= arrToResize.Get Type().GetEleme ntType();
Array newArray=Array. CreateInstance( t,length);
Array.Copy(arrT oResize,0,newAr ray,0,Math.Min( arrToResize.Len gth,length));
return newArray;
}
}

public class AdFunctions
{
enum TOKEN_INFORMATI ON_CLASS
{
TokenUser = 1,
TokenGroups,
TokenPrivileges ,
TokenOwner,
TokenPrimaryGro up,
TokenDefaultDac l,
TokenSource,
TokenType,
TokenImpersonat ionLevel,
TokenStatistics ,
TokenRestricted Sids,
TokenSessionId,
TokenGroupsAndP rivileges,
TokenSessionRef erence,
TokenSandBoxIne rt,
TokenAuditPolic y,
TokenOrigin
}

public struct TOKEN_USER
{
public SID_AND_ATTRIBU TES User; // a single SID_AND_ATTRIBU TES
struct
}

[StructLayout(La youtKind.Sequen tial)]
public struct TOKEN_GROUPS
{
public int GroupCount; // DWORD number of groups
public SID_AND_ATTRIBU TES[] Groups; // array of SID_AND_ATTRIBU TES
structs
}

[StructLayout(La youtKind.Sequen tial)]
public struct SID_AND_ATTRIBU TES
{
public IntPtr Sid; // pointer to a sid
public int Attributes; // DWORD attributes
}
//[DllImport("adva pi32.dll", CharSet=CharSet .Auto)]
//static extern bool ConvertSidToStr ingSid( IntPtr pSID,
[In,Out,MarshalA s(UnmanagedType .LPTStr)] ref string pStringSid);

// Using IntPtr for pSID insted of Byte[]
[DllImport("adva pi32.dll", CharSet=CharSet .Auto, SetLastError=tr ue)]
static extern bool ConvertSidToStr ingSid(IntPtr pSID, out IntPtr
pSid);

[DllImport("adva pi32.dll", CharSet=CharSet .Auto, SetLastError=tr ue)]
static extern bool ConvertStringSi dToSid( string sStringSid, out
IntPtr pSID );

[DllImport("adva pi32.dll", SetLastError=tr ue)]
static extern bool GetTokenInforma tion(
IntPtr TokenHandle,
TOKEN_INFORMATI ON_CLASS TokenInformatio nClass,
IntPtr TokenInformatio n,
int TokenInformatio nLength,
out int ReturnLength);

[DllImport("kern el32.dll")]
static extern IntPtr LocalFree(IntPt r hMem);

public int GetGroupSidsFro mToken(IntPtr pToken, ref string[] aSids)
{
int iTokenInfoLengt h = 0;
bool bResult = true;

// first call gets length of TokenInformatio n
bResult = GetTokenInforma tion( pToken,
TOKEN_INFORMATI ON_CLASS.TokenG roups, IntPtr.Zero, 0, out
iTokenInfoLengt h );
// if I uncomment this, the call returns an integer rapidly
//return iTokenInfoLengt h;

// if we got a return, continue
if ( iTokenInfoLengt h > 0 )
{
// allocate a memory buffer for the TokenInformatio n
IntPtr pTokenInfo = Marshal.AllocHG lobal( iTokenInfoLengt h );

// get the TokenInformatio n
bResult = GetTokenInforma tion( pToken,
TOKEN_INFORMATI ON_CLASS.TokenG roups , pTokenInfo, iTokenInfoLengt h, out
iTokenInfoLengt h ) ;
if ( bResult == false ) { return 2; }

// why would this be here and not after Marshal.PtrToSt ructure?
like TokenGroups.Gro upCount?
int groupCount = Marshal.ReadInt 32( pTokenInfo );

// convert the TokenInformatio n to a TOKEN_GROUPS struct
// BREAKING HERE
//TOKEN_GROUPS TokenGroups = ( TOKEN_GROUPS
)Marshal.PtrToS tructure( pTokenInfo , typeof( TOKEN_GROUPS ) ) ;

// get a pointer to the first group
int pSidAndAttibute s = (int)pTokenInfo + 4;

// loop through the groups
for ( int i=0; i < groupCount; i++ )
{
// marshall the struct out of the pointer
SID_AND_ATTRIBU TES SidAndAttibutes =
(SID_AND_ATTRIB UTES)Marshal.Pt rToStructure( (IntPtr)pSidAnd Attibutes ,
typeof(SID_AND_ ATTRIBUTES) ) ;

// initialize a pointer and get the sid converted
IntPtr pSid = IntPtr.Zero;
bResult = ConvertSidToStr ingSid( SidAndAttibutes .Sid, out pSid );
if ( bResult == false ) { return 3; }

// place it into a c# string and free up the memory
string sSid = Marshal.PtrToSt ringAuto( pSid );
LocalFree(pSid) ;

// add it to the array reference
aSids[i] = sSid;

// move to the next pointer
pSidAndAttibute s += Marshal.SizeOf( typeof(SID_AND_ ATTRIBUTES) );
}
// redim the array
Misc oMisc = new Misc();
aSids = (string[])oMisc.redim(aS ids, groupCount);
}
else
{
// GetTokenInforma tion returned a 0 length
return 1;
}

// all set
return 0;
}

Nov 17 '05 #2

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

Similar topics

2
10238
by: Stefan | last post by:
I have the following question The Marshal class contains a function to allocate a block of memory 1. Marshal.AllocHGlobal ( int cb 2. Marshal.AllocHGlobal ( IntPtr cb The first version I can understand, because the integer indicates the size of the memory block that is required But the second version I do not understand. If I want a memoryblock of 20 bytes could I use IntPtr p = Marshal.AllocHGlobal ( new IntPtr ( 20 ) )
2
4590
by: Hypnotron | last post by:
Hello, Regarding Marshal.AllocHGlobal versus Marshal.AllocCoTaskMem Does anyone know the circumstances in which one should use one over the other? http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/ frlrfsystemruntimeinteropservicesmarshalclassalloccotaskmemtopic.asp http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dllproc/bas e/overlapped_str.asp
0
1366
by: Hypnotron | last post by:
>Hello, >Regarding Marshal.AllocHGlobal versus Marshal.AllocCoTaskMem Does anyone >know the circumstances in which one should use one over the other? > >http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html / frlrfsystemruntimeinteropservicesmarshalclassalloccotaskmemtopic.asp > >http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dllproc/ba s
13
2169
by: Just Me | last post by:
The following almost works. The problem is Marshal.PtrToStringAuto seems to terminate at the first null so I don't get the full string. Any suggestions on how to fix this? Or how to improve the code? Thanks PS I added the +1 because as I understand the GetLogicalDriveStrings doc
2
8143
by: scottt | last post by:
I need to call into a C++ DLL from my C# code. The function is expecting a void pointer to an unsigned short. Which would be more correct? UInt16 wRegData; IntPtr p = Marshal.AllocHGlobal(Marshal.SizeOf(wRegData)); Marshal.StructureToPtr(wRegData, p, false);
2
7317
by: runner | last post by:
I'm trying to call some functions from OpenSSL library but I'm a bit confused when I have to use pinvoke. first function should create key from some input data, it's declared : void BF_set_key(BF_KEY *key, int len, const unsigned char *data); I've translated it as public static extern IntPtr BF_set_key (IntPtr key, int len, byte data) and I try to call it this way:
2
7207
by: O.B. | last post by:
When using Marshal to copy data from a byte array to the structure below, only the first byte of the "other" array is getting copied from the original byte array. What do I need to specify to get Marshal.PtrToStructure to copy the all the data into the "other" array? unsafe public struct DeadReckoning {
0
2135
by: Charming12 | last post by:
Hi All, I have a strange problem and due to my inefficiency with IntPtr i am unable to figure it out. I have an structure something like: public struct Detail { public int age; public Detail(int _age)
2
15944
by: O.B. | last post by:
I have operation within a class that marshals the data into a byte array. Below are three different ways that work. Are there any downsides to using one over the the other? public virtual byte ToRaw1() { byte byteArray = new byte; IntPtr pointer = Marshal.AllocHGlobal(Size); Marshal.StructureToPtr(this, pointer, false); Marshal.Copy(pointer, byteArray, 0, Size);
0
9643
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10315
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
10147
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...
0
9946
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
5379
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
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4044
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
2
3645
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2877
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.