Class: File

Inherits:
Object
  • Object
show all
Extended by:
Windows::File::Constants, Windows::File::Functions, Windows::File::Structs
Includes:
Windows::File::Constants, Windows::File::Functions
Defined in:
lib/win32/file/security.rb

Constant Summary collapse

WIN32_FILE_SECURITY_VERSION =

The version of the win32-file library

'1.0.10'.freeze

Constants included from Windows::File::Constants

Windows::File::Constants::ACCESS_ALLOWED_ACE_TYPE, Windows::File::Constants::ACCESS_SYSTEM_SECURITY, Windows::File::Constants::ACL_REVISION2, Windows::File::Constants::ADD, Windows::File::Constants::ALLOW_ACE_LENGTH, Windows::File::Constants::CHANGE, Windows::File::Constants::CONTAINER_INHERIT_ACE, Windows::File::Constants::DACL_SECURITY_INFORMATION, Windows::File::Constants::DELETE, Windows::File::Constants::ERROR_INSUFFICIENT_BUFFER, Windows::File::Constants::ERROR_NOT_SUPPORTED, Windows::File::Constants::ERROR_NO_SECURITY_ON_OBJECT, Windows::File::Constants::FILE_ADD_FILE, Windows::File::Constants::FILE_ADD_SUBDIRECTORY, Windows::File::Constants::FILE_ALL_ACCESS, Windows::File::Constants::FILE_APPEND_DATA, Windows::File::Constants::FILE_CASE_PRESERVED_NAMES, Windows::File::Constants::FILE_CASE_SENSITIVE_SEARCH, Windows::File::Constants::FILE_CREATE_PIPE_INSTANCE, Windows::File::Constants::FILE_DELETE_CHILD, Windows::File::Constants::FILE_ENCRYPTABLE, Windows::File::Constants::FILE_EXECUTE, Windows::File::Constants::FILE_FILE_COMPRESSION, Windows::File::Constants::FILE_GENERIC_EXECUTE, Windows::File::Constants::FILE_GENERIC_READ, Windows::File::Constants::FILE_GENERIC_WRITE, Windows::File::Constants::FILE_IS_ENCRYPTED, Windows::File::Constants::FILE_LIST_DIRECTORY, Windows::File::Constants::FILE_NOTIFY_CHANGE_ATTRIBUTES, Windows::File::Constants::FILE_NOTIFY_CHANGE_CREATION, Windows::File::Constants::FILE_NOTIFY_CHANGE_DIR_NAME, Windows::File::Constants::FILE_NOTIFY_CHANGE_FILE_NAME, Windows::File::Constants::FILE_NOTIFY_CHANGE_LAST_ACCESS, Windows::File::Constants::FILE_NOTIFY_CHANGE_LAST_WRITE, Windows::File::Constants::FILE_NOTIFY_CHANGE_SECURITY, Windows::File::Constants::FILE_NOTIFY_CHANGE_SIZE, Windows::File::Constants::FILE_PERSISTENT_ACLS, Windows::File::Constants::FILE_READ_ATTRIBUTES, Windows::File::Constants::FILE_READ_DATA, Windows::File::Constants::FILE_READ_EA, Windows::File::Constants::FILE_READ_ONLY, Windows::File::Constants::FILE_READ_PROPERTIES, Windows::File::Constants::FILE_ROOT_DIR, Windows::File::Constants::FILE_SHARE_DELETE, Windows::File::Constants::FILE_SHARE_READ, Windows::File::Constants::FILE_SHARE_WRITE, Windows::File::Constants::FILE_SUPPORTS_ENCRYPTION, Windows::File::Constants::FILE_SUPPORTS_OBJECT_IDS, Windows::File::Constants::FILE_SUPPORTS_REMOTE_STORAGE, Windows::File::Constants::FILE_SUPPORTS_REPARSE_POINTS, Windows::File::Constants::FILE_SUPPORTS_SPARSE_FILES, Windows::File::Constants::FILE_SYSTEM_ATTR, Windows::File::Constants::FILE_SYSTEM_DIR, Windows::File::Constants::FILE_SYSTEM_NOT_SUPPORT, Windows::File::Constants::FILE_TRAVERSE, Windows::File::Constants::FILE_UNICODE_ON_DISK, Windows::File::Constants::FILE_UNKNOWN, Windows::File::Constants::FILE_VOLUME_IS_COMPRESSED, Windows::File::Constants::FILE_VOLUME_QUOTAS, Windows::File::Constants::FILE_WRITE_ATTRIBUTES, Windows::File::Constants::FILE_WRITE_DATA, Windows::File::Constants::FILE_WRITE_EA, Windows::File::Constants::FILE_WRITE_PROPERTIES, Windows::File::Constants::FULL, Windows::File::Constants::GENERIC_ALL, Windows::File::Constants::GENERIC_EXECUTE, Windows::File::Constants::GENERIC_READ, Windows::File::Constants::GENERIC_RIGHTS_CHK, Windows::File::Constants::GENERIC_WRITE, Windows::File::Constants::GROUP_SECURITY_INFORMATION, Windows::File::Constants::INHERIT_ONLY_ACE, Windows::File::Constants::MAXDWORD, Windows::File::Constants::MAXIMUM_ALLOWED, Windows::File::Constants::OBJECT_INHERIT_ACE, Windows::File::Constants::OWNER_SECURITY_INFORMATION, Windows::File::Constants::READ, Windows::File::Constants::READ_CONTROL, Windows::File::Constants::REST_RIGHTS_MASK, Windows::File::Constants::SECURITY_DESCRIPTOR_MIN_LENGTH, Windows::File::Constants::SECURITY_DESCRIPTOR_REVISION, Windows::File::Constants::SE_BACKUP_NAME, Windows::File::Constants::SE_CHANGE_NOTIFY_NAME, Windows::File::Constants::SE_DACL_PRESENT, Windows::File::Constants::SE_FILE_OBJECT, Windows::File::Constants::SE_KERNEL_OBJECT, Windows::File::Constants::SE_PRIVILEGE_ENABLED, Windows::File::Constants::SE_RESTORE_NAME, Windows::File::Constants::SE_SECURITY_NAME, Windows::File::Constants::SE_TAKE_OWNERSHIP_NAME, Windows::File::Constants::SPECIFIC_RIGHTS_ALL, Windows::File::Constants::STANDARD_RIGHTS_ALL, Windows::File::Constants::STANDARD_RIGHTS_EXECUTE, Windows::File::Constants::STANDARD_RIGHTS_READ, Windows::File::Constants::STANDARD_RIGHTS_REQUIRED, Windows::File::Constants::STANDARD_RIGHTS_WRITE, Windows::File::Constants::SYNCHRONIZE, Windows::File::Constants::TOKEN_ADJUST_PRIVILEGES, Windows::File::Constants::TOKEN_QUERY, Windows::File::Constants::TokenGroups, Windows::File::Constants::TokenUser, Windows::File::Constants::WRITE_DAC, Windows::File::Constants::WRITE_OWNER

