Question

Changing a NTFS volume between writable and read-only in a Windows C/C++ program

Asked by: jmgallag

Hi,

I have a NTFS volume with ~300,000 folders and files on it. Using C/C++, I need to change the effective permission from read-only to writable QUICKLY. I have written some code using SetNamedSecurityInfo() against the root directory, which worked, however, I was dismayed to find that using the ACE flags CONTAINER_INHERIT_ACE | OBJECT_INHERIT_ACE caused the new ACE to be propagated immediately, instead of calculated when the subobjects were accessed. It took about 15 minutes for SetSecurityInfo() to return.  Here is my test code:

int main(int argc, char* argv[])
{
#define THE_PATH "g:\\"
      
      PSECURITY_DESCRIPTOR SecurityDescriptor = NULL;
      PACL pDacl;
      DWORD status;
      PSID psidOwner;
      PACL NewAcl = NULL;
      time_t seconds;
      
      DWORD InheritFlag = CONTAINER_INHERIT_ACE | OBJECT_INHERIT_ACE;
      ACCESS_MODE option = GRANT_ACCESS;
      EXPLICIT_ACCESS explicitaccess;
      
      seconds = time(NULL);      
      
      status = GetNamedSecurityInfo(
            THE_PATH,
            SE_FILE_OBJECT,
            DACL_SECURITY_INFORMATION|OWNER_SECURITY_INFORMATION,
            &psidOwner,
            NULL,
            &pDacl,
            NULL,
            &SecurityDescriptor
            );

      BuildExplicitAccessWithName(
            &explicitaccess,
            "Users",
            FILE_ALL_ACCESS,
            // FILE_GENERIC_READ,
            SET_ACCESS,
            InheritFlag
            );
      
      status = SetEntriesInAcl(
            1,
            &explicitaccess,
            NULL,
            &NewAcl
            );
      
      status = SetNamedSecurityInfo(
            THE_PATH,
            SE_FILE_OBJECT,
            DACL_SECURITY_INFORMATION ,
            NULL,
            NULL,
            NewAcl,
            NULL);
      
      seconds = time(NULL) - seconds;
      
      printf("It took %d seconds.\n", seconds);
      
      if (ERROR_SUCCESS != status)  {
            printf( "SetNamedSecurityInfo Error %u\n", status );
      }  
      
      if(SecurityDescriptor) LocalFree(SecurityDescriptor);
      return 0;
}


Some background on my situation: The volume in question is essentially a database extract, which is distributed on a hard drive to my customers. The customers are frequently in situations where a network connection is unavailable, so the hard drive provides them the data they need without requiring a network connection. Also provided is a util for synchronizing their copy with a master copy, which is used when a network connection is available.  We have run into problems where a user accidentally drags one of the folders into another folder, which disturbs the structure expected by the update util. Hence the desire for this data to be read-only, except when the util is running. The owner of all the files/dirs is the group Users, so the customers will not have problems running a program that changes permissions on objects on this volume. What this boils down to is that we are not concerned with setting protections that can't be changed with the Explorer Security dialog, merely preventing accidental moves/deletes.

I have thoughts on how I might solve this:

- Are inherited ACEs always propagated immediately? If not, what code is required for this behavior?

- I have seen hints that XP supports mounting NTFS volumes read-only, but no code samples on how this is accomplised. Is this a flag that can easily be set without unmounting the volume? My volume is actually encrypted using PGPdisk, so if I can't set a flag on an already mounted volume, I doubt I could get this approach to work.

Other suggestions?

Thanks


This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2006-03-08 at 07:13:25ID21765371
Tags

buildexplicitaccesswithname

Topic

Miscellaneous Programming

Participating Experts
2
Points
500
Comments
25

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. How to make a folder writable
    I'm running W2P; I'm the only user, no password required to log on. I'm trying to run a program that needs the C:\temp folder to be writable; checked its attributes and "read only" is checked. I unchecked this option, refreshed Explorer, see the folder's attributes...
  2. Ntfs Permissions
    Hello, I would like to know how to change ntfs permissions using c/c++. Exapmles will be appreciated.
  3. Security Descriptor
    Hi I need to delete a file on a Windows 2000 server but getting "access denied" messages. I've found out that the file for some reason doesn't have a "security descriptor". Is it possible to create a default "security descriptor" for a file and ...
  4. printf( "%s",&p); and printf( "%s",p);
    Question is in the comment of the following code: #include <stdio.h> int main(int argc, char *argv[]) { int f; char p[100]; if (argc!=2){ printf("%s\n", "please enter exactly one argument"); }else{ f=fopen(argv[1],"r&quo...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: KavarPosted on 2006-03-08 at 07:27:35ID: 16134583

