예제 #1
0
        public MyFile GetSpecifiedFile(string filepath)
        {
            if (!File.Exists(filepath))
            {
                throw new Microsoft.BusinessData.Runtime.ObjectNotFoundException(String.Format(
                                                                                     "No file exists at the path {0}",
                                                                                     filepath));
            }

            FileInfo fi     = new FileInfo(filepath);
            MyFile   myfile = new MyFile();

            myfile.Path      = filepath;
            myfile.Extension = fi.Extension.TrimStart(new char[] { '.' });

            if (myfile.Extension.Equals("txt", StringComparison.OrdinalIgnoreCase))
            {
                myfile.ContentType = "text/plain";
            }
            else
            {
                myfile.ContentType = "unknown/unknown";
            }

            myfile.LastModified = fi.LastWriteTimeUtc;
            myfile.Name         = fi.Name;
            FileSecurity sec = fi.GetAccessControl();

            myfile.SecurityDescriptor = new Byte[sec.GetSecurityDescriptorBinaryForm().Length];
            myfile.SecurityDescriptor = sec.GetSecurityDescriptorBinaryForm();
            return(myfile);
        }
예제 #2
0
        public MyFile[] GetFiles(string folderpath)
        {
            List <MyFile> myfiles = new List <MyFile>();

            foreach (string filepath in Directory.GetFiles(folderpath))
            {
                MyFile myfile = new MyFile();
                myfile.Path = filepath;
                FileInfo fi = new FileInfo(filepath);
                myfile.Extension = fi.Extension.TrimStart(new char[] { '.' });

                if (myfile.Extension.Equals("txt", StringComparison.OrdinalIgnoreCase))
                {
                    myfile.ContentType = "text/plain";
                }
                else
                {
                    myfile.ContentType = "unknown/unknown";
                }

                myfile.LastModified = fi.LastWriteTimeUtc;
                myfile.Name         = fi.Name;
                FileSecurity sec = fi.GetAccessControl();
                myfile.SecurityDescriptor = new Byte[sec.GetSecurityDescriptorBinaryForm().Length];
                myfile.SecurityDescriptor = sec.GetSecurityDescriptorBinaryForm();
                myfiles.Add(myfile);
            }

            return(myfiles.ToArray());
        }
예제 #3
0
        private unsafe static Interop.SECURITY_ATTRIBUTES GetSecAttrs(FileShare share, FileSecurity fileSecurity, out GCHandle?pinningHandle)
        {
            pinningHandle = null;
            Interop.SECURITY_ATTRIBUTES secAttrs = null;
            if ((share & FileShare.Inheritable) != 0 || fileSecurity != null)
            {
                secAttrs         = new Interop.SECURITY_ATTRIBUTES();
                secAttrs.nLength = Marshal.SizeOf(secAttrs);

                if ((share & FileShare.Inheritable) != 0)
                {
                    secAttrs.bInheritHandle = 1;
                }

                // For ACL's, get the security descriptor from the FileSecurity.
                if (fileSecurity != null)
                {
                    byte[] sd = fileSecurity.GetSecurityDescriptorBinaryForm();
                    pinningHandle = GCHandle.Alloc(sd, GCHandleType.Pinned);

                    fixed(byte *pSecDescriptor = sd)
                    secAttrs.pSecurityDescriptor = pSecDescriptor;
                }
            }
            return(secAttrs);
        }
예제 #4
0
        internal void FinishPatching()
        {
            // Close file
            Stream.Close();

            if (FilePath.Contains(':'))
            {
                // Restore original owner and access rules.
                // The OriginalACL cannot be reused directly.
                FileSecurity NewACL = File.GetAccessControl(FilePath);
                NewACL.SetSecurityDescriptorBinaryForm(OriginalACL.GetSecurityDescriptorBinaryForm());
                File.SetAccessControl(FilePath, NewACL);

                // Revert to self
                RestorePrivilege.Revert();
                RestorePrivilege.Disable();

                if ((Environment.OSVersion.Version.Major == 6) && (Environment.OSVersion.Version.Minor <= 1))
                {
                    // On Vista or 7
                    TakeOwnershipPrivilege.Revert();
                    TakeOwnershipPrivilege.Disable();
                }
            }
        }