Class Method Summary collapse

Class Method Details

.chown(owner, group, *files) ⇒ Object

Changes the owner of the named file(s) to the given owner (userid). It will typically require elevated privileges in order to change the owner of a file.

This group argument is currently ignored, but is included in the method definition for compatibility with the current spec. Also note that the owner should be a string, not a numeric ID.

Example:

File.chown('some_user', nil, 'some_file.txt')

– In the future we may allow the owner argument to be a SID or a RID and simply adjust accordingly.



636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
# File 'lib/win32/file/security.rb', line 636

def chown(owner, group, *files)
  token = FFI::MemoryPointer.new(:ulong)

  begin
    bool = OpenProcessToken(
      GetCurrentProcess(),
      TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY,
      token
    )

    raise SystemCallError.new("OpenProcessToken", FFI.errno) unless bool

    token_handle = token.read_ulong

    privs = [
      SE_SECURITY_NAME,
      SE_TAKE_OWNERSHIP_NAME,
      SE_BACKUP_NAME,
      SE_RESTORE_NAME,
      SE_CHANGE_NOTIFY_NAME
    ]

    privs.each{ |name|
      luid = LUID.new

      unless LookupPrivilegeValueA(nil, name, luid)
        raise SystemCallError.new("LookupPrivilegeValue", FFI.errno)
      end

      tp = TOKEN_PRIVILEGES.new
      tp[:PrivilegeCount] = 1
      tp[:Privileges][0][:Luid] = luid
      tp[:Privileges][0][:Attributes] = SE_PRIVILEGE_ENABLED

      unless AdjustTokenPrivileges(token_handle, 0, tp, 0, nil, nil)
        raise SystemCallError.new("AdjustTokenPrivileges", FFI.errno)
      end
    }

    sid      = FFI::MemoryPointer.new(:uchar)
    sid_size = FFI::MemoryPointer.new(:ulong)
    dom      = FFI::MemoryPointer.new(:uchar)
    dom_size = FFI::MemoryPointer.new(:ulong)
    use      = FFI::MemoryPointer.new(:ulong)

    wowner = owner.wincode

    # First run, get needed sizes
    LookupAccountNameW(nil, wowner, sid, sid_size, dom, dom_size, use)

    sid = FFI::MemoryPointer.new(:uchar, sid_size.read_ulong * 2)
    dom = FFI::MemoryPointer.new(:uchar, dom_size.read_ulong * 2)

    # Second run with required sizes
    unless LookupAccountNameW(nil, wowner, sid, sid_size, dom, dom_size, use)
      raise SystemCallError.new("LookupAccountName", FFI.errno)
    end

    files.each{ |file|
      wfile = string_check(file).wincode

      size = FFI::MemoryPointer.new(:ulong)
      sec  = FFI::MemoryPointer.new(:ulong)

      # First pass, get the size needed
      GetFileSecurityW(wfile, OWNER_SECURITY_INFORMATION, sec, sec.size, size)

      security = FFI::MemoryPointer.new(size.read_ulong)

      # Second pass, this time with the appropriately sized security pointer
      bool = GetFileSecurityW(
        wfile,
        OWNER_SECURITY_INFORMATION,
        security,
        security.size,
        size
      )

      raise SystemCallError.new("GetFileSecurity", FFI.errno) unless bool

      unless InitializeSecurityDescriptor(security, SECURITY_DESCRIPTOR_REVISION)
        raise SystemCallError.new("InitializeSecurityDescriptor", FFI.errno)
      end

      unless SetSecurityDescriptorOwner(security, sid, 0)
        raise SystemCallError.new("SetSecurityDescriptorOwner", FFI.errno)
      end

      unless SetFileSecurityW(wfile, OWNER_SECURITY_INFORMATION, security)
        raise SystemCallError.new("SetFileSecurity", FFI.errno)
      end
    }
  ensure
    CloseHandle(token.read_ulong)
  end

  files.size
