⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 contman.c

📁 windows的加密api源码
💻 C
📖 第 1 页 / 共 5 页
字号:
    BOOL        fAlloced = FALSE;

    BOOL        fRet = FALSE;

    ptgUser = (PTOKEN_USER)FastBuffer; // try fast buffer first
    cbUser = FAST_BUF_SIZE;
    if (!GetUserSid(&ptgUser, &cbUser, &fAlloced))
        goto Ret;

    //
    // obtain the textual representaion of the Sid
    //

    if (!GetTextualSidA(ptgUser->User.Sid, // user binary Sid
                        lpBuffer,          // buffer for TextualSid
                        nSize))
        goto Ret;

    fRet = TRUE;
Ret:
    if (fAlloced)
    {
        if(ptgUser)
            ContInfoFree(ptgUser);
    }

    return fRet;
}

BOOL
GetUserTextualSidW(
    LPWSTR lpBuffer,
    LPDWORD nSize
    )
{
    BYTE        FastBuffer[FAST_BUF_SIZE];
    PTOKEN_USER ptgUser;
    DWORD       cbUser;
    BOOL        fAlloced = FALSE;

    BOOL        fRet = FALSE;

    ptgUser = (PTOKEN_USER)FastBuffer; // try fast buffer first
    cbUser = FAST_BUF_SIZE;
    if (!GetUserSid(&ptgUser, &cbUser, &fAlloced))
        goto Ret;

    //
    // obtain the textual representaion of the Sid
    //

    if (!GetTextualSidW(ptgUser->User.Sid, // user binary Sid
                        lpBuffer,          // buffer for TextualSid
                        nSize))
        goto Ret;

    fRet = TRUE;
Ret:
    if (fAlloced)
    {
        if(ptgUser)
            ContInfoFree(ptgUser);
    }

    return fRet;
}

DWORD GetUserDirectory(
                       IN BOOL fMachineKeyset,
                       OUT LPWSTR pwszUser,
                       OUT DWORD *pcbUser
                       )
{
    DWORD   dwErr = 0;

    if (fMachineKeyset)
    {
        wcscpy(pwszUser, MACHINE_KEYS_DIR);
        *pcbUser = wcslen(pwszUser) + 1;
    }
    else
    {
        if (FIsWinNT())
        {
            if (!GetUserTextualSidW(pwszUser, pcbUser))
            {
                SetLastError((DWORD) NTE_BAD_KEYSET);
                goto Ret;
            }
        }
        else
        {
            dwErr = (DWORD)NTE_FAIL;
            goto Ret;
        }
    }
Ret:
    return dwErr;
}

#define WSZRSAPRODUCTSTRING  L"\\Microsoft\\Crypto\\RSA\\"
#define WSZDSSPRODUCTSTRING  L"\\Microsoft\\Crypto\\DSS\\"
#define PRODUCTSTRINGLEN    sizeof(WSZRSAPRODUCTSTRING) - sizeof(WCHAR)

typedef HRESULT (WINAPI *SHGETFOLDERPATHW)(
    HWND hwnd,
    int csidl,
    HANDLE hToken,
    DWORD dwFlags,
    LPWSTR pwszPath
    );

static SHGETFOLDERPATHW _SHGetFolderPathW;