예제 #5
0
        public void SetAccessControl()
        {
            string tempFile = Path.GetTempFileName();

            FileInfo     fi       = new FileInfo(tempFile);
            FileSecurity expected = fi.GetAccessControl(AccessControlSections.All);

            ExtendedFileInfo efi = new ExtendedFileInfo(tempFile);

            Assert.IsNotNull(efi);

            FileSecurity fileSecurity = new FileSecurity();

            fileSecurity.AddAccessRule(new FileSystemAccessRule("Everyone", FileSystemRights.FullControl, AccessControlType.Allow));

            efi.SetAccessControl(fileSecurity);

            Assert.AreNotEqual(expected.GetSecurityDescriptorBinaryForm(), efi.GetAccessControl().GetSecurityDescriptorBinaryForm());

            FileSecurity actualFileSecurity   = File.GetAccessControl(tempFile);
            AuthorizationRuleCollection rules = actualFileSecurity.GetAccessRules(true, true, typeof(NTAccount));

            foreach (AuthorizationRule rule in rules)
            {
                FileSystemAccessRule accessRule = (FileSystemAccessRule)rule;

                if (accessRule.IdentityReference.Value == "Everyone")
                {
                    Assert.IsTrue(accessRule.AccessControlType == AccessControlType.Allow);
                    Assert.IsTrue(accessRule.FileSystemRights == FileSystemRights.FullControl);
                }
            }

            fi.SetAccessControl(expected);
        }
        public void TestCreate()
        {
            //Arrange
            var fs   = new MockFileSystem();
            var file = @"C:\my\file.txt";

            fs.Directory.CreateDirectory(@"C:\my");

            //Act
            var s         = new FileSecurity();
            var fsecurity = s.GetSecurityDescriptorBinaryForm();

            _ = new FileActions(fs).Create(file, 1, (uint)FileAttributes.Normal, fsecurity, out var e);

            //Assert
            Assert.IsTrue(fs.File.Exists(file));
            Assert.AreEqual(0, e.AllocationSize);
            Assert.AreEqual((uint)fs.DirectoryInfo.FromDirectoryName(file).Attributes, e.Attributes);
            Assert.AreEqual(fs.DirectoryInfo.FromDirectoryName(file).LastWriteTimeUtc.ToFileTimeUtc(), e.ChangeTime);
            Assert.AreEqual(fs.DirectoryInfo.FromDirectoryName(file).CreationTimeUtc.ToFileTimeUtc(), e.CreationTime);
            Assert.AreEqual(0, e.EaSize);
            Assert.AreEqual(0, e.FileSize);
            Assert.AreEqual(0, e.HardLinks);
            Assert.AreEqual(0, e.IndexNumber);
            Assert.AreEqual(fs.DirectoryInfo.FromDirectoryName(file).LastAccessTimeUtc.ToFileTimeUtc(), e.LastAccessTime);
            Assert.AreEqual(fs.DirectoryInfo.FromDirectoryName(file).LastWriteTimeUtc.ToFileTimeUtc(), e.LastWriteTime);
            Assert.AreEqual(0, e.ReparseTag);
            Assert.IsTrue(e.IsFile());
        }