end

.decrypt(file) ⇒ Object

Decrypts an encrypted file or directory.

The caller must have the FILE_READ_DATA, FILE_WRITE_DATA, FILE_READ_ATTRIBUTES, FILE_WRITE_ATTRIBUTES, and SYNCHRONIZE access rights.

Requires exclusive access to the file being decrypted, and will fail if another process is using the file. If the file is not encrypted an error is NOT raised, it’s simply a no-op.



175
176
177
178
179
180
# File 'lib/win32/file/security.rb', line 175

def decrypt(file)
  unless DecryptFileW(string_check(file).wincode, 0)
    raise SystemCallError.new("DecryptFile", FFI.errno)
  end
  self
end

.encrypt(file) ⇒ Object

Encrypts a file or directory. All data streams in a file are encrypted. All new files created in an encrypted directory are encrypted.

The caller must have the FILE_READ_DATA, FILE_WRITE_DATA, FILE_READ_ATTRIBUTES, FILE_WRITE_ATTRIBUTES, and SYNCHRONIZE access rights.

Requires exclusive access to the file being encrypted, and will fail if another process is using the file or the file is marked read-only. If the file is compressed the file will be decompressed before encrypting it.



158
159
160
161
162
163
# File 'lib/win32/file/security.rb', line 158

def encrypt(file)
  unless EncryptFileW(string_check(file).wincode)
    raise SystemCallError.new("EncryptFile", FFI.errno)
  end
  self
end

.encryptable?(file = nil) ⇒ Boolean

Returns whether or not the root path of the specified file is encryptable. If no path or a relative path is specified, it will check against the root of the current directory.

Be sure to include a trailing slash if specifying a root path.

Examples:

p File.encryptable?
p File.encryptable?("D:/")
p File.encryptable?("C:/foo/bar.txt") # Same as 'C:\'

Returns:

  • (Boolean)


74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
# File 'lib/win32/file/security.rb', line 74

def encryptable?(file = nil)
  bool = false
  flags_ptr = FFI::MemoryPointer.new(:ulong)

  if file
    file = File.expand_path(string_check(file))
    wide_file = file.wincode

    if !PathIsRootW(wide_file)
      unless PathStripToRootW(wide_file)
        raise SystemCallError.new("PathStripToRoot", FFI.errno)
      end
    end
  else
    wide_file = nil
  end

  unless GetVolumeInformationW(wide_file, nil, 0, nil, nil, flags_ptr, nil, 0)
    raise SystemCallError.new("GetVolumeInformation", FFI.errno)
  end

  flags = flags_ptr.read_ulong

  if flags & FILE_SUPPORTS_ENCRYPTION > 0
    bool = true
  end

  bool