A MUCH SIMPLER approach would be to have the utitlity run under the only writable credentials.  This would prevent the writes, but would allow for no changes to the NTFS drive

 

by: jmgallagPosted on 2006-03-08 at 09:41:34ID: 16136234

Kavar,

Can you elaborate and provide a code snippet? Would this involve using a different account? Many of the customer devices are in different domains, and we cannot assume that they will be connected to our corporate network at first use.

Thanks

 

by: jmgallagPosted on 2006-03-08 at 09:48:03ID: 16136302

Wait, stupid comment- of course they will be on the network when synchronizing. Will the process require a password to change credentials?

 

by: KavarPosted on 2006-03-08 at 09:51:53ID: 16136338

no a password will not need to be entered if you don't want to require it, you can set it up to provide credentials when it runs, either as a service or scheduled task

 

by: KavarPosted on 2006-03-08 at 09:54:54ID: 16136373

to provide the credentials when running as a service, simply set the service up to run under those credentials, same as a scheduled task, if you want to use the "createprocess" method then there is just a little of programming that has to happen, but ... I think it is much BETTER to run it as a service, if the user must run a program, then the program should just start the service (which will automatically stop when syncronize is complete), and then just leave the Syncronize service as run manually

 

by: jmgallagPosted on 2006-03-08 at 10:40:03ID: 16136814

I think the CreateProcess method will be easier. I don't want the hassle of maintaining the service account password on all the end user devices. Maybe I'm not cluing in yet... what do you mean by "you can set it up to provide credentials when it runs"? How is this accomplished?

 

by: KavarPosted on 2006-03-08 at 10:47:29ID: 16136899

Well, what happens now is that when the person runs the utility they are creating the process under thier user ID, I am suggesting a different user ID be created for the syncronization process and that user ID should be the only one that has sufficient rights to the local hard drive, you can either have the user supply them in a password box at the time of run (added security) or have them set up in the process read from some encrypted source on the computer, the create process is a simple function callable from just about every language, and in C, you have the added benefiet of being able to provide SPI credentials

 

by: jmgallagPosted on 2006-03-08 at 11:21:44ID: 16137292

Kavar,

Your solution will certainly work, but I was hoping not to have to create an additional account and manage a password. There is a certain amount of corporate bureaucracy involved with accounts that are not regular user accounts, and I prefer to avoid it if possible.

I am new to Experts Exchange. Can I leave the question open for a few days to see if other approaches are suggested?

Thanks

 

by: KavarPosted on 2006-03-08 at 11:53:16ID: 16137629

sure, But as far as quickly changing security descriptors.... there are several problems involved the first being, depending on the layout, there may be litterally 1000s of ACLs to change, additionally, the right to change those ACLS must exist and therefore, you are inherently running this from an account that CAN change the data even if you don't want to ...

 

by: jmgallagPosted on 2006-03-08 at 11:58:42ID: 16137685

Right. I set the owner of the root dir to the group Users, so all users can change the permissions. I just didn't expect that the ACL propagated to children immediately...

 

by: KavarPosted on 2006-03-08 at 12:02:36ID: 16137726

well it "doesn't" if the children have the inherritence flag set, and do not have thier "own" acl, so if the only change is at the root, it will return immediately, the problem is most of the time, this is not the case.... and when you say "I", I assume that means some program... if the program is running under special credentials then your are back where we started, if the program is not running under special credentials, then how did you have rights to change the ACL from Read to modify?

 

by: jmgallagPosted on 2006-03-08 at 12:25:57ID: 16137962

OK, I image the disks before they are distributed. Part of my planned imaging process is to change the owner of the volume root to the group Users, and to set all the child files/dirs so that their only ACL is what they inherit from the root. Any authenticated user is a member of the group Users, so any of my customers will have permission to change permission, as they are members of the owning group. When I check the Security dialog in Explorer, it does indicate that the only ACL the children have is inherited from the parent. Then, using the code in my original post, I change the root from FILE_ALL_ACCESS to FILE_GENERIC_READ, or vice versa, and SetNamedSecurityInfo() takes a --long-- time. Using Sysinternals Process Explorer verifies that every child is being accessed, which I must assume is to propagate the ACL. So, either I'm doing something wrong in my code (very possible), or that's just how it works.

 