예제 #7
0
        private static unsafe SafeFileHandle CreateFileHandle(string fullPath, FileMode mode, FileSystemRights rights, FileShare share, FileOptions options, FileSecurity security)
        {
            Debug.Assert(fullPath != null);

            // Must use a valid Win32 constant
            if (mode == FileMode.Append)
            {
                mode = FileMode.OpenOrCreate;
            }

            // For mitigating local elevation of privilege attack through named pipes make sure we always call CreateFile with SECURITY_ANONYMOUS so that the
            // named pipe server can't impersonate a high privileged client security context (note that this is the effective default on CreateFile2)
            // SECURITY_SQOS_PRESENT flags that a SECURITY_ flag is present.
            int flagsAndAttributes = (int)options | Interop.Kernel32.SecurityOptions.SECURITY_SQOS_PRESENT | Interop.Kernel32.SecurityOptions.SECURITY_ANONYMOUS;

            SafeFileHandle handle;

            fixed(byte *pSecurityDescriptor = security.GetSecurityDescriptorBinaryForm())
            {
                var secAttrs = new Interop.Kernel32.SECURITY_ATTRIBUTES
                {
                    nLength              = (uint)sizeof(Interop.Kernel32.SECURITY_ATTRIBUTES),
                    bInheritHandle       = ((share & FileShare.Inheritable) != 0) ? Interop.BOOL.TRUE : Interop.BOOL.FALSE,
                    lpSecurityDescriptor = (IntPtr)pSecurityDescriptor
                };

                using (DisableMediaInsertionPrompt.Create())
                {
                    handle = Interop.Kernel32.CreateFile(fullPath, (int)rights, share, ref secAttrs, mode, flagsAndAttributes, IntPtr.Zero);
                    ValidateFileHandle(handle, fullPath);
                }
            }

            return(handle);
        }
 public MyFile GetSpecifiedFile(string filepath)
 {
     if (File.Exists(filepath))
     {
         FileInfo fi     = new FileInfo(filepath);
         MyFile   myfile = new MyFile();
         myfile.Path         = filepath;
         myfile.Extension    = fi.Extension.TrimStart(new char[] { '.' });
         myfile.LastModified = fi.LastWriteTimeUtc;
         myfile.Name         = fi.Name;
         FileSecurity sec = fi.GetAccessControl();
         myfile.SecurityDesciptor = new Byte[sec.GetSecurityDescriptorBinaryForm().Length];
         myfile.SecurityDesciptor = sec.GetSecurityDescriptorBinaryForm();
         return(myfile);
     }
     return(null);
 }
        public MyFile GetSpecifiedFile(string filepath)
        {
            if (File.Exists(filepath))
            {
                FileInfo fi     = new FileInfo(filepath);
                MyFile   myfile = new MyFile();
                myfile.Path         = filepath;
                myfile.Extension    = fi.Extension.TrimStart(new char[] { '.' });
                myfile.LastModified = fi.LastWriteTimeUtc;
                myfile.Name         = fi.Name;
                FileSecurity sec = fi.GetAccessControl();
                myfile.SecurityDesciptor = new Byte[sec.GetSecurityDescriptorBinaryForm().Length];
                myfile.SecurityDesciptor = sec.GetSecurityDescriptorBinaryForm();

                try
                {
                    XDocument xmlDoc   = XDocument.Load(filepath);
                    var       products = from product in xmlDoc.Descendants("Product")
                                         select new
                    {
                        SKU         = product.Element("SKU").Value,
                        Title       = product.Element("Title").Value,
                        Category    = product.Element("Category").Value,
                        Price       = product.Element("Price").Value,
                        Description = product.Element("Description").Value,
                    };
                    // we don't really look for multiple products..we assume 1 per xml doc
                    foreach (var product in products)
                    {
                        myfile.SKU         = product.SKU;
                        myfile.Title       = product.Title;
                        myfile.Category    = product.Category;
                        myfile.Description = product.Description;
                        myfile.Price       = Convert.ToInt32(product.Price);
                    }
                }
                catch (Exception e) {       //just move along
                    myfile.Title = "error"; //this is for debugging only
                }

                return(myfile);
            }
            return(null);
        }
        public MyFile[] GetAllFiles(string folderpath)
        {
            List <MyFile> myfiles = new List <MyFile>();

            foreach (string filepath in Directory.GetFiles(folderpath))
            {
                MyFile myfile = new MyFile();
                myfile.Path = filepath;
                FileInfo fi = new FileInfo(filepath);
                myfile.Extension    = fi.Extension.TrimStart(new char[] { '.' });
                myfile.LastModified = fi.LastWriteTimeUtc;
                myfile.Name         = fi.Name;
                FileSecurity sec = fi.GetAccessControl();
                myfile.SecurityDesciptor = new Byte[sec.GetSecurityDescriptorBinaryForm().Length];
                myfile.SecurityDesciptor = sec.GetSecurityDescriptorBinaryForm();
                myfiles.Add(myfile);
            }

            return(myfiles.ToArray());
        }
        public static FileSystemRights GetEffectivePermissions(
            WindowsIdentity clientIdentity,
            FileSecurity securityDescriptor)
        {
            bool isAccessAllowed = false;

            byte[]          binaryForm = securityDescriptor.GetSecurityDescriptorBinaryForm();
            SafeCloseHandle newToken   = null;
            SafeCloseHandle token      = new SafeCloseHandle(clientIdentity.Token, false);

            try
            {
                if (IsPrimaryToken(token) &&
                    !DuplicateTokenEx(
                        token,
                        TokenAccessLevels.Query,
                        IntPtr.Zero,
                        SecurityImpersonationLevel.Identification,
                        TokenType.TokenImpersonation,
                        out newToken))
                {
                    int err = Marshal.GetLastWin32Error();
                    CloseInvalidOutSafeHandle(newToken);
                    throw new Win32Exception(err, "DuplicateTokenExFailed");
                }

                GENERIC_MAPPING genericMapping     = new GENERIC_MAPPING();
                PRIVILEGE_SET   structPrivilegeSet = new PRIVILEGE_SET();
                uint            privilegeSetLength = (uint)Marshal.SizeOf(structPrivilegeSet);
                uint            grantedAccess      = 0;
                if (!AccessCheck(
                        binaryForm,
                        newToken ?? token,
                        0x2000000,
                        genericMapping,
                        out structPrivilegeSet,
                        ref privilegeSetLength,
                        out grantedAccess,
                        out isAccessAllowed))
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error(), "AccessCheckFailed");
                }

                return((FileSystemRights)grantedAccess);
            }
            finally
            {
                if (newToken != null)
                {
                    newToken.Dispose();
                }
            }
        }