end

.encryption_status(file) ⇒ Object

Returns the encryption status of a file as a string. Possible return values are:

  • encryptable

  • encrypted

  • readonly

  • root directory (i.e. not encryptable)

  • system file (i.e. not encryptable)

  • unsupported

  • unknown



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/win32/file/security.rb', line 32

def encryption_status(file)
  wide_file  = string_check(file).wincode
  status_ptr = FFI::MemoryPointer.new(:ulong)

  unless FileEncryptionStatusW(wide_file, status_ptr)
    raise SystemCallError.new("FileEncryptionStatus", FFI.errno)
  end

  status = status_ptr.read_ulong

  rvalue = case status
    when FILE_ENCRYPTABLE
      "encryptable"
    when FILE_IS_ENCRYPTED
      "encrypted"
    when FILE_READ_ONLY
      "readonly"
    when FILE_ROOT_DIR
      "root directory"
    when FILE_SYSTEM_ATTR
      "system file"
    when FILE_SYSTEM_NOT_SUPPORTED
      "unsupported"
    else
      "unknown"
  end

  rvalue
end

.get_permissions(file, host = nil) ⇒ Object

Returns a hash describing the current file permissions for the given file. The account name is the key, and the value is an integer mask that corresponds to the security permissions for that file.

To get a human readable version of the permissions, pass the value to the File.securities method.

You may optionally specify a host as the second argument. If no host is specified then the current host is used.

Examples:

hash = File.get_permissions('test.txt')

p hash # => {"NT AUTHORITY\\SYSTEM"=>2032127, "BUILTIN\\Administrators"=>2032127, ...}

hash.each{ |name, mask|
  p name
  p File.securities(mask)
}

Raises:

  • (SystemCallError)


203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
# File 'lib/win32/file/security.rb', line 203

def get_permissions(file, host=nil)
  # Check local filesystem to see if it supports ACL's. If not, bail early
  # because the GetFileSecurity function will not fail on an unsupported FS.
  if host.nil?
    unless supports_acls?(file)
      raise ArgumentError, "Filesystem does not implement ACL support"
    end
  end

  wide_file = string_check(file).wincode
  wide_host = host ? host.wincode : nil

  size_needed_ptr = FFI::MemoryPointer.new(:ulong)
  security_ptr    = FFI::MemoryPointer.new(:ulong)

  # First pass, get the size needed
  bool = GetFileSecurityW(
    wide_file,
    DACL_SECURITY_INFORMATION,
    security_ptr,
    security_ptr.size,
    size_needed_ptr
  )

  errno = FFI.errno

  if !bool && errno != ERROR_INSUFFICIENT_BUFFER
    raise SystemCallError.new("GetFileSecurity", errno)
  end

  size_needed = size_needed_ptr.read_ulong

  security_ptr = FFI::MemoryPointer.new(size_needed)

  # Second pass, this time with the appropriately sized security pointer
  bool = GetFileSecurityW(
    wide_file,
    DACL_SECURITY_INFORMATION,
    security_ptr,
    security_ptr.size,
    size_needed_ptr
  )

  raise SystemCallError.new("GetFileSecurity", FFI.errno) unless bool

  control_ptr  = FFI::MemoryPointer.new(:ulong)
  revision_ptr = FFI::MemoryPointer.new(:ulong)

  unless GetSecurityDescriptorControl(security_ptr, control_ptr, revision_ptr)
    raise SystemCallError.new("GetSecurityDescriptorControl", FFI.errno)
  end

  control = control_ptr.read_ulong

  if control & SE_DACL_PRESENT == 0
    raise ArgumentError, "No DACL present: explicit deny all"
  end

  dacl_pptr          = FFI::MemoryPointer.new(:pointer)
  dacl_present_ptr   = FFI::MemoryPointer.new(:bool)
  dacl_defaulted_ptr = FFI::MemoryPointer.new(:ulong)

  bool = GetSecurityDescriptorDacl(
    security_ptr,
    dacl_present_ptr,
    dacl_pptr,
    dacl_defaulted_ptr
  )

  unless bool
    raise SystemCallError.new("GetSecurityDescriptorDacl", FFI.errno)
  end

  acl = ACL.new(dacl_pptr.read_pointer)

  if acl[:AclRevision] == 0
    raise ArgumentError, "DACL is NULL: implicit access grant"
  end

  ace_count  = acl[:AceCount]
  perms_hash = {}

  0.upto(ace_count - 1){ |i|
    ace_pptr = FFI::MemoryPointer.new(:pointer)
    next unless GetAce(acl, i, ace_pptr)

    access = ACCESS_ALLOWED_ACE.new(ace_pptr.read_pointer)

    if access[:Header][:AceType] == ACCESS_ALLOWED_ACE_TYPE
      name = FFI::MemoryPointer.new(:uchar, 260)
      name_size = FFI::MemoryPointer.new(:ulong)
      name_size.write_ulong(name.size)

      domain = FFI::MemoryPointer.new(:uchar, 260)
      domain_size = FFI::MemoryPointer.new(:ulong)
      domain_size.write_ulong(domain.size)

      use_ptr = FFI::MemoryPointer.new(:pointer)

      bool = LookupAccountSidW(
        wide_host,
        ace_pptr.read_pointer + 8,
        name,
        name_size,
        domain,
        domain_size,
        use_ptr
      )

      raise SystemCallError.new("LookupAccountSid", FFI.errno) unless bool

      # The x2 multiplier is necessary due to wide char strings.
      name = name.read_string(name_size.read_ulong * 2).wstrip

      dsize = domain_size.read_ulong

      # It's possible there is no domain.
      if dsize > 0
        domain = domain.read_string(dsize * 2).wstrip

        unless domain.empty?
          name = domain + '\\' + name
        end
      end

      perms_hash[name] = access[:Mask]
    end
  }

  perms_hash