DWORD
GetUserStorageArea(
    IN      DWORD dwProvType,
    IN      BOOL fMachineKeyset,
    IN      BOOL fOldWin2KMachineKeyPath,
    OUT     BOOL *pfIsLocalSystem,      // used if fMachineKeyset is FALSE, in this
                                        // case TRUE is returned if running as Local System
    IN  OUT LPWSTR *ppwszUserStorageArea
    )
{
    WCHAR wszUserStorageRoot[MAX_PATH+1];
    DWORD cbUserStorageRoot;

    WCHAR *wszProductString;

    WCHAR wszUser[MAX_PATH];
    DWORD cbUser;
    DWORD cchUser = MAX_PATH;

    BOOL fLocalMachine = FALSE;
    HANDLE hToken;
    DWORD dwTempProfileFlags = 0;

    DWORD dwLastError = 0;

    *pfIsLocalSystem = FALSE;

    if ((PROV_RSA_SIG == dwProvType) || (PROV_RSA_FULL == dwProvType) ||
        (PROV_RSA_SCHANNEL == dwProvType))
    {
        wszProductString = WSZRSAPRODUCTSTRING;
    }
    else if ((PROV_DSS == dwProvType) || (PROV_DSS_DH == dwProvType) ||
             (PROV_DH_SCHANNEL == dwProvType))
    {
        wszProductString = WSZDSSPRODUCTSTRING;
    }

    //
    // check if running in the LocalSystem context
    //
    if (!fMachineKeyset)
    {
        if (!IsThreadLocalSystem(pfIsLocalSystem))
        {
            dwLastError = (DWORD)NTE_FAIL;
            goto Ret;
        }
    }

    //
    // determine path to per-user storage area, based on whether this
    // is a local machine disposition call or a per-user disposition call.
    //

    if( fMachineKeyset || *pfIsLocalSystem )
    {

        if (!fOldWin2KMachineKeyPath)
        {
            if(_SHGetFolderPathW == NULL) {
                HMODULE hShell32 = LoadLibraryW( L"shell32.dll" );
                if(hShell32 == NULL)
                {
                    dwLastError = GetLastError();
                    goto Ret;
                }

                _SHGetFolderPathW = (SHGETFOLDERPATHW)GetProcAddress(hShell32, "SHGetFolderPathW");

                if(_SHGetFolderPathW == NULL)
                {
                    dwLastError = GetLastError();
                    goto Ret;
                }
            }

            if(!OpenThreadToken( GetCurrentThread(), TOKEN_QUERY | TOKEN_IMPERSONATE,
                                TRUE, &hToken ))
            {
                if (ERROR_NO_TOKEN != (dwLastError = GetLastError()))
                    goto Ret;

                // For Jeff, fall back and get the process token
                if(!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY | TOKEN_IMPERSONATE,
                                     &hToken))
                {
                    dwLastError = GetLastError();
                    goto Ret;
                }
            }

            dwLastError = (DWORD)_SHGetFolderPathW( NULL,
                                                    CSIDL_COMMON_APPDATA | CSIDL_FLAG_CREATE,
                                                    hToken,
                                                    0,
                                                    wszUserStorageRoot );

            CloseHandle( hToken );

            if( dwLastError != ERROR_SUCCESS )
                goto Ret;

            cbUserStorageRoot = wcslen( wszUserStorageRoot ) * sizeof(WCHAR);
        }
        else
        {
            cbUserStorageRoot = GetSystemDirectoryW(
                                    wszUserStorageRoot,
                                    MAX_PATH
                                    );

            cbUserStorageRoot *= sizeof(WCHAR);
        }

    }
    else
    {
        // check if the profile is temporary
        if (!GetProfileType(&dwTempProfileFlags))
        {
            dwLastError = GetLastError();
            goto Ret;
        }
        if ((dwTempProfileFlags & PT_TEMPORARY) ||
            (dwTempProfileFlags & PT_MANDATORY))
        {
            dwLastError = (DWORD)NTE_TEMPORARY_PROFILE;
            goto Ret;
        }

        if(_SHGetFolderPathW == NULL) {
            HMODULE hShell32 = LoadLibraryW( L"shell32.dll" );
            if(hShell32 == NULL)
            {
                dwLastError = GetLastError();
                goto Ret;
            }

            _SHGetFolderPathW = (SHGETFOLDERPATHW)GetProcAddress(hShell32, "SHGetFolderPathW");

            if(_SHGetFolderPathW == NULL)
            {
                dwLastError = GetLastError();
                goto Ret;
            }
        }

        if(!OpenThreadToken( GetCurrentThread(), TOKEN_QUERY | TOKEN_IMPERSONATE,
                            TRUE, &hToken ))
        {
            if (ERROR_NO_TOKEN != (dwLastError = GetLastError()))
                goto Ret;

            // For Jeff, fall back and get the process token
            if(!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY | TOKEN_IMPERSONATE,
                                 &hToken))
            {
                dwLastError = GetLastError();
                goto Ret;
            }
        }

        dwLastError = (DWORD)_SHGetFolderPathW( NULL,
                                                CSIDL_APPDATA | CSIDL_FLAG_CREATE,
                                                hToken,
                                                0,
                                                wszUserStorageRoot );

        CloseHandle( hToken );

        if( dwLastError != ERROR_SUCCESS )
            goto Ret;

        cbUserStorageRoot = wcslen( wszUserStorageRoot ) * sizeof(WCHAR);
    }

    if(cbUserStorageRoot == 0)
    {
        dwLastError = (DWORD)NTE_FAIL;
        goto Ret;
    }


    //
    // get the user name associated with the call.
    // Note: this is the textual Sid on NT, and will fail on Win95.
    //

    dwLastError = GetUserDirectory( fMachineKeyset, wszUser, &cchUser );
    if(dwLastError != 0)
        goto Ret;

    cbUser = (cchUser-1) * sizeof(WCHAR);


    *ppwszUserStorageArea = (LPWSTR)ContInfoAlloc(
                                    cbUserStorageRoot +
                                    PRODUCTSTRINGLEN +
                                    cbUser + 2 * sizeof(WCHAR)   // trailing slash and NULL
                                    );
    if (*ppwszUserStorageArea) {

        PBYTE pbCurrent = (PBYTE)*ppwszUserStorageArea;

        CopyMemory(pbCurrent, wszUserStorageRoot, cbUserStorageRoot);
        pbCurrent += cbUserStorageRoot;

        CopyMemory(pbCurrent, wszProductString, PRODUCTSTRINGLEN);
        pbCurrent += PRODUCTSTRINGLEN;

        CopyMemory(pbCurrent, wszUser, cbUser);
        pbCurrent += cbUser; // note: cbUser does not include terminal NULL

        ((LPSTR)pbCurrent)[0] = '\\';
        ((LPSTR)pbCurrent)[1] = '\0';


        dwLastError = CreateNestedDirectories(
                            *ppwszUserStorageArea,
                            (LPWSTR)((LPBYTE)*ppwszUserStorageArea +
                                cbUserStorageRoot + sizeof(WCHAR)),
                            fMachineKeyset);
    }
    else
        dwLastError = NTE_NO_MEMORY;