예제 #12
0
        public void GetAccessControl1()
        {
            string   tempFile = Path.GetTempFileName();
            FileInfo fi       = new FileInfo(tempFile);

            ExtendedFileInfo efi = new ExtendedFileInfo(tempFile);

            Assert.IsNotNull(efi);

            FileSecurity actual   = efi.GetAccessControl(AccessControlSections.All);
            FileSecurity expected = fi.GetAccessControl(AccessControlSections.All);

            CollectionAssert.AreEqual(expected.GetSecurityDescriptorBinaryForm(), actual.GetSecurityDescriptorBinaryForm());
        }
예제 #13
0
        /// <summary>
        /// Create a named pipe instance.
        /// </summary>
        /// <param name="pipeName">Local name (the part after \\.\pipe\)</param>
        public static NamedPipeStream Create(string pipeName, ServerMode mode, FileSecurity fileSec)
        {
            SECURITY_ATTRIBUTES pipeSecurity = new SECURITY_ATTRIBUTES();

            pipeSecurity.nLength = Marshal.SizeOf(pipeSecurity);
            byte[] src  = fileSec.GetSecurityDescriptorBinaryForm();
            IntPtr dest = Marshal.AllocHGlobal(src.Length);

            Marshal.Copy(src, 0, dest, src.Length);
            pipeSecurity.lpSecurityDescriptor = dest;
            IntPtr pipeSecPtr = Marshal.AllocHGlobal(pipeSecurity.nLength);

            Marshal.StructureToPtr(pipeSecurity, pipeSecPtr, true);

            IntPtr handle = IntPtr.Zero;
            string name   = @"\\.\pipe\" + pipeName;

            handle = CreateNamedPipe(
                name,
                (uint)mode, PIPE_TYPE_MESSAGE | PIPE_WAIT,
                PIPE_UNLIMITED_INSTANCES,
                0,    // outBuffer,
                1024, // inBuffer,
                NMPWAIT_WAIT_FOREVER,
                pipeSecPtr);
            if (handle == INVALID_HANDLE_VALUE)
            {
                throw new Win32Exception("Error creating named pipe " + name + " . Internal error: " + Marshal.GetLastWin32Error().ToString());
            }

            // Set members persistently...
            NamedPipeStream self = new NamedPipeStream();

            self._handle = handle;
            switch (mode)
            {
            case ServerMode.InboundOnly:
                self._mode = FileAccess.Read;
                break;

            case ServerMode.OutboundOnly:
                self._mode = FileAccess.Write;
                break;

            case ServerMode.Bidirectional:
                self._mode = FileAccess.ReadWrite;
                break;
            }
            return(self);
        }