end

.group(file) ⇒ Object

Returns the primary group of the specified file in domain\userid format.

Example:

p File.group('some_file.txt') # => "your_domain\\some_group"

Raises:

  • (SystemCallError)


805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
# File 'lib/win32/file/security.rb', line 805

def group(file)
  file = string_check(file).wincode
  size_needed = FFI::MemoryPointer.new(:ulong)

  # First pass, get the size needed
  bool = GetFileSecurityW(
    file,
    GROUP_SECURITY_INFORMATION,
    nil,
    0,
    size_needed
  )

  security = FFI::MemoryPointer.new(size_needed.read_ulong)

  # Second pass, this time with the appropriately sized security pointer
  bool = GetFileSecurityW(
    file,
    GROUP_SECURITY_INFORMATION,
    security,
    security.size,
    size_needed
  )

  raise SystemCallError.new("GetFileSecurity", FFI.errno) unless bool

  sid = FFI::MemoryPointer.new(:pointer)
  defaulted = FFI::MemoryPointer.new(:int)

  unless GetSecurityDescriptorGroup(security, sid, defaulted)
    raise SystemCallError.new("GetFileSecurity", FFI.errno)
  end

  sid = sid.read_pointer

  name      = FFI::MemoryPointer.new(:uchar)
  name_size = FFI::MemoryPointer.new(:ulong)
  dom       = FFI::MemoryPointer.new(:uchar)
  dom_size  = FFI::MemoryPointer.new(:ulong)
  use       = FFI::MemoryPointer.new(:int)

  # First call, get sizes needed
  LookupAccountSidW(nil, sid, name, name_size, dom, dom_size, use)

  name = FFI::MemoryPointer.new(:uchar, name_size.read_ulong * 2)
  dom  = FFI::MemoryPointer.new(:uchar, dom_size.read_ulong * 2)

  # Second call, get desired information
  unless LookupAccountSidW(nil, sid, name, name_size, dom, dom_size, use)
    raise SystemCallError.new("LookupAccountSid", FFI.errno)
  end

  name = name.read_string(name.size).wstrip
  domain = dom.read_string(dom.size).wstrip

  domain << "\\" << name
end

.grpowned?(file) ⇒ Boolean

Returns true if the primary group ID of the process is the same as the owner of the named file.

Example:

p File.grpowned?('some_file.txt') # => true
p File.grpowned?('C:/Windows/regedit.exe') # => false

– This method was redefined for MS Windows.

Returns:

  • (Boolean)

Raises:

  • (SystemCallError)


873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
# File 'lib/win32/file/security.rb', line 873

