Click here to Skip to main content
Click here to Skip to main content
Add your own
alternative version

The Windows Access Control Model Part 3

, 1 Jul 2005
In the third part of this series, we will take a tour of the new access control classes coming in .NET v2.0.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections.Specialized;


namespace NetAccessControl
{
	public partial class ReadToken : Form
	{
		private int PID;
		public ReadToken()
		{
			InitializeComponent();
		}

		private void ReadToken_Load(object sender, EventArgs e)
		{
			GetProcessList();
		}

		private void GetProcessList()
		{
			EmptyList();
			this.procLists.Items.Clear();
			foreach (System.Diagnostics.Process process in System.Diagnostics.Process.GetProcesses())
			{/* fill up the list of processes. */
				try
				{
					this.procLists.Items.Add(process.ProcessName + " (" + process.Id.ToString() + ")");
				}
				catch (System.NullReferenceException)
				{/* "System" process workaround. skip the process name */
				}
			}
		}

		private void EmptyList()
		{
			this.PID = -1;
			this.toolStripStatusLabel.Text = "refreshing list";
			this.ownerEdit.Text = "";
			this.groupListView.Items.Clear();
			this.privListView.Items.Clear();
			this.enableToolStripMenuItem.Enabled = false;
			this.disableToolStripMenuItem.Enabled = false;
			this.toolStripStatusLabel.Text = "Ready";
		}

		private void getTokenButton_Click(object sender, EventArgs e)
		{
			/* generate feedback */
			EmptyList();
			this.toolStripStatusLabel.Text = "Retrieving process handle";
			this.UseWaitCursor = true;

			string ModuleName = Convert.ToString(this.procLists.SelectedItem);
			string RegexRes = System.Text.RegularExpressions.Regex.Matches(ModuleName, "\\((.*?)\\)")[0].Groups[1].Value;
			this.PID = Convert.ToInt32(RegexRes);
			AccessToken.AccessToken ProcToken;

			try
			{
				/* Open up the token with the access token */
				this.toolStripStatusLabel.Text = "Retrieving access token";
				AccessToken.ManagedTokenHandle tmpToken = AccessToken.AccessToken.GetAccessToken
					(System.Diagnostics.Process.GetProcessById(this.PID).Handle,
					System.Security.Principal.TokenAccessLevels.Read |
					System.Security.Principal.TokenAccessLevels.Write);
				ProcToken = new AccessToken.AccessToken(tmpToken.HandleInternal);
				/* We opened up an access token. Enable the PrivContextmenu */
				this.enableToolStripMenuItem.Enabled = true;
				this.disableToolStripMenuItem.Enabled = true;
			}
			catch (System.Exception)
			{
				/* Attempt to open the token with lesser rights, and gray the menu items */
				try
				{
					this.toolStripStatusLabel.Text = "Error occurred, attempting to open read only";
					AccessToken.ManagedTokenHandle tmpToken = AccessToken.AccessToken.GetAccessToken
						(System.Diagnostics.Process.GetProcessById(PID).Handle,
						System.Security.Principal.TokenAccessLevels.Read);
					ProcToken = new AccessToken.AccessToken(tmpToken.HandleInternal);
				}
				catch (System.Exception ex)
				{
					this.toolStripStatusLabel.Text = "Error occurred: " + ex.Message;
					return;
				}
			}

			/* Get the list of privileges from the token. */
			this.toolStripStatusLabel.Text = "getting privileges";
			NameValueCollection privList = ProcToken.GetPrivileges();
			for(int i = 0; i < privList.Count; i++)
			{
				string FlagsString = "";
				this.privListView.Items.Add(privList.Keys[i]);
				int FlagAttributes = Convert.ToInt32(privList[i]);

				if (FlagAttributes == 0)
				{
					FlagsString = " Disabled";
					this.privListView.Items[i].BackColor = Color.LightGray;
				}
				else
				{
					if ((FlagAttributes & 1) != 0) /* SE_PRIVILEGE_ENABLED_BY_DEFAULT */
					{
						FlagsString += " Default";
						this.privListView.Items[i].BackColor = Color.LightCyan;
					}
					if ((FlagAttributes & 2) != 0) /* SE_PRIVILEGE_ENABLED */
					{
						FlagsString += " Enabled";
					}
					if ((FlagAttributes & 4) != 0) /* SE_PRIVILEGE_REMOVED */
					{
						FlagsString += ", Removed";
					}
					if ((FlagAttributes & 0x80000000) != 0) /* SE_PRIVILEGE_USED_FOR_ACCESS */
					{
						FlagsString += ", Used for access";
					}
				}
				FlagsString = FlagsString.Trim();
				this.privListView.Items[i].SubItems.Add(FlagsString);
			}

			this.toolStripStatusLabel.Text = "filling users";
			this.ownerEdit.Text = ProcToken.Name + " (" + ProcToken.Owner.ToString() + ")";

			for (int i = 0; i < ProcToken.Groups.Count; i++)
			{
				System.Security.Principal.NTAccount groupName = (System.Security.Principal.NTAccount)
					ProcToken.Groups[i].Translate(typeof(System.Security.Principal.NTAccount));
				this.groupListView.Items.Add(groupName.Value);
				this.groupListView.Items[i].SubItems.Add(ProcToken.Groups[i].Value);
			}

			this.toolStripStatusLabel.Text = "Ready";
			this.UseWaitCursor = false;
		}

		private void refreshButton_Click(object sender, EventArgs e)
		{
			GetProcessList();
		}

		private void CloseButton_Click(object sender, EventArgs e)
		{
			this.Close();
		}

		private void procLists_MouseDoubleClick(object sender, MouseEventArgs e)
		{
			this.getTokenButton_Click(sender, e);
		}

		private void privListView_SelectedIndexChanged(object sender, EventArgs e)
		{
			/* check if the user has deselected an item. */
			if (this.privListView.SelectedItems.Count == 0)
			{
				/* Hide any context menu if this is the case. */
				this.privListView.ContextMenuStrip = null;
			}
			else
			{
				/* show it otherwise. */
				this.privListView.ContextMenuStrip = this.PrivContextMenu;
			}
		}

		private void enableToolStripMenuItem_Click(object sender, EventArgs e)
		{
			/* We are required to enable the privilege */
			try
			{
				/* Open up the token with the access token */
				if (MessageBox.Show(this, "Caution, changing access tokens in this manner is unsafe and can" +
					" lead to system instability. Do you wish to continue?",
					"Are you sure?", MessageBoxButtons.YesNo, MessageBoxIcon.Warning,
					MessageBoxDefaultButton.Button2) == DialogResult.No)
				{
					return;
				}
				AccessToken.AccessToken ProcToken;
				this.toolStripStatusLabel.Text = "Retrieving access token";
				AccessToken.ManagedTokenHandle tmpToken = AccessToken.AccessToken.GetAccessToken
					(System.Diagnostics.Process.GetProcessById(this.PID).Handle,
					System.Security.Principal.TokenAccessLevels.Read |
					System.Security.Principal.TokenAccessLevels.Write);
				ProcToken = new AccessToken.AccessToken(tmpToken.HandleInternal);
				/* We opened up an access token. Enable the PrivContextmenu */
				ProcToken.SetPrivilege(this.privListView.SelectedItems[0].Text, true);
				this.privListView.SelectedItems[0].SubItems[1].Text = "Enabled";
				this.privListView.SelectedItems[0].BackColor = System.Drawing.Color.Empty;
			}
			catch (System.Exception ex)
			{
				this.toolStripStatusLabel.Text = "Error Occurred: " + ex.Message;
			}
		}

		private void disableToolStripMenuItem_Click(object sender, EventArgs e)
		{
			/* We are required to enable the privilege */
			try
			{
				/* Open up the token with the access token */
				if (MessageBox.Show(this, "Caution, changing access tokens in this manner is unsafe and can" +
					" lead to system instability. Do you wish to continue?",
					"Are you sure?", MessageBoxButtons.YesNo, MessageBoxIcon.Warning,
					MessageBoxDefaultButton.Button2) == DialogResult.No)
				{
					return;
				}
				AccessToken.AccessToken ProcToken;
				this.toolStripStatusLabel.Text = "Retrieving access token";
				AccessToken.ManagedTokenHandle tmpToken = AccessToken.AccessToken.GetAccessToken
					(System.Diagnostics.Process.GetProcessById(this.PID).Handle,
					System.Security.Principal.TokenAccessLevels.Read |
					System.Security.Principal.TokenAccessLevels.Write);
				ProcToken = new AccessToken.AccessToken(tmpToken.HandleInternal);
				/* We opened up an access token. Disable the PrivContextmenu */
				ProcToken.SetPrivilege(this.privListView.SelectedItems[0].Text, false);
				this.privListView.SelectedItems[0].SubItems[1].Text = "Disabled";
				this.privListView.SelectedItems[0].BackColor = System.Drawing.Color.LightGray;
			}
			catch (System.Exception ex)
			{
				this.toolStripStatusLabel.Text = "Error Occurred: " + ex.Message;
			}
		}
	}

}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

oshah
Web Developer
United States United States
Mr. Shah is a reclusive C++/C# developer lurking somewhere in the depths of the city of London. He learnt physics at Kings' College London and obtained a Master in Science there. Having earned an MCAD, he teeters on the brink of transitioning from C++ to C#, unsure of which language to jump to. Fortunately, he also knows how to use .NET interop to merge code between the two languages (which means he won't have to make the choice anytime soon).
 
His interests (apart from programming) are walking, football (the real one!), philosophy, history, retro-gaming, strategy gaming, and any good game in general.
 
He maintains a website / blog / FAQ / junk at shexec32.serveftp.net, where he places the best answers he's written to the questions you've asked. If you can find him, maybe you can hire Mr. Shah to help you with anything C++[/CLI]/C#/.NET related Smile | :) .

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.141220.1 | Last Updated 1 Jul 2005
Article Copyright 2005 by oshah
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid