mirror of
https://github.com/Microsoft/sql-server-samples.git
synced 2025-12-08 14:58:54 +00:00
Sample application using AE with VBS enclaves
This commit is contained in:
+63
@@ -0,0 +1,63 @@
|
||||
###############################################################################
|
||||
# Set default behavior to automatically normalize line endings.
|
||||
###############################################################################
|
||||
* text=auto
|
||||
|
||||
###############################################################################
|
||||
# Set default behavior for command prompt diff.
|
||||
#
|
||||
# This is need for earlier builds of msysgit that does not have it on by
|
||||
# default for csharp files.
|
||||
# Note: This is only used by command line
|
||||
###############################################################################
|
||||
#*.cs diff=csharp
|
||||
|
||||
###############################################################################
|
||||
# Set the merge driver for project and solution files
|
||||
#
|
||||
# Merging from the command prompt will add diff markers to the files if there
|
||||
# are conflicts (Merging from VS is not affected by the settings below, in VS
|
||||
# the diff markers are never inserted). Diff markers may cause the following
|
||||
# file extensions to fail to load in VS. An alternative would be to treat
|
||||
# these files as binary and thus will always conflict and require user
|
||||
# intervention with every merge. To do so, just uncomment the entries below
|
||||
###############################################################################
|
||||
#*.sln merge=binary
|
||||
#*.csproj merge=binary
|
||||
#*.vbproj merge=binary
|
||||
#*.vcxproj merge=binary
|
||||
#*.vcproj merge=binary
|
||||
#*.dbproj merge=binary
|
||||
#*.fsproj merge=binary
|
||||
#*.lsproj merge=binary
|
||||
#*.wixproj merge=binary
|
||||
#*.modelproj merge=binary
|
||||
#*.sqlproj merge=binary
|
||||
#*.wwaproj merge=binary
|
||||
|
||||
###############################################################################
|
||||
# behavior for image files
|
||||
#
|
||||
# image files are treated as binary by default.
|
||||
###############################################################################
|
||||
#*.jpg binary
|
||||
#*.png binary
|
||||
#*.gif binary
|
||||
|
||||
###############################################################################
|
||||
# diff behavior for common document formats
|
||||
#
|
||||
# Convert binary document formats to text before diffing them. This feature
|
||||
# is only available from the command line. Turn it on by uncommenting the
|
||||
# entries below.
|
||||
###############################################################################
|
||||
#*.doc diff=astextplain
|
||||
#*.DOC diff=astextplain
|
||||
#*.docx diff=astextplain
|
||||
#*.DOCX diff=astextplain
|
||||
#*.dot diff=astextplain
|
||||
#*.DOT diff=astextplain
|
||||
#*.pdf diff=astextplain
|
||||
#*.PDF diff=astextplain
|
||||
#*.rtf diff=astextplain
|
||||
#*.RTF diff=astextplain
|
||||
+363
@@ -0,0 +1,363 @@
|
||||
## Ignore Visual Studio temporary files, build results, and
|
||||
## files generated by popular Visual Studio add-ons.
|
||||
##
|
||||
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
|
||||
|
||||
# User-specific files
|
||||
*.rsuser
|
||||
*.suo
|
||||
*.user
|
||||
*.userosscache
|
||||
*.sln.docstates
|
||||
|
||||
# User-specific files (MonoDevelop/Xamarin Studio)
|
||||
*.userprefs
|
||||
|
||||
# Mono auto generated files
|
||||
mono_crash.*
|
||||
|
||||
# Build results
|
||||
[Dd]ebug/
|
||||
[Dd]ebugPublic/
|
||||
[Rr]elease/
|
||||
[Rr]eleases/
|
||||
x64/
|
||||
x86/
|
||||
[Ww][Ii][Nn]32/
|
||||
[Aa][Rr][Mm]/
|
||||
[Aa][Rr][Mm]64/
|
||||
bld/
|
||||
[Bb]in/
|
||||
[Oo]bj/
|
||||
[Oo]ut/
|
||||
[Ll]og/
|
||||
[Ll]ogs/
|
||||
|
||||
# Visual Studio 2015/2017 cache/options directory
|
||||
.vs/
|
||||
# Uncomment if you have tasks that create the project's static files in wwwroot
|
||||
#wwwroot/
|
||||
|
||||
# Visual Studio 2017 auto generated files
|
||||
Generated\ Files/
|
||||
|
||||
# MSTest test Results
|
||||
[Tt]est[Rr]esult*/
|
||||
[Bb]uild[Ll]og.*
|
||||
|
||||
# NUnit
|
||||
*.VisualState.xml
|
||||
TestResult.xml
|
||||
nunit-*.xml
|
||||
|
||||
# Build Results of an ATL Project
|
||||
[Dd]ebugPS/
|
||||
[Rr]eleasePS/
|
||||
dlldata.c
|
||||
|
||||
# Benchmark Results
|
||||
BenchmarkDotNet.Artifacts/
|
||||
|
||||
# .NET Core
|
||||
project.lock.json
|
||||
project.fragment.lock.json
|
||||
artifacts/
|
||||
|
||||
# ASP.NET Scaffolding
|
||||
ScaffoldingReadMe.txt
|
||||
|
||||
# StyleCop
|
||||
StyleCopReport.xml
|
||||
|
||||
# Files built by Visual Studio
|
||||
*_i.c
|
||||
*_p.c
|
||||
*_h.h
|
||||
*.ilk
|
||||
*.meta
|
||||
*.obj
|
||||
*.iobj
|
||||
*.pch
|
||||
*.pdb
|
||||
*.ipdb
|
||||
*.pgc
|
||||
*.pgd
|
||||
*.rsp
|
||||
*.sbr
|
||||
*.tlb
|
||||
*.tli
|
||||
*.tlh
|
||||
*.tmp
|
||||
*.tmp_proj
|
||||
*_wpftmp.csproj
|
||||
*.log
|
||||
*.vspscc
|
||||
*.vssscc
|
||||
.builds
|
||||
*.pidb
|
||||
*.svclog
|
||||
*.scc
|
||||
|
||||
# Chutzpah Test files
|
||||
_Chutzpah*
|
||||
|
||||
# Visual C++ cache files
|
||||
ipch/
|
||||
*.aps
|
||||
*.ncb
|
||||
*.opendb
|
||||
*.opensdf
|
||||
*.sdf
|
||||
*.cachefile
|
||||
*.VC.db
|
||||
*.VC.VC.opendb
|
||||
|
||||
# Visual Studio profiler
|
||||
*.psess
|
||||
*.vsp
|
||||
*.vspx
|
||||
*.sap
|
||||
|
||||
# Visual Studio Trace Files
|
||||
*.e2e
|
||||
|
||||
# TFS 2012 Local Workspace
|
||||
$tf/
|
||||
|
||||
# Guidance Automation Toolkit
|
||||
*.gpState
|
||||
|
||||
# ReSharper is a .NET coding add-in
|
||||
_ReSharper*/
|
||||
*.[Rr]e[Ss]harper
|
||||
*.DotSettings.user
|
||||
|
||||
# TeamCity is a build add-in
|
||||
_TeamCity*
|
||||
|
||||
# DotCover is a Code Coverage Tool
|
||||
*.dotCover
|
||||
|
||||
# AxoCover is a Code Coverage Tool
|
||||
.axoCover/*
|
||||
!.axoCover/settings.json
|
||||
|
||||
# Coverlet is a free, cross platform Code Coverage Tool
|
||||
coverage*.json
|
||||
coverage*.xml
|
||||
coverage*.info
|
||||
|
||||
# Visual Studio code coverage results
|
||||
*.coverage
|
||||
*.coveragexml
|
||||
|
||||
# NCrunch
|
||||
_NCrunch_*
|
||||
.*crunch*.local.xml
|
||||
nCrunchTemp_*
|
||||
|
||||
# MightyMoose
|
||||
*.mm.*
|
||||
AutoTest.Net/
|
||||
|
||||
# Web workbench (sass)
|
||||
.sass-cache/
|
||||
|
||||
# Installshield output folder
|
||||
[Ee]xpress/
|
||||
|
||||
# DocProject is a documentation generator add-in
|
||||
DocProject/buildhelp/
|
||||
DocProject/Help/*.HxT
|
||||
DocProject/Help/*.HxC
|
||||
DocProject/Help/*.hhc
|
||||
DocProject/Help/*.hhk
|
||||
DocProject/Help/*.hhp
|
||||
DocProject/Help/Html2
|
||||
DocProject/Help/html
|
||||
|
||||
# Click-Once directory
|
||||
publish/
|
||||
|
||||
# Publish Web Output
|
||||
*.[Pp]ublish.xml
|
||||
*.azurePubxml
|
||||
# Note: Comment the next line if you want to checkin your web deploy settings,
|
||||
# but database connection strings (with potential passwords) will be unencrypted
|
||||
*.pubxml
|
||||
*.publishproj
|
||||
|
||||
# Microsoft Azure Web App publish settings. Comment the next line if you want to
|
||||
# checkin your Azure Web App publish settings, but sensitive information contained
|
||||
# in these scripts will be unencrypted
|
||||
PublishScripts/
|
||||
|
||||
# NuGet Packages
|
||||
*.nupkg
|
||||
# NuGet Symbol Packages
|
||||
*.snupkg
|
||||
# The packages folder can be ignored because of Package Restore
|
||||
**/[Pp]ackages/*
|
||||
# except build/, which is used as an MSBuild target.
|
||||
!**/[Pp]ackages/build/
|
||||
# Uncomment if necessary however generally it will be regenerated when needed
|
||||
#!**/[Pp]ackages/repositories.config
|
||||
# NuGet v3's project.json files produces more ignorable files
|
||||
*.nuget.props
|
||||
*.nuget.targets
|
||||
|
||||
# Microsoft Azure Build Output
|
||||
csx/
|
||||
*.build.csdef
|
||||
|
||||
# Microsoft Azure Emulator
|
||||
ecf/
|
||||
rcf/
|
||||
|
||||
# Windows Store app package directories and files
|
||||
AppPackages/
|
||||
BundleArtifacts/
|
||||
Package.StoreAssociation.xml
|
||||
_pkginfo.txt
|
||||
*.appx
|
||||
*.appxbundle
|
||||
*.appxupload
|
||||
|
||||
# Visual Studio cache files
|
||||
# files ending in .cache can be ignored
|
||||
*.[Cc]ache
|
||||
# but keep track of directories ending in .cache
|
||||
!?*.[Cc]ache/
|
||||
|
||||
# Others
|
||||
ClientBin/
|
||||
~$*
|
||||
*~
|
||||
*.dbmdl
|
||||
*.dbproj.schemaview
|
||||
*.jfm
|
||||
*.pfx
|
||||
*.publishsettings
|
||||
orleans.codegen.cs
|
||||
|
||||
# Including strong name files can present a security risk
|
||||
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
|
||||
#*.snk
|
||||
|
||||
# Since there are multiple workflows, uncomment next line to ignore bower_components
|
||||
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
|
||||
#bower_components/
|
||||
|
||||
# RIA/Silverlight projects
|
||||
Generated_Code/
|
||||
|
||||
# Backup & report files from converting an old project file
|
||||
# to a newer Visual Studio version. Backup files are not needed,
|
||||
# because we have git ;-)
|
||||
_UpgradeReport_Files/
|
||||
Backup*/
|
||||
UpgradeLog*.XML
|
||||
UpgradeLog*.htm
|
||||
ServiceFabricBackup/
|
||||
*.rptproj.bak
|
||||
|
||||
# SQL Server files
|
||||
*.mdf
|
||||
*.ldf
|
||||
*.ndf
|
||||
|
||||
# Business Intelligence projects
|
||||
*.rdl.data
|
||||
*.bim.layout
|
||||
*.bim_*.settings
|
||||
*.rptproj.rsuser
|
||||
*- [Bb]ackup.rdl
|
||||
*- [Bb]ackup ([0-9]).rdl
|
||||
*- [Bb]ackup ([0-9][0-9]).rdl
|
||||
|
||||
# Microsoft Fakes
|
||||
FakesAssemblies/
|
||||
|
||||
# GhostDoc plugin setting file
|
||||
*.GhostDoc.xml
|
||||
|
||||
# Node.js Tools for Visual Studio
|
||||
.ntvs_analysis.dat
|
||||
node_modules/
|
||||
|
||||
# Visual Studio 6 build log
|
||||
*.plg
|
||||
|
||||
# Visual Studio 6 workspace options file
|
||||
*.opt
|
||||
|
||||
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
|
||||
*.vbw
|
||||
|
||||
# Visual Studio LightSwitch build output
|
||||
**/*.HTMLClient/GeneratedArtifacts
|
||||
**/*.DesktopClient/GeneratedArtifacts
|
||||
**/*.DesktopClient/ModelManifest.xml
|
||||
**/*.Server/GeneratedArtifacts
|
||||
**/*.Server/ModelManifest.xml
|
||||
_Pvt_Extensions
|
||||
|
||||
# Paket dependency manager
|
||||
.paket/paket.exe
|
||||
paket-files/
|
||||
|
||||
# FAKE - F# Make
|
||||
.fake/
|
||||
|
||||
# CodeRush personal settings
|
||||
.cr/personal
|
||||
|
||||
# Python Tools for Visual Studio (PTVS)
|
||||
__pycache__/
|
||||
*.pyc
|
||||
|
||||
# Cake - Uncomment if you are using it
|
||||
# tools/**
|
||||
# !tools/packages.config
|
||||
|
||||
# Tabs Studio
|
||||
*.tss
|
||||
|
||||
# Telerik's JustMock configuration file
|
||||
*.jmconfig
|
||||
|
||||
# BizTalk build output
|
||||
*.btp.cs
|
||||
*.btm.cs
|
||||
*.odx.cs
|
||||
*.xsd.cs
|
||||
|
||||
# OpenCover UI analysis results
|
||||
OpenCover/
|
||||
|
||||
# Azure Stream Analytics local run output
|
||||
ASALocalRun/
|
||||
|
||||
# MSBuild Binary and Structured Log
|
||||
*.binlog
|
||||
|
||||
# NVidia Nsight GPU debugger configuration file
|
||||
*.nvuser
|
||||
|
||||
# MFractors (Xamarin productivity tool) working folder
|
||||
.mfractor/
|
||||
|
||||
# Local History for Visual Studio
|
||||
.localhistory/
|
||||
|
||||
# BeatPulse healthcheck temp database
|
||||
healthchecksdb
|
||||
|
||||
# Backup folder for Package Reference Convert tool in Visual Studio 2017
|
||||
MigrationBackup/
|
||||
|
||||
# Ionide (cross platform F# VS Code tools) working folder
|
||||
.ionide/
|
||||
|
||||
# Fody - auto-generated XML schema
|
||||
FodyWeavers.xsd
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio Version 17
|
||||
VisualStudioVersion = 17.8.34408.163
|
||||
MinimumVisualStudioVersion = 10.0.40219.1
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AlwaysEncryptedConsole", "AlwaysEncryptedConsole\AlwaysEncryptedConsole.csproj", "{66F6F7D3-3B6E-4460-921F-8E6127C73F33}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
Release|Any CPU = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{66F6F7D3-3B6E-4460-921F-8E6127C73F33}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{66F6F7D3-3B6E-4460-921F-8E6127C73F33}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{66F6F7D3-3B6E-4460-921F-8E6127C73F33}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{66F6F7D3-3B6E-4460-921F-8E6127C73F33}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||
SolutionGuid = {B18CFE54-1A5E-4299-96CE-11F0DCB01A9D}
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net8.0-windows10.0.22621.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<EnforceCodeStyleInBuild>False</EnforceCodeStyleInBuild>
|
||||
<AnalysisLevel>none</AnalysisLevel>
|
||||
<RunAnalyzersDuringBuild>False</RunAnalyzersDuringBuild>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Azure.Identity" Version="1.10.4" />
|
||||
<PackageReference Include="Azure.Security.KeyVault.Secrets" Version="4.5.0" />
|
||||
<PackageReference Include="Microsoft.Data.SqlClient" Version="5.1.4" />
|
||||
<PackageReference Include="Microsoft.Data.SqlClient.AlwaysEncrypted.AzureKeyVaultProvider" Version="3.0.0" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio Version 17
|
||||
VisualStudioVersion = 17.5.002.0
|
||||
MinimumVisualStudioVersion = 10.0.40219.1
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AlwaysEncryptedConsole", "AlwaysEncryptedConsole.csproj", "{D51BF679-04F7-40F7-8652-2921AA73593F}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
Release|Any CPU = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{D51BF679-04F7-40F7-8652-2921AA73593F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{D51BF679-04F7-40F7-8652-2921AA73593F}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{D51BF679-04F7-40F7-8652-2921AA73593F}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{D51BF679-04F7-40F7-8652-2921AA73593F}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||
SolutionGuid = {30E31893-7EC2-4FC1-91E4-C3781F5FF081}
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
//*********************************************************
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
// This code is licensed under the MIT License (MIT).
|
||||
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
|
||||
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
|
||||
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
|
||||
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
|
||||
//
|
||||
// Author: Michael Howard, Azure Data Security
|
||||
//*********************************************************
|
||||
|
||||
using Microsoft.Data.SqlClient;
|
||||
|
||||
partial class Program
|
||||
{
|
||||
// Displays rows and cols from a SqlDataReader query result
|
||||
public static void DumpData(SqlDataReader? data)
|
||||
{
|
||||
if (data is null)
|
||||
{
|
||||
Console.WriteLine("No data");
|
||||
return;
|
||||
}
|
||||
|
||||
// get column headers
|
||||
Console.WriteLine("Fetching Data");
|
||||
for (int i = 0; i < data.FieldCount; i++)
|
||||
Console.Write(data.GetName(i) + ", ");
|
||||
|
||||
Console.WriteLine();
|
||||
|
||||
// get data
|
||||
while (data.Read())
|
||||
{
|
||||
for (int i = 0; i < data.FieldCount; i++)
|
||||
{
|
||||
var value = data.GetValue(i);
|
||||
|
||||
if (value is not null)
|
||||
{
|
||||
var type = data.GetFieldType(i);
|
||||
|
||||
// if the data is a byte array (ie; ciphertext)
|
||||
// dump the first 16 bytes of hex string
|
||||
if (type == typeof(byte[]))
|
||||
// Possible null reference argument. There *IS* a check two lines up!
|
||||
#pragma warning disable CS8604
|
||||
value = ByteArrayToHexString(value as byte[], 16);
|
||||
#pragma warning restore CS8604
|
||||
}
|
||||
else
|
||||
{
|
||||
value = "?";
|
||||
}
|
||||
|
||||
Console.Write(value + ", ");
|
||||
}
|
||||
Console.WriteLine();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+176
@@ -0,0 +1,176 @@
|
||||
//*********************************************************
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
// This code is licensed under the MIT License (MIT).
|
||||
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
|
||||
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
|
||||
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
|
||||
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
|
||||
//
|
||||
// Author: Michael Howard, Azure Data Security
|
||||
//*********************************************************
|
||||
|
||||
//*********************************************************
|
||||
// Demo Steps
|
||||
// Step 1
|
||||
// Run, as-is, AE is set to false,
|
||||
// and the code will return ciphertext
|
||||
//
|
||||
// Step 2
|
||||
// Set useAlwaysEncrypted to true (line 47)
|
||||
// Re-run code, will fail because of no params
|
||||
//
|
||||
// Step 3
|
||||
// Set testWithParams to true (line 50)
|
||||
// Re-run code, but will fail because of no AKV
|
||||
//
|
||||
// Step 4
|
||||
// Set registerAkv4Ae to true (line 53)
|
||||
// Re-run. At this point everything should work.
|
||||
// Two queries, the first is slow because intial authn/authz/column metadata
|
||||
// Second is much faster
|
||||
|
||||
using Azure.Core;
|
||||
using Microsoft.Data.SqlClient;
|
||||
using System.Data;
|
||||
using System.Diagnostics;
|
||||
|
||||
partial class Program
|
||||
{
|
||||
static void Main()
|
||||
{
|
||||
// START all these flags should be false
|
||||
|
||||
// Demo step 1 will not use AE,
|
||||
// and you will only see the SSN and Salary columns as ciphertext
|
||||
|
||||
// Demo step 2 set this to true
|
||||
bool useAlwaysEncrypted = true;
|
||||
|
||||
// Demo step 3 set this to true
|
||||
bool testWithParams = true;
|
||||
|
||||
// Demo step 4 set this to true
|
||||
bool registerAkv4Ae = true;
|
||||
|
||||
Console.WriteLine($"Cold Start\nUse Always Encrypted with Enclaves? {(useAlwaysEncrypted ? "Yes" : "No")}");
|
||||
|
||||
// Login to Azure and get Azure SQL DB OAuth2 token
|
||||
Console.WriteLine("Connecting to Azure");
|
||||
(TokenCredential? credential, string? oauth2TokenSql) = LoginToAure();
|
||||
if (credential is null || oauth2TokenSql is null)
|
||||
throw new ArgumentNullException("Unable to login to Azure");
|
||||
|
||||
Console.WriteLine("Connecting to Azure SQL DB");
|
||||
|
||||
// Connect to Azure SQL DB using EntraID AuthN rather than Windows or SQL AuthN
|
||||
var connectionString = GetSQLConnectionString(useAlwaysEncrypted);
|
||||
using SqlConnection conn = new(connectionString)
|
||||
{
|
||||
AccessToken = oauth2TokenSql
|
||||
};
|
||||
conn.Open();
|
||||
|
||||
// Register the enclave attestation URL, do this once on app startup
|
||||
if (useAlwaysEncrypted && registerAkv4Ae)
|
||||
RegisterAkvForAe(credential);
|
||||
|
||||
// From here on is real database work
|
||||
SqlCommand sqlCommand;
|
||||
|
||||
if (useAlwaysEncrypted == false)
|
||||
{
|
||||
string query =
|
||||
"SELECT Top 10 SSN, Salary, LastName, FirstName " +
|
||||
"FROM Employees";
|
||||
|
||||
sqlCommand = new(query, conn);
|
||||
DoQuery(sqlCommand);
|
||||
}
|
||||
else
|
||||
{
|
||||
///////////////////////////////////////////////////
|
||||
// QUERY #1: Get count based on employee salary
|
||||
// Demo step 4 - keep as is, but after demo set to false
|
||||
if (testWithParams == false)
|
||||
{
|
||||
string query1 = "SELECT count(*) FROM Employees where [Salary] > 50000";
|
||||
sqlCommand = new(query1, conn);
|
||||
DoQuery(sqlCommand);
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////
|
||||
// QUERY #2: Find minimum salary with specific SSN
|
||||
string query2 =
|
||||
"SELECT [SSN], [Salary], [LastName], [FirstName] " +
|
||||
"FROM Employees WHERE [Salary] > @MinSalary AND [SSN] LIKE @SSN " +
|
||||
"ORDER by [Salary] DESC";
|
||||
|
||||
sqlCommand = new(query2, conn);
|
||||
|
||||
// MUST use parameters
|
||||
SqlParameter minSalaryParam = new("@MinSalary", SqlDbType.Money) {
|
||||
Value = 50_000
|
||||
};
|
||||
sqlCommand.Parameters.Add(minSalaryParam);
|
||||
|
||||
SqlParameter ssnParam = new("@SSN", SqlDbType.Char) {
|
||||
Value = "6%"
|
||||
};
|
||||
sqlCommand.Parameters.Add(ssnParam);
|
||||
|
||||
DoQuery(sqlCommand);
|
||||
|
||||
///////////////////////////////////////////////////
|
||||
// QUERY #2: sproc to find salary range
|
||||
string query3 = "EXEC usp_GetSalary @MinSalary = @MinSalaryRange, @MaxSalary = @MaxSalaryRange";
|
||||
|
||||
sqlCommand = new(query3, conn);
|
||||
|
||||
SqlParameter minSalaryRange = new("@MinSalaryRange", SqlDbType.Money) {
|
||||
Value = 40_000
|
||||
};
|
||||
sqlCommand.Parameters.Add(minSalaryRange);
|
||||
|
||||
SqlParameter maxSalaryRange = new("@MaxSalaryRange", SqlDbType.Money) {
|
||||
Value = 42_000
|
||||
};
|
||||
sqlCommand.Parameters.Add(maxSalaryRange);
|
||||
|
||||
DoQuery(sqlCommand);
|
||||
}
|
||||
}
|
||||
|
||||
// Perform the actual query and gather stats
|
||||
// The time is the round trip time to and from the database
|
||||
// This will be higher than the actual query time due to network latency
|
||||
// IMPORTANT: the first query is slower due to lots of moving parts
|
||||
// getting loaded, authN, AuthZ, etc.
|
||||
static void DoQuery(SqlCommand sqlCommand)
|
||||
{
|
||||
var stopwatch = Stopwatch.StartNew();
|
||||
|
||||
Console.WriteLine($"\nPerforming Query\n{sqlCommand.CommandText}");
|
||||
|
||||
SqlDataReader? data = null;
|
||||
try
|
||||
{
|
||||
data = sqlCommand.ExecuteReader();
|
||||
}
|
||||
catch (SqlException ex)
|
||||
{
|
||||
Console.WriteLine(ex.Message);
|
||||
Environment.Exit(-1);
|
||||
}
|
||||
catch (System.InvalidOperationException ex)
|
||||
{
|
||||
Console.WriteLine(ex.Message);
|
||||
Environment.Exit(-1);
|
||||
}
|
||||
|
||||
stopwatch.Stop();
|
||||
Console.WriteLine($"Network Roundtrip + Query took [{stopwatch.ElapsedMilliseconds}ms]");
|
||||
|
||||
DumpData(data);
|
||||
data.Close();
|
||||
}
|
||||
}
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
//*********************************************************
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
// This code is licensed under the MIT License (MIT).
|
||||
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
|
||||
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
|
||||
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
|
||||
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
|
||||
//
|
||||
// Author: Michael Howard, Azure Data Security
|
||||
//*********************************************************
|
||||
|
||||
using System.Text;
|
||||
using Azure.Core;
|
||||
using Azure.Identity;
|
||||
using Microsoft.Data.SqlClient;
|
||||
using Microsoft.Data.SqlClient.AlwaysEncrypted.AzureKeyVaultProvider;
|
||||
|
||||
partial class Program
|
||||
{
|
||||
// Helper function to dump binary data
|
||||
// Can truncate the output if needed
|
||||
public static string ByteArrayToHexString(byte[] byteArray, int maxLen = 16)
|
||||
{
|
||||
StringBuilder hex = new(byteArray.Length * 2);
|
||||
foreach (byte b in byteArray)
|
||||
hex.AppendFormat("{0:x2}", b);
|
||||
|
||||
return hex.ToString()[..maxLen];
|
||||
}
|
||||
|
||||
// Build SQL Connection String
|
||||
public static string GetSQLConnectionString(bool useAE = true)
|
||||
{
|
||||
const string _EnvVar = "ConnectContosoHR";
|
||||
|
||||
string? sqlConn =
|
||||
Environment.GetEnvironmentVariable(_EnvVar, EnvironmentVariableTarget.Process)
|
||||
?? throw new ArgumentException($"Missing environment variable, {_EnvVar}");
|
||||
|
||||
// Add AE settings if needed
|
||||
// You could also use a connection string builder, SqlConnectionStringBuilder
|
||||
if (useAE)
|
||||
sqlConn += ";Column Encryption Setting=Enabled;Attestation Protocol=None;";
|
||||
|
||||
return sqlConn;
|
||||
}
|
||||
|
||||
// Login to Azure and get token to Azure SQL DB OAuth2 token
|
||||
// This uses Azure CLI for authentication, but you could change this
|
||||
// to use other methods such as Managed Identity, Service Principal, etc.
|
||||
// You'll get an error if you don't have the Azure CLI installed and have yet to login.
|
||||
// Learn more about the various Azure token credential sources at
|
||||
// https://learn.microsoft.com/en-us/dotnet/api/azure.identity.defaultazurecredential?view=azure-dotnet
|
||||
public static (TokenCredential? tok, string? oauth2Sql) LoginToAure()
|
||||
{
|
||||
try
|
||||
{
|
||||
var credential = new AzureCliCredential();
|
||||
var oauth2TokenSql = credential.GetToken(
|
||||
new TokenRequestContext(
|
||||
["https://database.windows.net/.default"])).Token;
|
||||
return (credential, oauth2TokenSql);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine(ex.Message);
|
||||
return (null, null);
|
||||
}
|
||||
}
|
||||
|
||||
// We need to register the use of AKV for AE, do these once per app on startup
|
||||
public static void RegisterAkvForAe(TokenCredential cred)
|
||||
{
|
||||
var akvAeProvider = new SqlColumnEncryptionAzureKeyVaultProvider(cred);
|
||||
SqlConnection.RegisterColumnEncryptionKeyStoreProviders(
|
||||
customProviders: new Dictionary<string, SqlColumnEncryptionKeyStoreProvider>() {
|
||||
{ SqlColumnEncryptionAzureKeyVaultProvider.ProviderName, akvAeProvider }
|
||||
});
|
||||
}
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2024 Microsoft Corp.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
This is a sample C# client app used to demo the coding aspects of Always Encrypted with VBS enclaves using the ContosoHR Database.
|
||||
|
||||
The raw SQL files are here: https://github.com/microsoft/sql-server-samples/blob/master/samples/features/security/always-encrypted-with-secure-enclaves/azure-sql-database-vbs/setup/PopulateDatabase.sql
|
||||
|
||||
...and the entire repo is here https://github.com/microsoft/sql-server-samples/tree/master/samples/features/security/always-encrypted-with-secure-enclaves/azure-sql-database-vbs.
|
||||
|
||||
To setup, you need an environment variable named ConnectContosoHR that is the connection string to your Azure SQL DB instance. eg; `Server=tcp:XXXXXXXserver.database.windows.net;Database=ContosoHR;`
|
||||
|
||||
Don't put the enclave-specific settings in the connection string, these are added by the code so you can demo with- and without-AE.
|
||||
|
||||
When the code runs, there's a flag in the code:
|
||||
`bool useAlwaysEncrypted = true;`
|
||||
|
||||
You can set this to false and run the code, and then true and re-run.
|
||||
|
||||
- When useAlwaysEncrypted==false, you will see a hex dump of the ciphertext fields, SSN and Salary.
|
||||
- When useAlwaysEncrypted==true, the code will change the connection string to support AE and then display the plaintext for SSN and Salary.
|
||||
Reference in New Issue
Block a user