def grpowned?(file)
  wide_file = string_check(file).wincode

  return_value = false
  size_needed_ptr = FFI::MemoryPointer.new(:ulong)

  # First pass, get the size needed
  bool = GetFileSecurityW(
    wide_file,
    GROUP_SECURITY_INFORMATION,
    nil,
    0,
    size_needed_ptr
  )

  size_needed = size_needed_ptr.read_ulong

  security_ptr = FFI::MemoryPointer.new(size_needed)

  # Second pass, this time with the appropriately sized security pointer
  bool = GetFileSecurityW(
    wide_file,
    GROUP_SECURITY_INFORMATION,
    security_ptr,
    security_ptr.size,
    size_needed_ptr
  )

  raise SystemCallError.new("GetFileSecurity", FFI.errno) unless bool

  sid_ptr = FFI::MemoryPointer.new(:pointer)
  defaulted = FFI::MemoryPointer.new(:int)
  pstring_sid = FFI::MemoryPointer.new(:string)

  unless GetSecurityDescriptorGroup(security_ptr, sid_ptr, defaulted)
    raise SystemCallError.new("GetFileSecurity", FFI.errno)
  end

  sid = sid_ptr.read_pointer
  ConvertSidToStringSidA(sid, pstring_sid)
  file_string_sid = pstring_sid.read_pointer.read_string

  token = FFI::MemoryPointer.new(:uintptr_t)

  begin
    # Get the current process sid
    unless OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, token)
      raise SystemCallError, FFI.errno, "OpenProcessToken"
    end

    token   = token.read_pointer.to_i
    rlength = FFI::MemoryPointer.new(:ulong)
    tgroup  = TOKEN_GROUP.new

    bool = GetTokenInformation(
      token,
      TokenGroups,
      tgroup,
      tgroup.size,
      rlength
    )

    unless bool
      raise SystemCallError.new("GetTokenInformation", FFI.errno)
    end

    ConvertSidToStringSidA(tgroup[:Groups][0][:Sid], pstring_sid)
    string_sid = pstring_sid.read_pointer.read_string

    # Now compare the sid strings
    if string_sid == file_string_sid
      return_value = true
    end
  ensure
    CloseHandle(token)
  end

  return_value
end

.owned?(file) ⇒ Boolean

Returns true if the effective user ID of the process is the same as the owner of the named file.

Example:

p File.owned?('some_file.txt') # => true
p File.owned?('C:/Windows/regedit.ext') # => false

– This method was redefined for MS Windows.

Returns:

  • (Boolean)

Raises:

  • (SystemCallError)


545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
# File 'lib/win32/file/security.rb', line 545

def owned?(file)
  wide_file = string_check(file).wincode

  return_value = false
  size_needed_ptr = FFI::MemoryPointer.new(:ulong)

  # First pass, get the size needed
  bool = GetFileSecurityW(
    wide_file,
    OWNER_SECURITY_INFORMATION,
    nil,
    0,
    size_needed_ptr
  )

  size_needed = size_needed_ptr.read_ulong

  security_ptr = FFI::MemoryPointer.new(size_needed)

  # Second pass, this time with the appropriately sized security pointer
  bool = GetFileSecurityW(
    wide_file,
    OWNER_SECURITY_INFORMATION,
    security_ptr,
    security_ptr.size,
    size_needed_ptr
  )

  raise SystemCallError.new("GetFileSecurity", FFI.errno) unless bool

  sid_ptr = FFI::MemoryPointer.new(:pointer)
  defaulted = FFI::MemoryPointer.new(:int)

  unless GetSecurityDescriptorOwner(security_ptr, sid_ptr, defaulted)
    raise SystemCallError.new("GetFileSecurity", FFI.errno)
  end

  sid = sid_ptr.read_pointer

  token = FFI::MemoryPointer.new(:uintptr_t)

  begin
    # Get the current process sid
    unless OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, token)
      raise SystemCallError, FFI.errno, "OpenProcessToken"
    end

    token   = token.read_pointer.to_i
    rlength = FFI::MemoryPointer.new(:pointer)
    tuser   = 0.chr * 512

    bool = GetTokenInformation(
      token,
      TokenUser,
      tuser,
      tuser.size,
      rlength
    )

    unless bool
      raise SystemCallError, FFI.errno, "GetTokenInformation"
    end

    string_sid = tuser[FFI.type_size(:pointer)*2, (rlength.read_ulong - FFI.type_size(:pointer)*2)]

    # Now compare the sid strings
    if string_sid == sid.read_string(string_sid.size)
      return_value = true
    end
  ensure
    CloseHandle(token)
  end

  return_value
end

.owner(file) ⇒ Object

Returns the owner of the specified file in domain\userid format.

Example:

p File.owner('some_file.txt') # => "your_domain\\some_user"

Raises:

  • (SystemCallError)


741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
# File 'lib/win32/file/security.rb', line 741