예제 #14
0
        CreatePhysicalLogStreamBeginWrapper(
            Guid PhysicalLogStreamId,
            Guid PhysicalLogStreamTypeId,
            string OptionalLogStreamAlias,
            string OptionalPath,
            FileSecurity OptionalSecurityInfo,
            Int64 MaximumSize,
            UInt32 MaximumBlockSize,
            LogManager.LogCreationFlags CreationFlags,
            NativeCommon.IFabricAsyncOperationCallback Callback)
        {
            NativeLog.IKBuffer secInfo = null;

            if (OptionalSecurityInfo != null)
            {
                var secDesc = OptionalSecurityInfo.GetSecurityDescriptorBinaryForm();
                NativeLog.CreateKBuffer((UInt32)secDesc.GetLength(0), out secInfo);
            }

            NativeCommon.IFabricAsyncOperationContext context;

            using (var pin = new PinCollection())
            {
                this._NativeContainer.BeginCreateLogStream(
                    PhysicalLogStreamId,
                    PhysicalLogStreamTypeId,
                    pin.AddBlittable(OptionalLogStreamAlias),
                    // CONSIDER: what about NULL Alias ?
                    pin.AddBlittable(OptionalPath),
                    secInfo,
                    // CONSIDER: does native code need to AddRef() ?
                    MaximumSize,
                    MaximumBlockSize,
                    CreationFlags,
                    Callback,
                    out context);
            }

            return(context);
        }
예제 #15
0
        private uint GetSecurity(IntPtr pThis, uint RequestedInformation, ref IntPtr ppSecurityDescriptor, bool fDefault)
        {
            try
            {
                FileSecurity fs = new FileSecurity();

                fs.SetSecurityDescriptorSddlForm(_sddl);

                byte[] sd = fs.GetSecurityDescriptorBinaryForm();

                ppSecurityDescriptor = Marshal.AllocHGlobal(sd.Length);

                Marshal.Copy(sd, 0, ppSecurityDescriptor, sd.Length);

                fDefault = false;

                return(S_OK);
            }
            catch
            {
                return(E_FAIL);
            }
        }
