home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 9 Archive / 09-Archive.zip / zip22.zip / win32 / nt.c < prev    next >
C/C++ Source or Header  |  1997-10-15  |  15KB  |  474 lines

  1. /*++
  2.  
  3. Copyright (c) 1996  Scott Field
  4.  
  5. Module Name:
  6.  
  7.     nt.c (formerly nt_zip.c)
  8.  
  9. Abstract:
  10.  
  11.     This module implements WinNT security descriptor operations for the
  12.     Win32 Info-ZIP project.  Operation such as querying file security,
  13.     using/querying local and remote privileges.  The contents of this module
  14.     are only relevant when the code is running on Windows NT, and the target
  15.     volume supports persistent Acl storage.
  16.  
  17.     User privileges that allow accessing certain privileged aspects of the
  18.     security descriptor (such as the Sacl) are only used if the user specified
  19.     to do so.
  20.  
  21.     In the future, this module may be expanded to support storage of
  22.     OS/2 EA data, Macintosh resource forks, and hard links, which are all
  23.     supported by NTFS.
  24.  
  25. Author:
  26.  
  27.     Scott Field (sfield@microsoft.com)  27-Sep-96
  28.  
  29. --*/
  30.  
  31. #include "zip.h"
  32.  
  33. #define WIN32_LEAN_AND_MEAN
  34. #include <windows.h>
  35. #ifdef __RSXNT__
  36. #  include "win32/rsxntwin.h"
  37. #endif
  38. #include "win32/nt.h"
  39.  
  40. #ifdef NTSD_EAS         /* This file is only needed for NTSD handling */
  41.  
  42. /* Borland C++ does not define FILE_SHARE_DELETE. Others also? */
  43. #ifndef FILE_SHARE_DELETE
  44. #  define FILE_SHARE_DELETE 0x00000004
  45. #endif
  46.  
  47. #ifndef NO_NTSD_WITH_RSXNT  /* RSXNT windows.h does not yet support NT sec. */
  48.  
  49. /* private prototypes */
  50.  
  51. static BOOL Initialize(VOID);
  52. static BOOL Shutdown(VOID);
  53. static VOID GetRemotePrivilegesGet(CHAR *FileName, PDWORD dwRemotePrivileges);
  54. static VOID InitLocalPrivileges(VOID);
  55.  
  56.  
  57. BOOL bZipInitialized = FALSE;  /* module level stuff initialized? */
  58. HANDLE hZipInitMutex = NULL;   /* prevent multiple initialization */
  59.  
  60. BOOL g_bBackupPrivilege = FALSE;    /* for local get file security override */
  61. BOOL g_bZipSaclPrivilege = FALSE;      /* for local get sacl operations, only when
  62.                                        backup privilege not present */
  63.  
  64. /* our single cached volume capabilities structure that describes the last
  65.    volume root we encountered.  A single entry like this works well in the
  66.    zip/unzip scenario for a number of reasons:
  67.    1. typically one extraction path during unzip.
  68.    2. typically process one volume at a time during zip, and then move
  69.       on to the next.
  70.    3. no cleanup code required and no memory leaks.
  71.    4. simple code.
  72.  
  73.    This approach should be reworked to a linked list approach if we expect to
  74.    be called by many threads which are processing a variety of input/output
  75.    volumes, since lock contention and stale data may become a bottleneck. */
  76.  
  77. VOLUMECAPS g_VolumeCaps;
  78. CRITICAL_SECTION VolumeCapsLock;
  79.  
  80.  
  81. static BOOL Initialize(VOID)
  82. {
  83.     HANDLE hMutex;
  84.     HANDLE hOldMutex;
  85.  
  86.     if(bZipInitialized) return TRUE;
  87.  
  88.     hMutex = CreateMutex(NULL, TRUE, NULL);
  89.     if(hMutex == NULL) return FALSE;
  90.  
  91.     hOldMutex = (HANDLE)InterlockedExchange((LPLONG)&hZipInitMutex, (LONG)hMutex);
  92.  
  93.     if(hOldMutex != NULL) {
  94.         /* somebody setup the mutex already */
  95.         InterlockedExchange((LPLONG)&hZipInitMutex, (LONG)hOldMutex);
  96.  
  97.         CloseHandle(hMutex); /* close new, un-needed mutex */
  98.  
  99.         /* wait for initialization to complete and return status */
  100.         WaitForSingleObject(hOldMutex, INFINITE);
  101.         ReleaseMutex(hOldMutex);
  102.  
  103.         return bZipInitialized;
  104.     }
  105.  
  106.     /* initialize module level resources */
  107.  
  108.     InitializeCriticalSection( &VolumeCapsLock );
  109.     memset(&g_VolumeCaps, 0, sizeof(VOLUMECAPS));
  110.  
  111.     InitLocalPrivileges();
  112.  
  113.     bZipInitialized = TRUE;
  114.  
  115.     ReleaseMutex(hMutex); /* release correct mutex */
  116.  
  117.     return TRUE;
  118. }
  119.  
  120. static BOOL Shutdown(VOID)
  121. {
  122.     /* really need to free critical sections, disable enabled privilges, etc,
  123.        but doing so brings up possibility of race conditions if those resources
  124.        are about to be used.  The easiest way to handle this is let these
  125.        resources be freed when the process terminates... */
  126.  
  127.     return TRUE;
  128. }
  129.  
  130.  
  131. static VOID GetRemotePrivilegesGet(char *FileName, PDWORD dwRemotePrivileges)
  132. {
  133.     HANDLE hFile;
  134.  
  135.     *dwRemotePrivileges = 0;
  136.  
  137.     /* see if we have the SeBackupPrivilege */
  138.  
  139.     hFile = CreateFileA(
  140.         FileName,
  141.         ACCESS_SYSTEM_SECURITY | GENERIC_READ | READ_CONTROL,
  142.         FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
  143.         NULL,
  144.         OPEN_EXISTING,
  145.         FILE_FLAG_BACKUP_SEMANTICS,
  146.         NULL
  147.         );
  148.  
  149.     if(hFile != INVALID_HANDLE_VALUE) {
  150.         /* no remote way to determine SeBackupPrivilege -- just try a read
  151.            to simulate it */
  152.         SECURITY_INFORMATION si = DACL_SECURITY_INFORMATION | SACL_SECURITY_INFORMATION;
  153.         PSECURITY_DESCRIPTOR sd;
  154.         DWORD cbBuf = 0;
  155.  
  156.         GetKernelObjectSecurity(hFile, si, NULL, cbBuf, &cbBuf);
  157.  
  158.         if(ERROR_INSUFFICIENT_BUFFER == GetLastError()) {
  159.             if((sd = HeapAlloc(GetProcessHeap(), 0, cbBuf)) != NULL) {
  160.                 if(GetKernelObjectSecurity(hFile, si, sd, cbBuf, &cbBuf)) {
  161.                     *dwRemotePrivileges |= OVERRIDE_BACKUP;
  162.                 }
  163.                 HeapFree(GetProcessHeap(), 0, sd);
  164.             }
  165.         }
  166.  
  167.         CloseHandle(hFile);
  168.     } else {
  169.  
  170.         /* see if we have the SeSecurityPrivilege */
  171.         /* note we don't need this if we have SeBackupPrivilege */
  172.  
  173.         hFile = CreateFileA(
  174.             FileName,
  175.             ACCESS_SYSTEM_SECURITY,
  176.             FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, /* maximum sharing */
  177.             NULL,
  178.             OPEN_EXISTING,
  179.             0,
  180.             NULL
  181.             );
  182.  
  183.         if(hFile != INVALID_HANDLE_VALUE) {
  184.             CloseHandle(hFile);
  185.             *dwRemotePrivileges |= OVERRIDE_SACL;
  186.         }
  187.     }
  188. }
  189.  
  190.  
  191. BOOL ZipGetVolumeCaps(
  192.     char *rootpath,         /* filepath, or NULL */
  193.     char *name,             /* filename associated with rootpath */
  194.     PVOLUMECAPS VolumeCaps  /* result structure describing capabilities */
  195.     )
  196. {
  197.     char TempRootPath[MAX_PATH + 1];
  198.     DWORD cchTempRootPath = 0;
  199.     BOOL bSuccess = TRUE;   /* assume success until told otherwise */
  200.  
  201.     if(!bZipInitialized) if(!Initialize()) return FALSE;
  202.  
  203.     /* process the input path to produce a consistent path suitable for
  204.        compare operations and also suitable for certain picky Win32 API
  205.        that don't like forward slashes */
  206.  
  207.     if(rootpath != NULL && rootpath[0] != '\0') {
  208.         DWORD i;
  209.  
  210.         cchTempRootPath = lstrlen(rootpath);
  211.         if(cchTempRootPath > MAX_PATH) return FALSE;
  212.  
  213.         /* copy input, converting forward slashes to back slashes as we go */
  214.  
  215.         for(i = 0 ; i <= cchTempRootPath ; i++) {
  216.             if(rootpath[i] == '/') TempRootPath[i] = '\\';
  217.             else TempRootPath[i] = rootpath[i];
  218.         }
  219.  
  220.         /* check for UNC and Null terminate or append trailing \ as appropriate */
  221.  
  222.         /* possible valid UNCs we are passed follow:
  223.            \\machine\foo\bar (path is \\machine\foo\)
  224.            \\machine\foo     (path is \\machine\foo\)
  225.            \\machine\foo\
  226.            \\.\c$\           (FIXFIX: Win32API doesn't like this - GetComputerName())
  227.            LATERLATER: handling mounted DFS drives in the future will require
  228.                        slightly different logic which isn't available today.
  229.                        This is required because directories can point at
  230.                        different servers which have differing capabilities.
  231.          */
  232.  
  233.         if(TempRootPath[0] == '\\' && TempRootPath[1] == '\\') {
  234.             DWORD slash = 0;
  235.  
  236.             for(i = 2 ; i < cchTempRootPath ; i++) {
  237.                 if(TempRootPath[i] == '\\') {
  238.                     slash++;
  239.  
  240.                     if(slash == 2) {
  241.                         i++;
  242.                         TempRootPath[i] = '\0';
  243.                         cchTempRootPath = i;
  244.                         break;
  245.                     }
  246.                 }
  247.             }
  248.  
  249.             /* if there was only one slash found, just tack another onto the end */
  250.  
  251.             if(slash == 1 && TempRootPath[cchTempRootPath] != '\\') {
  252.                 TempRootPath[cchTempRootPath] = TempRootPath[0]; /* '\' */
  253.                 TempRootPath[cchTempRootPath+1] = '\0';
  254.                 cchTempRootPath++;
  255.             }
  256.  
  257.         } else {
  258.  
  259.             if(TempRootPath[1] == ':') {
  260.  
  261.                 /* drive letter specified, truncate to root */
  262.                 TempRootPath[2] = '\\';
  263.                 TempRootPath[3] = '\0';
  264.                 cchTempRootPath = 3;
  265.             } else {
  266.  
  267.                 /* must be file on current drive */
  268.                 TempRootPath[0] = '\0';
  269.                 cchTempRootPath = 0;
  270.             }
  271.  
  272.         }
  273.  
  274.     } /* if path != NULL */
  275.  
  276.     /* grab lock protecting cached entry */
  277.     EnterCriticalSection( &VolumeCapsLock );
  278.  
  279.     if(!g_VolumeCaps.bValid || lstrcmpi(g_VolumeCaps.RootPath, TempRootPath) != 0) {
  280.  
  281.         /* no match found, build up new entry */
  282.  
  283.         DWORD dwFileSystemFlags;
  284.         DWORD dwRemotePrivileges = 0;
  285.         BOOL bRemote = FALSE;
  286.  
  287.         /* release lock during expensive operations */
  288.         LeaveCriticalSection( &VolumeCapsLock );
  289.  
  290.         bSuccess = GetVolumeInformation(
  291.             (TempRootPath[0] == '\0') ? NULL : TempRootPath,
  292.             NULL, 0,
  293.             NULL, NULL,
  294.             &dwFileSystemFlags,
  295.             NULL, 0);
  296.  
  297.         /* only if target volume supports Acls, and we were told to use
  298.            privileges do we need to go out and test for the remote case */
  299.  
  300.         if(bSuccess && (dwFileSystemFlags & FS_PERSISTENT_ACLS) && VolumeCaps->bUsePrivileges) {
  301.             if(GetDriveType( (TempRootPath[0] == '\0') ? NULL : TempRootPath ) == DRIVE_REMOTE) {
  302.                 bRemote = TRUE;
  303.  
  304.                 /* make a determination about our remote capabilities */
  305.  
  306.                 GetRemotePrivilegesGet(name, &dwRemotePrivileges);
  307.             }
  308.         }
  309.  
  310.         /* always take the lock again, since we release it below */
  311.         EnterCriticalSection( &VolumeCapsLock );
  312.  
  313.         /* replace the existing data if successful */
  314.         if(bSuccess) {
  315.  
  316.             lstrcpynA(g_VolumeCaps.RootPath, TempRootPath, cchTempRootPath+1);
  317.             g_VolumeCaps.bProcessDefer = FALSE;
  318.             g_VolumeCaps.dwFileSystemFlags = dwFileSystemFlags;
  319.             g_VolumeCaps.bRemote = bRemote;
  320.             g_VolumeCaps.dwRemotePrivileges = dwRemotePrivileges;
  321.             g_VolumeCaps.bValid = TRUE;
  322.         }
  323.     }
  324.  
  325.     if(bSuccess) {
  326.         /* copy input elements */
  327.         g_VolumeCaps.bUsePrivileges = VolumeCaps->bUsePrivileges;
  328.         g_VolumeCaps.dwFileAttributes = VolumeCaps->dwFileAttributes;
  329.  
  330.         /* give caller results */
  331.         memcpy(VolumeCaps, &g_VolumeCaps, sizeof(VOLUMECAPS));
  332.     } else {
  333.         g_VolumeCaps.bValid = FALSE;
  334.     }
  335.  
  336.     LeaveCriticalSection( &VolumeCapsLock ); /* release lock */
  337.  
  338.     return bSuccess;
  339. }
  340.  
  341. BOOL SecurityGet(
  342.     char *resource,
  343.     PVOLUMECAPS VolumeCaps,
  344.     unsigned char *buffer,
  345.     DWORD *cbBuffer
  346.     )
  347. {
  348.     HANDLE hFile;
  349.     DWORD dwDesiredAccess;
  350.     DWORD dwFlags;
  351.     PSECURITY_DESCRIPTOR sd = (PSECURITY_DESCRIPTOR)buffer;
  352.     SECURITY_INFORMATION RequestedInfo;
  353.     BOOL bBackupPrivilege = FALSE;
  354.     BOOL bSaclPrivilege = FALSE;
  355.     BOOL bSuccess = FALSE;
  356.  
  357.     DWORD cchResourceLen;
  358.  
  359.     if(!bZipInitialized) if(!Initialize()) return FALSE;
  360.  
  361.     /* see if we are dealing with a directory */
  362.     /* rely on the fact resource has a trailing [back]slash, rather
  363.        than calling expensive GetFileAttributes() */
  364.  
  365.     cchResourceLen = lstrlenA(resource);
  366.  
  367.     if(resource[cchResourceLen-1] == '/' || resource[cchResourceLen-1] == '\\')
  368.         VolumeCaps->dwFileAttributes |= FILE_ATTRIBUTE_DIRECTORY;
  369.  
  370.     /* setup privilege usage based on if told we can use privileges, and if so,
  371.        what privileges we have */
  372.  
  373.     if(VolumeCaps->bUsePrivileges) {
  374.         if(VolumeCaps->bRemote) {
  375.             /* use remotely determined privileges */
  376.             if(VolumeCaps->dwRemotePrivileges & OVERRIDE_BACKUP)
  377.                 bBackupPrivilege = TRUE;
  378.  
  379.             if(VolumeCaps->dwRemotePrivileges & OVERRIDE_SACL)
  380.                 bSaclPrivilege = TRUE;
  381.         } else {
  382.             /* use local privileges */
  383.             bBackupPrivilege = g_bBackupPrivilege;
  384.             bSaclPrivilege = g_bZipSaclPrivilege;
  385.         }
  386.     }
  387.  
  388.     /* always try to read the basic security information:  Dacl, Owner, Group */
  389.  
  390.     dwDesiredAccess = READ_CONTROL;
  391.  
  392.     RequestedInfo = OWNER_SECURITY_INFORMATION |
  393.                     GROUP_SECURITY_INFORMATION |
  394.                     DACL_SECURITY_INFORMATION;
  395.  
  396.     /* if we have the SeBackupPrivilege or SeSystemSecurityPrivilege, read
  397.        the Sacl, too */
  398.  
  399.     if(bBackupPrivilege || bSaclPrivilege) {
  400.         dwDesiredAccess |= ACCESS_SYSTEM_SECURITY;
  401.         RequestedInfo |= SACL_SECURITY_INFORMATION;
  402.     }
  403.  
  404.     dwFlags = 0;
  405.  
  406.     /* if we have the backup privilege, specify that */
  407.     /* opening a directory requires FILE_FLAG_BACKUP_SEMANTICS */
  408.  
  409.     if(bBackupPrivilege || (VolumeCaps->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
  410.         dwFlags |= FILE_FLAG_BACKUP_SEMANTICS;
  411.  
  412.     hFile = CreateFileA(
  413.         resource,
  414.         dwDesiredAccess,
  415.         FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, /* maximum sharing */
  416.         NULL,
  417.         OPEN_EXISTING,
  418.         dwFlags,
  419.         NULL
  420.         );
  421.  
  422.     if(hFile == INVALID_HANDLE_VALUE) return FALSE;
  423.  
  424.     if(GetKernelObjectSecurity(hFile, RequestedInfo, sd, *cbBuffer, cbBuffer)) {
  425.         *cbBuffer = GetSecurityDescriptorLength( sd );
  426.         bSuccess = TRUE;
  427.     }
  428.  
  429.     CloseHandle(hFile);
  430.  
  431.     return bSuccess;
  432. }
  433.  
  434. static VOID InitLocalPrivileges(VOID)
  435. {
  436.     HANDLE hToken;
  437.     TOKEN_PRIVILEGES tp;
  438.  
  439.     /* try to enable some interesting privileges that give us the ability
  440.        to get some security information that we normally cannot.
  441.  
  442.        note that enabling privileges is only relevant on the local machine;
  443.        when accessing files that are on a remote machine, any privileges
  444.        that are present on the remote machine get enabled by default. */
  445.  
  446.     if(!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &hToken))
  447.         return;
  448.  
  449.     tp.PrivilegeCount = 1;
  450.     tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
  451.  
  452.     /* try to enable SeBackupPrivilege.
  453.        if this succeeds, we can read all aspects of the security descriptor */
  454.  
  455.     if(LookupPrivilegeValue(NULL, SE_BACKUP_NAME, &tp.Privileges[0].Luid)) {
  456.         if(AdjustTokenPrivileges(hToken, FALSE, &tp, 0, NULL, NULL) &&
  457.            GetLastError() == ERROR_SUCCESS) g_bBackupPrivilege = TRUE;
  458.     }
  459.  
  460.     /* try to enable SeSystemSecurityPrivilege if SeBackupPrivilege not present.
  461.        if this succeeds, we can read the Sacl */
  462.  
  463.     if(!g_bBackupPrivilege &&
  464.         LookupPrivilegeValue(NULL, SE_SECURITY_NAME, &tp.Privileges[0].Luid)) {
  465.  
  466.         if(AdjustTokenPrivileges(hToken, FALSE, &tp, 0, NULL, NULL) &&
  467.            GetLastError() == ERROR_SUCCESS) g_bZipSaclPrivilege = TRUE;
  468.     }
  469.  
  470.     CloseHandle(hToken);
  471. }
  472. #endif /* !NO_NTSD_WITH_RSXNT */
  473. #endif /* NTSD_EAS */
  474.