def owner(file)
  file = string_check(file).wincode
  size_needed = FFI::MemoryPointer.new(:ulong)

  # First pass, get the size needed
  bool = GetFileSecurityW(
    file,
    OWNER_SECURITY_INFORMATION,
    nil,
    0,
    size_needed
  )

  security = FFI::MemoryPointer.new(size_needed.read_ulong)

  # Second pass, this time with the appropriately sized security pointer
  bool = GetFileSecurityW(
    file,
    OWNER_SECURITY_INFORMATION,
    security,
    security.size,
    size_needed
  )

  raise SystemCallError.new("GetFileSecurity", FFI.errno) unless bool

  sid = FFI::MemoryPointer.new(:pointer)
  defaulted = FFI::MemoryPointer.new(:int)

  unless GetSecurityDescriptorOwner(security, sid, defaulted)
    raise SystemCallError.new("GetFileSecurity", FFI.errno)
  end

  sid = sid.read_pointer

  name      = FFI::MemoryPointer.new(:uchar)
  name_size = FFI::MemoryPointer.new(:ulong)
  dom       = FFI::MemoryPointer.new(:uchar)
  dom_size  = FFI::MemoryPointer.new(:ulong)
  use       = FFI::MemoryPointer.new(:int)

  # First call, get sizes needed
  LookupAccountSidW(nil, sid, name, name_size, dom, dom_size, use)

  name = FFI::MemoryPointer.new(:uchar, name_size.read_ulong * 2)
  dom  = FFI::MemoryPointer.new(:uchar, dom_size.read_ulong * 2)

  # Second call, get desired information
  unless LookupAccountSidW(nil, sid, name, name_size, dom, dom_size, use)
    raise SystemCallError.new("LookupAccountSid", FFI.errno)
  end

  name = name.read_string(name.size).wstrip
  domain = dom.read_string(dom.size).wstrip

  domain << "\\" << name
end

.securities(mask) ⇒ Object

Returns an array of human-readable strings that correspond to the permission flags.

Example:

File.get_permissions('test.txt').each{ |name, mask|
  puts name
  p File.securities(mask)
}


507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
# File 'lib/win32/file/security.rb', line 507

def securities(mask)
  sec_array = []

  security_rights = {
    'FULL'    => FULL,
    'DELETE'  => DELETE,
    'READ'    => READ,
    'CHANGE'  => CHANGE,
    'ADD'     => ADD
  }

  if mask == 0
    sec_array.push('NONE')
  else
    if (mask & FULL) ^ FULL == 0
      sec_array.push('FULL')
    else
      security_rights.each{ |string, numeric|
        if (numeric & mask) ^ numeric == 0
          sec_array.push(string)
        end
      }
    end
  end

  sec_array
end

.set_permissions(file, perms) ⇒ Object

Sets the file permissions for the given file name. The ‘permissions’ argument is a hash with an account name as the key, and the various permission constants as possible values. The possible constant values are:

  • FILE_READ_DATA

  • FILE_WRITE_DATA

  • FILE_APPEND_DATA

  • FILE_READ_EA

  • FILE_WRITE_EA

  • FILE_EXECUTE

  • FILE_DELETE_CHILD

  • FILE_READ_ATTRIBUTES

  • FILE_WRITE_ATTRIBUTES

  • FULL

  • READ

  • ADD

  • CHANGE

  • DELETE

  • READ_CONTROL

  • WRITE_DAC

  • WRITE_OWNER

  • SYNCHRONIZE

  • STANDARD_RIGHTS_ALL

  • STANDARD_RIGHTS_REQUIRED

  • STANDARD_RIGHTS_READ

  • STANDARD_RIGHTS_WRITE

  • STANDARD_RIGHTS_EXECUTE

  • SPECIFIC_RIGHTS_ALL

  • ACCESS_SYSTEM_SECURITY

  • MAXIMUM_ALLOWED

  • GENERIC_READ

  • GENERIC_WRITE

  • GENERIC_EXECUTE

  • GENERIC_ALL

Example:

# Set locally
File.set_permissions(file, "userid" => File::GENERIC_ALL)

# Set a remote system
File.set_permissions(file, "host\\userid" => File::GENERIC_ALL)

Raises:

  • (TypeError)


379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
# File 'lib/win32/file/security.rb', line 379