by: gabesoPosted on 2006-03-08 at 13:18:46ID: 16138549

Would it be possible to generate an .iso image of a filesystem (by definition read-only) and then publich it to users as a virtual cdrom volume shared over the network using daemontools (for example)?

 

by: jmgallagPosted on 2006-03-08 at 15:00:35ID: 16139720

The filesystem is currently 60 GB, and is about 2/3 full, and my customers are usually thousands of miles away from our data center (high latency), and sometimes on slow links, so it's not reasonable to pull the entire filesystem. A share is out because the whole purpose of this system is make the data available when a network is not. The update process is a client server system with a database on the backend; the database stores all changes to the master copy. Each customer filesystem has a unique ID and timestamp. When the client connects, only the changes that are later than the client's timestamp are sent. This keeps the number of transactions and data sent to a minimum.

 

by: KavarPosted on 2006-03-08 at 17:07:47ID: 16140548

why dont you do it this way then...

create a local group on the machine that has Write priveledges to that drive (and only that group) then leave the memeber ship empty when its supposed to be right protected and add Domain users to it when it's supposed to be writable, that fixes it I am pretty sure

 

by: jmgallagPosted on 2006-03-08 at 22:04:47ID: 16141776

OK, interesting. An admin is required to install the various software packages, so my package could create a local group. But most of the end users do not have admin rights, so how could a program running as a regular user add that user to a local group?

 

by: KavarPosted on 2006-03-09 at 06:32:34ID: 16144837

now that is easy, you will need a local admin account of course, but I can give you script that modified a local group using different credentials

 

by: jmgallagPosted on 2006-03-09 at 06:47:19ID: 16144970

This sounds very promising; please do.

 

by: KavarPosted on 2006-03-09 at 08:42:32ID: 16146258

on error resume next
Computername=<name of local computer>
username=<local admin user account>
password=<local admin user account password>
GroupName=<local group to modify>


Set Root=GetObject("WinNT:")
Path="WinNT://" & Computername
Set ComputerObj=Root.OpenDSObject(Path,username,password,5)
If Err.Number=0 Then
      Set GroupObj=ComputerObj.GetObject("group",GroupName)
      If Err.Number<>0 Then
            GroupObj.Add "WinNT://"& DomainName &"/Domain Users"
            if err.number then
                  wscript.echo "Error Adding Domain Users to Group: " & Groupname
            else
                  wscript.echo "Worked"
            end if
        else
            wscript.echo "Error Connecting to Group object on computer: " & computername
      End If
End If

 

by: jmgallagPosted on 2006-03-09 at 12:23:00ID: 16148369

Kavar,

This approach still requires a second account, and management of an additional password. The difference is that it is a local account rather than a domain account, which actually makes things more difficult, as we have multiple customer computers, hence multiple local accounts.

 

by: KavarPosted on 2006-03-09 at 12:44:38ID: 16148636

but you can always make it a standard account name and password that only you guys know... but it solves you speed requirement ;)

 

by: jmgallagPosted on 2006-03-09 at 15:12:11ID: 16150325

Hmmm... I think our security group would not be too happy with a package creating local admin accounts all over the place. I would be better off with a domain level service account that has full access to the volume.

I am still perplexed by the ACL propagation issue. Can you shed some light on what the NO_PROPAGATE_INHERIT_ACE flag does in conjunction with the BuildExplicitAccessWithName function?

 

by: KavarPosted on 2006-03-09 at 18:56:56ID: 16151420

NO_PROPAGATE_INHERIT_ACE - If the ACE is inherited by a child object,
the system clears the OBJECT_INHERIT_ACE and CONTAINER_INHERIT_ACE flags
in the inherited ACE. This prevents the ACE from being inherited by
subsequent generations of objects.  This flag allows the admin to set
inheritance for only one-level down, ie. contents of the current
container.

The key being that the flag is for newly generated objects, not existing

 

by: jmgallagPosted on 2006-03-10 at 16:53:52ID: 16160519

Kavar,

I think the best approach for my app is to run the sync program as a different user. Is there a way a process to change what user it's running as, similar to setuid on Unix? If not, can a process created with CreateProcessWithLogonW interact with the logged in user's desktop? Our sync program has a GUI that provides progress status and the ability to interupt the sync.

 

by: KavarPosted on 2006-03-14 at 08:03:57ID: 16184676

the process cannot change user credentials (to my knowledge), but you can provide credentials for newly created processes, so as long as the sync process itself (the program writing to the drive) is run with the alternate credentials you will be fine

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...