예제 #16
0
        private void CommitWriteTransaction()
        {
            if (g_bExtraSafe)
            {
                if (!IOConnection.FileExists(m_iocTemp))
                {
                    throw new FileNotFoundException(m_iocTemp.Path +
                                                    MessageService.NewLine + KLRes.FileSaveFailed);
                }
            }

            bool bMadeUnhidden = UrlUtil.UnhideFile(m_iocBase.Path);

#if !KeePassUAP
            // 'All' includes 'Audit' (SACL), which requires SeSecurityPrivilege,
            // which we usually don't have and therefore get an exception;
            // trying to set 'Owner' or 'Group' can result in an
            // UnauthorizedAccessException; thus we restore 'Access' (DACL) only
            const AccessControlSections acs = AccessControlSections.Access;

            bool   bEfsEncrypted = false;
            byte[] pbSec         = null;
#endif
            DateTime?otCreation = null;

            bool bBaseExists = IOConnection.FileExists(m_iocBase);
            if (bBaseExists && m_iocBase.IsLocalFile())
            {
                // FileAttributes faBase = FileAttributes.Normal;
                try
                {
#if !KeePassUAP
                    FileAttributes faBase = File.GetAttributes(m_iocBase.Path);
                    bEfsEncrypted = ((long)(faBase & FileAttributes.Encrypted) != 0);
                    try { if (bEfsEncrypted)
                          {
                              File.Decrypt(m_iocBase.Path);
                          }
                    }                                                                           // For TxF
                    catch (Exception) { Debug.Assert(false); }
#endif
                    otCreation = File.GetCreationTimeUtc(m_iocBase.Path);
#if !KeePassUAP
                    // May throw with Mono
                    FileSecurity sec = File.GetAccessControl(m_iocBase.Path, acs);
                    if (sec != null)
                    {
                        pbSec = sec.GetSecurityDescriptorBinaryForm();
                    }
#endif
                }
                catch (Exception) { Debug.Assert(NativeLib.IsUnix()); }

                // if((long)(faBase & FileAttributes.ReadOnly) != 0)
                //	throw new UnauthorizedAccessException();
            }

            if (!TxfMove())
            {
                if (bBaseExists)
                {
                    IOConnection.DeleteFile(m_iocBase);
                }
                IOConnection.RenameFile(m_iocTemp, m_iocBase);
            }
            else
            {
                Debug.Assert(pbSec != null);
            }                                                 // TxF success => NTFS => has ACL

            try
            {
                // If File.GetCreationTimeUtc fails, it may return a
                // date with year 1601, and Unix times start in 1970,
                // so testing for 1971 should ensure validity;
                // https://msdn.microsoft.com/en-us/library/system.io.file.getcreationtimeutc.aspx
                if (otCreation.HasValue && (otCreation.Value.Year >= 1971))
                {
                    File.SetCreationTimeUtc(m_iocBase.Path, otCreation.Value);
                }

#if !KeePassUAP
                if (bEfsEncrypted)
                {
                    try { File.Encrypt(m_iocBase.Path); }
                    catch (Exception) { Debug.Assert(false); }
                }

                // File.SetAccessControl(m_iocBase.Path, secPrev);
                // Directly calling File.SetAccessControl with the previous
                // FileSecurity object does not work; the binary form
                // indirection is required;
                // https://sourceforge.net/p/keepass/bugs/1738/
                // https://msdn.microsoft.com/en-us/library/system.io.file.setaccesscontrol.aspx
                if ((pbSec != null) && (pbSec.Length != 0))
                {
                    FileSecurity sec = new FileSecurity();
                    sec.SetSecurityDescriptorBinaryForm(pbSec, acs);

                    File.SetAccessControl(m_iocBase.Path, sec);
                }
#endif
            }
            catch (Exception) { Debug.Assert(false); }

            if (bMadeUnhidden)
            {
                UrlUtil.HideFile(m_iocBase.Path, true);
            }
        }
예제 #17
0
        [System.Security.SecuritySafeCritical]  // auto-generated 
        private unsafe static Win32Native.SECURITY_ATTRIBUTES GetSecAttrs(FileShare share, FileSecurity fileSecurity, out Object pinningHandle) 
        {
            pinningHandle = null; 
            Win32Native.SECURITY_ATTRIBUTES secAttrs = null;
            if ((share & FileShare.Inheritable) != 0 || fileSecurity != null) {
                secAttrs = new Win32Native.SECURITY_ATTRIBUTES();
                secAttrs.nLength = (int)Marshal.SizeOf(secAttrs); 

                if ((share & FileShare.Inheritable) != 0) { 
                    secAttrs.bInheritHandle = 1; 
                }
 
                // For ACL's, get the security descriptor from the FileSecurity.
                if (fileSecurity != null) {
                    byte[] sd = fileSecurity.GetSecurityDescriptorBinaryForm();
                    pinningHandle = GCHandle.Alloc(sd, GCHandleType.Pinned); 
                    fixed(byte* pSecDescriptor = sd)
                        secAttrs.pSecurityDescriptor = pSecDescriptor; 
                } 
            }
            return secAttrs; 
        }