def set_permissions(file, perms)
  # Check local filesystem to see if it supports ACL's. If not, bail early
  # because the GetFileSecurity function will not fail on an unsupported FS.
  unless supports_acls?(file)
    raise ArgumentError, "Filesystem does not implement ACL support"
  end

  wide_file = string_check(file).wincode
  raise TypeError unless perms.kind_of?(Hash)

  sec_desc = FFI::MemoryPointer.new(:pointer, SECURITY_DESCRIPTOR_MIN_LENGTH)

  unless InitializeSecurityDescriptor(sec_desc, 1)
    raise SystemCallError.new("InitializeSecurityDescriptor", FFI.errno)
  end

  acl_new = FFI::MemoryPointer.new(ACL, 100)

  unless InitializeAcl(acl_new, acl_new.size, ACL_REVISION2)
    raise SystemCallError.new("InitializeAcl", FFI.errno)
  end

  perms.each{ |, mask|
    next if mask.nil?

    # reset account_rights for each entry in perms:
     = 0

    server,  = .split("\\")

    if ['BUILTIN', 'NT AUTHORITY'].include?(server.upcase)
      wide_server = nil
    elsif .nil?
      wide_server = nil
       = server
    else
      wide_server = server.wincode
    end

     = .wincode

    sid = FFI::MemoryPointer.new(:uchar, 1024)
    sid_size = FFI::MemoryPointer.new(:ulong)
    sid_size.write_ulong(sid.size)

    domain = FFI::MemoryPointer.new(:uchar, 260)
    domain_size = FFI::MemoryPointer.new(:ulong)
    domain_size.write_ulong(domain.size)

    use_ptr = FFI::MemoryPointer.new(:ulong)

    val = LookupAccountNameW(
       wide_server,
       ,
       sid,
       sid_size,
       domain,
       domain_size,
       use_ptr
    )

    raise SystemCallError.new("LookupAccountName", FFI.errno) unless val

    all_ace = ACCESS_ALLOWED_ACE2.new

    val = CopySid(
      ALLOW_ACE_LENGTH - ACCESS_ALLOWED_ACE.size,
      all_ace.to_ptr+8,
      sid
    )

    raise SystemCallError.new("CopySid", FFI.errno) unless val

    if (GENERIC_ALL & mask).nonzero?
       = GENERIC_ALL & mask
    elsif (GENERIC_RIGHTS_CHK & mask).nonzero?
       = GENERIC_RIGHTS_MASK & mask
    else
      # Do nothing, leave it set to zero.
    end

    all_ace[:Header][:AceFlags] = INHERIT_ONLY_ACE | OBJECT_INHERIT_ACE

    2.times{
      if  != 0
        all_ace[:Header][:AceSize] = 8 + GetLengthSid(sid)
        all_ace[:Mask] = 

        val = AddAce(
          acl_new,
          ACL_REVISION2,
          MAXDWORD,
          all_ace,
          all_ace[:Header][:AceSize]
        )

        raise SystemCallError.new("AddAce", FFI.errno) unless val

        all_ace[:Header][:AceFlags] = CONTAINER_INHERIT_ACE
      else
        all_ace[:Header][:AceFlags] = 0
      end

       = REST_RIGHTS_MASK & mask
    }
  }

  unless SetSecurityDescriptorDacl(sec_desc, 1, acl_new, 0)
    raise SystemCallError.new("SetSecurityDescriptorDacl", FFI.errno)
  end

  unless SetFileSecurityW(wide_file, DACL_SECURITY_INFORMATION, sec_desc)
    raise SystemCallError.new("SetFileSecurity", FFI.errno)
  end

  self
end

.supports_acls?(file = nil) ⇒ Boolean

Returns whether or not the root path of the specified file supports ACL’s. If no path or a relative path is specified, it will check against the root of the current directory.

Be sure to include a trailing slash if specifying a root path.

Examples:

p File.supports_acls?
p File.supports_acls?("D:/")
p File.supports_acls?("C:/foo/bar.txt") # Same as 'C:\'

Returns:

  • (Boolean)


117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
# File 'lib/win32/file/security.rb', line 117

def supports_acls?(file = nil)
  bool = false
  flags_ptr = FFI::MemoryPointer.new(:ulong)

  if file
    file = File.expand_path(string_check(file))
    wide_file = file.wincode

    if !PathIsRootW(wide_file)
      unless PathStripToRootW(wide_file)
        raise SystemCallError.new("PathStripToRoot", FFI.errno)
      end
    end
  else
    wide_file = nil
  end

  unless GetVolumeInformationW(wide_file, nil, 0, nil, nil, flags_ptr, nil, 0)
    raise SystemCallError.new("GetVolumeInformation", FFI.errno)
  end

  flags = flags_ptr.read_ulong

  if flags & FILE_PERSISTENT_ACLS > 0
    bool = true
  end

  bool
end