Ret:
    return dwLastError;
}

DWORD GetFilePath(
    IN      LPCWSTR  pwszUserStorageArea,
    IN      LPCWSTR  pwszFileName,
    IN OUT  LPWSTR   *ppwszFilePath
    )
{
    DWORD cbUserStorageArea;
    DWORD cbFileName;
    DWORD dwLastError = ERROR_SUCCESS;

    cbUserStorageArea = wcslen( pwszUserStorageArea ) * sizeof(WCHAR);

    cbFileName = wcslen( pwszFileName ) * sizeof(WCHAR);

    *ppwszFilePath = (LPWSTR)ContInfoAlloc( cbUserStorageArea + cbFileName + sizeof(WCHAR) );

    if( *ppwszFilePath == NULL )
    {
        dwLastError = ERROR_NOT_ENOUGH_MEMORY;
        goto Ret;
    }

    CopyMemory(*ppwszFilePath, pwszUserStorageArea, cbUserStorageArea);
    CopyMemory((LPBYTE)*ppwszFilePath+cbUserStorageArea, pwszFileName, cbFileName + sizeof(WCHAR));
Ret:
    return dwLastError;
}

static DWORD rgdwCreateFileRetryMilliseconds[] =
    { 1, 10, 100, 500, 1000, 5000 };

#define MAX_CREATE_FILE_RETRY_COUNT     \
            (sizeof(rgdwCreateFileRetryMilliseconds) / \
                sizeof(rgdwCreateFileRetryMilliseconds[0]))

HANDLE MyCreateFile(
  IN BOOL fMachineKeyset,         // indicates if this is a machine keyset
  IN LPCWSTR wszFilePath,          // pointer to name of the file
  IN DWORD dwDesiredAccess,       // access (read-write) mode
  IN DWORD dwShareMode,           // share mode
  IN DWORD dwCreationDisposition,  // how to create
  IN DWORD dwAttribs  // file attributes
)
{
    HANDLE          hToken = 0;
    BYTE            rgbPriv[sizeof(PRIVILEGE_SET) + sizeof(LUID_AND_ATTRIBUTES)];
    PRIVILEGE_SET   *pPriv = (PRIVILEGE_SET*)rgbPriv;
    BOOL            fPrivSet = FALSE;
    BOOL            fSetLastError = FALSE;
    HANDLE          hFile = INVALID_HANDLE_VALUE;
    DWORD           dwErr = 0;

    hFile = CreateFileW(
                wszFilePath,
                dwDesiredAccess,
                dwShareMode,
                NULL,
                dwCreationDisposition,
                dwAttribs,
                NULL
                );

    if (INVALID_HANDLE_VALUE == hFile)
    {
        // check if machine keyset
        if (fMachineKeyset)
        {
            dwErr = GetLastError();
            fSetLastError = TRUE;

            // open a token handle
            if (FALSE == OpenThreadToken(GetCurrentThread(),
                                         MAXIMUM_ALLOWED,
                                         TRUE,
                                         &hToken))
            {
                if (FALSE == OpenProcessToken(GetCurrentProcess(),
                                              TOKEN_QUERY,
                                              &hToken))
                {
                    goto Ret;
                }
            }

            memset(rgbPriv, 0, sizeof(rgbPriv));
            pPriv->PrivilegeCount = 1;
            // reading file
            if (dwDesiredAccess & GENERIC_READ)
            {
                if(!LookupPrivilegeValue(NULL, SE_BACKUP_NAME,
                                         &(pPriv->Privilege[0].Luid)))
                {
                    goto Ret;
                }
            }
            // writing
            else
            {
                if(!LookupPrivilegeValue(NULL, SE_RESTORE_NAME,
                                         &(pPriv->Privilege[0].Luid)))
                {
                    goto Ret;
                }
            }

            // check if the BACKUP or RESTORE privileges are set
            pPriv->Privilege[0].Attributes = SE_PRIVILEGE_ENABLED;
            if (!PrivilegeCheck(hToken, pPriv, &fPrivSet))
            {
                goto Ret;
            }

            if (fPrivSet)
            {

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -