473,387 Members | 1,520 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

setting security from code

Thanx Willy, this was very helpful.
But i also need (and want to know) how to do this from code.
Can you plase give me right topic in MSDN? is there good example?
Thanx
p.s. this is copy/paste from previous thread, don't ask why...

"Grei" <da*****************@zg.htnet.hr> wrote in message
news:d1**********@ss405.t-com.hr...
I need to set folder security to full control to everyone
is it possible from code?
example would be nice.

Thanx
The easiest is to use Process.Start to invoke the command line tool
cacls.exe.
The following adds everyone with Full access rights to the ACL of
"FolderName".
cacls FolderName /E /G everyone:F

Check MSDN for a Process.Start sample, run cacls /? to get a list of
options.

Willy.



Nov 17 '05 #1
1 2631

"Danko Greiner" <no*********@bcc.com> wrote in message
news:d2**********@ss405.t-com.hr...
Thanx Willy, this was very helpful.
But i also need (and want to know) how to do this from code.
Can you plase give me right topic in MSDN? is there good example?
Thanx
p.s. this is copy/paste from previous thread, don't ask why...


There are a number of alternatives, in order of my personal preference:

1. Wait for Whidbey if you can.
2. Use System.Management namespace classes and WMI, as the semantics closely
resemble what's been done in 1.
3. Use System.Directory namespace classes, as an alternative for 2 only when
running on XP or higher, this involves some COM interop to access the ADSI
security classes.
4. Use PInvoke to call the functions from the Win32 security API set.

Note that whatever method you choose you should be aware that managing
security permissions is hard and there are a lot of things you should be
aware of at the Win32 API level. Following is a sample of 2, just to give
you an idea how it looks like.

using System;
using System.Management;
using System.Collections;
// AccessPrivileges mask (Check MSDN )
[Flags]
enum AccessPrivileges : uint
{
FileReadData = 0x00000001,
FileWriteData = 0x00000002,
FileAppendData = 0x00000004,
FileReadEA = 0x00000008,
FileWriteEA = 0x00000010,
FileExecute = 0x00000020,
FileDeleteChild = 0x00000040,
FileReadAttributes = 0x00000080,
FileWriteAttributes= 0x00000100,
Delete = 0x00010000,
ReadControl = 0x00020000,
WriteDac = 0x00040000,
WriteOwner = 0x00080000,
Synchronize = 0x00100000,

AccessSystemSecurity = 0x01000000,
MaximumAllowed = 0x02000000,

GenericAll = 0x10000000,
GenericExecute= 0x20000000,
GenericWrite = 0x40000000,
GenericRead = 0x80000000
}
[Flags]
enum AceFlags : uint
{
NonInheritAce = 0,
ObjectInheritAce = 1,
ContainerInheritAce = 2,
NoPropagateInheritAce = 4,
InheritOnlyAce = 8,
InheritedAce = 16
}

[Flags]
enum AceType : uint
{
AccessAllowed = 0,
AccessDenied = 1,
Audit = 2
}
public class FileObjectSecurity
{
// ManagementPath path;
ManagementObject lfs;
ManagementBaseObject Descriptor; // Security descriptor for this object
ManagementBaseObject[] dacl;

public FileObjectSecurity(string FileSystemObject)
{
ManagementPath path = new ManagementPath();
path.Server = "."; // server name (. for local machine)
path.NamespacePath = @"root\cimv2";
path.RelativePath = @"Win32_LogicalFileSecuritySetting.Path=" + "'" +
FileSystemObject + "'";
lfs = new ManagementObject(path);
// Get the security descriptor for this object
ManagementBaseObject outParams =
lfs.InvokeMethod("GetSecurityDescriptor", null, null);
if (((uint)(outParams.Properties["ReturnValue"].Value)) == 0) // if
success
{
Descriptor =
((ManagementBaseObject)(outParams.Properties["Descriptor"].Value));
//The DACL is an array of Win32_ACE objects.
dacl = ((ManagementBaseObject[])(Descriptor.Properties["Dacl"].Value));
}
}
public void DumpDaclToConsole()
{
foreach(ManagementBaseObject mbo in this.dacl){
Console.WriteLine("-------------------------------------------------");
Console.WriteLine("{0:X} - {1} - {2}", mbo["AccessMask"],
Enum.Format(typeof(AceFlags), mbo["AceFlags"], "g") , mbo["AceType"]);
// Access allowed/denied ACE
if(Convert.ToInt32(mbo["AceType"]) == (int)AceType.AccessDenied)
Console.WriteLine("DENIED ACE TYPE");
else
Console.WriteLine("ALLOWED ACE TYPE");
// Dump trustees
ManagementBaseObject Trustee = ((ManagementBaseObject)(mbo["Trustee"]));
Console.WriteLine("Name: {0} - Domain: {1} - SID {2}\n",
Trustee.Properties["Name"].Value,
Trustee.Properties["Domain"].Value,
Trustee.Properties["SIDString"].Value);
// Dump ACE mask in readable form
UInt32 mask = (UInt32)mbo["AccessMask"];
Console.WriteLine(System.Enum.Format(typeof(Access Privileges), mask,
"g"));
}
}
// Add an ACE to the DACL
public bool AddEntryToDacl(string TrusteeName, Enum AccessPrivileges)
{
bool ret = false;
Array newDACL;
// Copy the non-inherited aces
ArrayList aceList = new ArrayList();
foreach(ManagementBaseObject entry in this.dacl)
aceList.Add(entry);

// Creates and initializes a one-dimensional Array of type
ManagementBaseObject
// with space for one extra direct ACE.
newDACL=Array.CreateInstance( typeof(ManagementBaseObject), aceList.Count
+ 1);
// Copy AL to Array
aceList.CopyTo(newDACL);

ManagementBaseObject trustee = null;
ManagementBaseObject ace = null;
// Initialize new Trustee (here a local account as sample)
try {
trustee = new ManagementClass( @"Win32_Trustee" );
// trustee.Properties["Domain"].Value = ""; // if domain other then local
machine
trustee.Properties["Name"].Value = TrusteeName;
}
// catch if non existing trustee
catch (Exception e)
{
Console.WriteLine(e.Message);
return ret;
}
try {
ace = new ManagementClass( @"Win32_ACE" );
ace.Properties["AccessMask"].Value = AccessPrivileges;
ace.Properties["AceFlags"].Value = AceFlags.NoPropagateInheritAce;
ace.Properties["AceType"].Value = AceType.AccessAllowed;
ace.Properties["Trustee"].Value = trustee;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return ret;
}
newDACL.SetValue(ace, newDACL.Length - 1);
// Re-write Security Descriptor
if(WriteSecurityDescriptor((ManagementBaseObject[])newDACL) == 0)
ret = true;
return ret;
}

private int WriteSecurityDescriptor(ManagementBaseObject[] Dacl)
{
ManagementBaseObject inParams =
lfs.GetMethodParameters("SetSecurityDescriptor");
Descriptor.Properties["Dacl"].Value = Dacl;
inParams["Descriptor"] = Descriptor;
ManagementBaseObject ret = lfs.InvokeMethod("SetSecurityDescriptor",
inParams, null);
return Convert.ToInt32(ret.Properties["ReturnValue"].Value);
}
}

class Tester {
public static void Main()
{
// Create FileObjectSecurity passing the file object (filepath) to the
ctor.
// Watch the double backslashes !!!!
FileObjectSecurity fos = new FileObjectSecurity(@"c:\\someFoledr");
fos.DumpDaclToConsole();
fos.AddEntryToDacl("Everyone", AccessPrivileges.FileWriteData);
}
}

Willy.
Nov 17 '05 #2

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

Similar topics

0
by: Fran Tirimo | last post by:
I am developing a small website using ASP scripts to format data retrieved from an Access database. It will run on a Windows 2003 server supporting FrontPage extensions 2002 hosted by the company...
0
by: Praveen | last post by:
Hello. I am writing some code that accepts a DFS Link and Username and grants that User permissions to the physical directory that the DFS Link corresponds to. I am using the System.Management...
6
by: Peter Krikelis | last post by:
Hi All, I am having a problem setting up input mode for serial communications. (Sorry about the long code post). The following code is what I use to set up my comm port.
1
by: CES | last post by:
All, Could someone please point me to a step by step resource on setting up a ..net Web Application on IIS. I'm having a problem setting up IIS to except a new Web Application. I'm deploying...
16
by: Marina | last post by:
Hi, I am trying to find the minimum security settings to allow a windows control embedded in IE have full trust. If I give the entire Intranet zone full trust, this works. However, this is...
8
by: David Lozzi | last post by:
Howdy, I have a user control that is a report to display data. On the page the control is inserted in, I have filter options to filter the report. When I try to do something like this, nothing...
4
by: ttan | last post by:
Hello, I'm writing a C# program on setting security for domain controller. what's a function call or class that apply for the security setting? is there a sample code? Here are the list of...
1
by: laredotornado | last post by:
Hi, I'm using PHP 4.4.4 on Apache 2 on Fedora Core 5. PHP was installed using Apache's apxs and the php library was installed to /usr/local/php. However, when I set my "error_reporting"...
6
by: John H Clark | last post by:
I am designing a site that requires AnonymousID. I set my web.config to allow this using <anonymousIdentification enable="true".../as recommended in the documentation. To verify the settings I...
5
by: =?Utf-8?B?bWFzaXg=?= | last post by:
We have an issue with load time in several installations of our application. We've located the information regarding KB 936707 and ensured that the application config file contains the runtime...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
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,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
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...

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.