SQL Server 程式設計和主機保護屬性SQL Server Programming and Host Protection Attributes

在 SQL Server 主機中載入和執行 Managed 程式碼的功能需要符合主機對程式碼存取安全性和主機資源保護的需求。The ability to load and execute managed code in a SQL Server host requires meeting the host's requirements for both code access security and host resource protection. 程式碼存取安全性需求由三個 SQL Server 權限集合其中之一所指定:SAFE、EXTERNAL-ACCESS 或 UNSAFE。The code access security requirements are specified by one of three SQL Server permission sets: SAFE, EXTERNAL-ACCESS, or UNSAFE. 在 SAFE 或 EXTERNAL-ACCESS 權限集合內執行的程式碼,必須避免已套用 HostProtectionAttribute 屬性的特定類型或成員。Code executing within the SAFE or EXTERNAL-ACCESS permission sets must avoid certain types or members that have the HostProtectionAttribute attribute applied. HostProtectionAttribute 不像可靠性保證一樣是安全性權限,關鍵在於它會識別主機可能不允許的特定程式碼建構 (類型或方法)。The HostProtectionAttribute is not a security permission as much as a reliability guarantee in that it identifies specific code constructs, either types or methods, that the host may disallow. 使用 HostProtectionAttribute 會強制使用有助於保護主機穩定性的程式設計模型。The use of the HostProtectionAttribute enforces a programming model that helps protect the stability of the host.

主機保護屬性Host Protection Attributes

主機保護屬性可識別不適合主機程式設計模型的類型或成員,並且代表下列遞增的可靠性威脅層級:Host protection attributes identify types or members that do not fit the host programming model and represent the following increasing levels of reliability threat:

  • 不是良性。Are otherwise benign.

  • 可能會導致伺服器管理的使用者程式碼不穩定。Could lead to destabilization of server-managed user code.

  • 可能會導致伺服器處理序本身不穩定。Could lead to destabilization of the server process itself.

SQL Server 不允許使用具有 HostProtectionAttribute 且其 HostProtectionResource 值指定為 SharedStateSynchronizationMayLeakOnAbortExternalProcessMgmt 的類型或成員。SQL Server disallows the use of a type or member that has a HostProtectionAttribute that specifies a HostProtectionResource value of SharedState, Synchronization, MayLeakOnAbort, or ExternalProcessMgmt. 這可防止組件呼叫可啟用共用狀態、執行同步處理、可能造成終止時資源流失,或影響 SQL Server 程序完整性的成員。This prevents the assemblies from calling members that enable sharing state, perform synchronization, might cause a resource leak on termination, or affect the integrity of the SQL Server process.

不允許的類型和成員Disallowed Types and Members

下表提供 SQL Server 不允許其 HostProtectionResource 值的類型和成員。The following table identifies types and members whose HostProtectionResource values are disallowed by SQL Server.

命名空間Namespace 類型或成員Type or member
Microsoft.Win32 PowerModeChangedEventArgs 類別PowerModeChangedEventArgs class

PowerModeChangedEventHandler 委派PowerModeChangedEventHandler delegate

SessionEndedEventArgs 類別SessionEndedEventArgs class

SessionEndedEventHandler 委派SessionEndedEventHandler delegate

SessionEndingEventArgs 類別SessionEndingEventArgs class

SessionEndingEventHandler 委派SessionEndingEventHandler delegate

SessionSwitchEventArgs 類別SessionSwitchEventArgs class

SessionSwitchEventHandler 委派SessionSwitchEventHandler delegate

SystemEvents 類別SystemEvents class

TimerElapsedEventArgs 類別TimerElapsedEventArgs class

TimerElapsedEventHandler 委派TimerElapsedEventHandler delegate

UserPreferenceChangedEventArgs 類別UserPreferenceChangedEventArgs class

UserPreferenceChangingEventArgs 類別UserPreferenceChangingEventArgs class
System.Collections ArrayList.Synchronized 方法ArrayList.Synchronized method

Hashtable.Synchronized 方法Hashtable.Synchronized method

Queue.Synchronized 方法Queue.Synchronized method

SortedList.Synchronized 方法SortedList.Synchronized method

Stack.Synchronized 方法Stack.Synchronized method
System.ComponentModel AddingNewEventArgs 類別AddingNewEventArgs class

AddingNewEventHandler 委派AddingNewEventHandler delegate

ArrayConverter 類別ArrayConverter class

AsyncCompletedEventArgs 類別AsyncCompletedEventArgs class

AsyncCompletedEventHandler 委派AsyncCompletedEventHandler delegate

AsyncOperation 類別AsyncOperation class

AsyncOperationManager 類別AsyncOperationManager class

AttributeCollection 類別AttributeCollection class

BackgroundWorker 類別BackgroundWorker class

BaseNumberConverter 類別BaseNumberConverter class

BindingList<T> 類別BindingList<T> class

BooleanConverter 類別BooleanConverter class

ByteConverter 類別ByteConverter class

CancelEventArgs 類別CancelEventArgs class

CancelEventHandler 委派CancelEventHandler delegate

CharConverter 類別CharConverter class

CollectionChangeEventArgs 類別CollectionChangeEventArgs class

CollectionChangeEventHandler 委派CollectionChangeEventHandler delegate

CollectionConverter 類別CollectionConverter class

ComponentCollection 類別ComponentCollection class

ComponentConverter 類別ComponentConverter class

ComponentEditor 類別ComponentEditor class

ComponentResourceManager 類別ComponentResourceManager class

Container 類別Container class

ContainerFilterService 類別ContainerFilterService class

CultureInfoConverter 類別CultureInfoConverter class

CustomTypeDescriptor 類別CustomTypeDescriptor class

DateTimeConverter 類別DateTimeConverter class

DecimalConverter 類別DecimalConverter class

ActiveDesignerEventArgs 類別ActiveDesignerEventArgs class

ActiveDesignerEventHandler 委派ActiveDesignerEventHandler delegate

CheckoutException 類別CheckoutException class

CommandID 類別CommandID class

ComponentChangedEventArgs 類別ComponentChangedEventArgs class

ComponentChangedEventHandler 委派ComponentChangedEventHandler delegate

ComponentChangingEventArgs 類別ComponentChangingEventArgs class

ComponentChangingEventHandler 委派ComponentChangingEventHandler delegate

ComponentEventArgs 類別ComponentEventArgs class

ComponentEventHandler 委派ComponentEventHandler delegate

ComponentRenameEventArgs 類別ComponentRenameEventArgs class

ComponentRenameEventHandler 委派ComponentRenameEventHandler delegate

DesignerCollection 類別DesignerCollection class

DesignerEventArgs 類別DesignerEventArgs class

DesignerEventHandler 委派DesignerEventHandler delegate

DesignerOptionService 類別DesignerOptionService class

DesignerTransaction 類別DesignerTransaction class

DesignerTransactionCloseEventArgs 類別DesignerTransactionCloseEventArgs class

DesignerTransactionCloseEventHandler 委派DesignerTransactionCloseEventHandler delegate

DesignerVerb 類別DesignerVerb class

DesignerVerbCollection 類別DesignerVerbCollection class

DesigntimeLicenseContext 類別DesigntimeLicenseContext class

DesigntimeLicenseContextSerializer 類別DesigntimeLicenseContextSerializer class

MenuCommand 類別MenuCommand class

ComponentSerializationService 類別ComponentSerializationService class

ContextStack 類別ContextStack class

DesignerLoader 類別DesignerLoader class

InstanceDescriptor 類別InstanceDescriptor class

MemberRelationshipService 類別MemberRelationshipService class

ResolveNameEventArgs 類別ResolveNameEventArgs class

ResolveNameEventHandler 委派ResolveNameEventHandler delegate

SerializationStore 類別SerializationStore class

ServiceContainer 類別ServiceContainer class

ServiceCreatorCallback 委派ServiceCreatorCallback delegate

StandardCommands 類別StandardCommands class

StandardToolWindows 類別StandardToolWindows class

DoubleConverter 類別DoubleConverter class

DoWorkEventArgs 類別DoWorkEventArgs class

DoWorkEventHandler 委派DoWorkEventHandler delegate

EnumConverter 類別EnumConverter class

EventDescriptor 類別EventDescriptor class

EventDescriptorCollection 類別EventDescriptorCollection class

EventHandlerList 類別EventHandlerList class

ExpandableObjectConverter 類別ExpandableObjectConverter class

HandledEventArgs 類別HandledEventArgs class

HandledEventHandler 委派HandledEventHandler delegate

InstanceCreationEditor 類別InstanceCreationEditor class

Int16Converter 類別Int16Converter class

Int32Converter 類別Int32Converter class

Int64Converter 類別Int64Converter class

InvalidAsynchronousStateException 類別InvalidAsynchronousStateException class

InvalidEnumArgumentException 類別InvalidEnumArgumentException class

BeginInvoke 方法BeginInvoke method

License 類別License class

LicenseContext 類別LicenseContext class

LicenseException 類別LicenseException class

LicenseManager 類別LicenseManager class

LicenseProvider 類別LicenseProvider class

LicFileLicenseProvider 類別LicFileLicenseProvider class

ListChangedEventArgs 類別ListChangedEventArgs class

ListChangedEventHandler 委派ListChangedEventHandler delegate

ListSortDescription 類別ListSortDescription class

ListSortDescriptionCollection 類別ListSortDescriptionCollection class

MaskedTextProvider 類別MaskedTextProvider class

MemberDescriptor 類別MemberDescriptor class

MultilineStringConverter 類別MultilineStringConverter class

NestedContainer 類別NestedContainer class

NullableConverter 類別NullableConverter class

ProgressChangedEventArgs 類別ProgressChangedEventArgs class

ProgressChangedEventHandler 委派ProgressChangedEventHandler delegate

PropertyChangedEventArgs 類別PropertyChangedEventArgs class

PropertyChangedEventHandler 委派PropertyChangedEventHandler delegate

PropertyDescriptor 類別PropertyDescriptor class

PropertyDescriptorCollection 類別PropertyDescriptorCollection class

ReferenceConverter 類別ReferenceConverter class

RefreshEventArgs 類別RefreshEventArgs class

RefreshEventHandler 委派RefreshEventHandler delegate

RunWorkerCompletedEventArgs 類別RunWorkerCompletedEventArgs class

RunWorkerCompletedEventHandler 委派RunWorkerCompletedEventHandler delegate

SByteConverter 類別SByteConverter class

SingleConverter 類別SingleConverter class

StringConverter 類別StringConverter class

SyntaxCheck 類別SyntaxCheck class

TimeSpanConverter 類別TimeSpanConverter class

TypeConverter 類別TypeConverter class

TypeDescriptionProvider 類別TypeDescriptionProvider class

TypeDescriptor 類別TypeDescriptor class

TypeListConverter 類別TypeListConverter class

UInt16Converter 類別UInt16Converter class

UInt32Converter 類別UInt32Converter class

UInt64Converter 類別UInt64Converter class

WarningException 類別WarningException class

Win32Exception 類別Win32Exception class
System.Diagnostics Debug.Listeners 屬性Debug.Listeners property

Trace.Listeners 屬性Trace.Listeners property

EventLog.SynchronizingObject 屬性EventLog.SynchronizingObject property

ConsoleTraceListener 類別ConsoleTraceListener class

DefaultTraceListener 類別DefaultTraceListener class

DelimitedListTraceListener 類別DelimitedListTraceListener class

EventLogTraceListener 類別EventLogTraceListener class

PerformanceCounter 類別PerformanceCounter class

PerformanceCounterCategory 類別PerformanceCounterCategory class

Process 類別Process class

ProcessStartInfo 類別ProcessStartInfo class

TextWriterTraceListener 類別TextWriterTraceListener class

TraceListener 類別TraceListener class

XmlWriterTraceListener 類別XmlWriterTraceListener class

TraceSource.Listeners 屬性TraceSource.Listeners property
System.IO Stream.Synchronized 方法Stream.Synchronized method

TextReader.Synchronized 方法TextReader.Synchronized method

TextWriter.Synchronized 方法TextWriter.Synchronized method
System.Reflection.Emit ConstructorBuilder 類別ConstructorBuilder class

EventBuilder 類別EventBuilder class

FieldBuilder 類別FieldBuilder class

MethodBuilder 類別MethodBuilder class

CustomAttributeBuilder 類別CustomAttributeBuilder class

MethodRental 類別MethodRental class

ModuleBuilder 類別ModuleBuilder class

PropertyBuilder 類別PropertyBuilder class

TypeBuilder 類別TypeBuilder class

UnmanagedMarshal 類別UnmanagedMarshal class
System.Text Group.Synchronized 方法Group.Synchronized method

Match.Synchronized 方法Match.Synchronized method
System.Threading AutoResetEvent 類別AutoResetEvent class

EventWaitHandle 類別EventWaitHandle class

ManualResetEvent 類別ManualResetEvent class

Monitor 類別Monitor class

Mutex 類別Mutex class

ReaderWriterLock 類別ReaderWriterLock class

Semaphore 類別Semaphore class

Thread.AllocateNamedDataSlot 方法Thread.AllocateNamedDataSlot method

Thread.BeginCriticalRegion 方法Thread.BeginCriticalRegion method

Thread.EndCriticalRegion 方法Thread.EndCriticalRegion method

Thread.FreeNamedDataSlot 方法Thread.FreeNamedDataSlot method

Thread.GetData 方法Thread.GetData method

Thread.Join 方法Thread.Join method

Thread.SetApartmentState 方法Thread.SetApartmentState method

Thread.SetData 方法Thread.SetData method

Thread.SpinWait 方法Thread.SpinWait method

Thread.Start 方法Thread.Start method

Thread.TrySetApartmentState 方法Thread.TrySetApartmentState method

ThreadPool 類別ThreadPool class

Timer 類別Timer class
System.Timers Timer 類別Timer class
System.Web.Configuration MachineKeyValidationConverter 類別MachineKeyValidationConverter class
System.Windows.Forms AutoCompleteStringCollection.SyncRoot 屬性AutoCompleteStringCollection.SyncRoot property

SQL Server 權限集合SQL Server Permission Sets

SQL Server 可讓使用者針對部署到資料庫中的程式碼指定可靠性需求。SQL Server allows users to specify the reliability requirements for code deployed into a database. 當組件上傳至資料庫時,組件作者可以為該組件指定三個權限集合的其中一個:SAFE、EXTERNAL-ACCESS 或 UNSAFE。When assemblies are uploaded into the database, the author of the assembly can specify one of three permission sets for that assembly: SAFE, EXTERNAL-ACCESS, or UNSAFE.

權限集合Permission set SAFESAFE EXTERNAL-ACCESSEXTERNAL-ACCESS UNSAFEUNSAFE
程式碼存取安全性Code access security 僅限執行Execute only 執行 + 存取外部資源Execute + access to external resources 無限制的Unrestricted
程式設計模型限制Programming model restrictions Yes Yes 無限制No restrictions
可驗證性需求Verifiability requirement Yes Yes No
呼叫原生程式碼的能力Ability to call native code No No Yes

SAFE 是最可靠且安全的模式,並且在允許的程式設計模型方面有相關限制。SAFE is the most reliable and secure mode with associated restrictions in terms of the allowed programming model. SAFE 程式碼具有高可靠性和安全性功能。SAFE code has high reliability and security features. SAFE 組件有足夠的權限來執行、執行計算,以及存取本機資料庫。SAFE assemblies are given enough permission to run, perform computations, and have access to the local database. SAFE 組件必須是可驗證的型別安全,且不允許呼叫 Unmanaged 程式碼。SAFE assemblies need to be verifiably type safe and are not allowed to call unmanaged code.

EXTERNAL-ACCESS 提供了中級安全性選項,允許程式碼存取資料庫之外的資源,但仍然保有 SAFE 的可靠性和安全性。EXTERNAL-ACCESS provides an intermediate security option, allowing code to access resources external to the database but still having the reliability and safety of SAFE.

UNSAFE 適用於只能由資料庫管理員建立的高度信任程式碼。UNSAFE is for highly trusted code that can only be created by database administrators. 此受信任的程式碼沒有程式碼存取限制,且可以呼叫 Unmanaged (原生) 程式碼。This trusted code has no code access restrictions, and it can call unmanaged (native) code.

SQL Server 使用主機層級程式碼存取安全性原則層來設定主機原則,根據儲存在 SQL Server 目錄的權限集合,授與三個權限集合的其中一個。SQL Server uses the host-level code access security policy layer to set up a host policy that grants one of the three sets of permissions based on the permission set stored in SQL Server catalogs. 在資料庫內執行的 Managed 程式碼一律會取得這些程式碼存取權限集合的其中一個。Managed code running inside the database always gets one of these code access permission sets.

程式設計模型限制Programming Model Restrictions

SQL Server 中的 Managed 程式碼程式設計模型需要的函式、程序和類型,不需要使用跨多個引動過程保留的狀態,或是在多個使用者工作階段之間共用狀態。The programming model for managed code in SQL Server requires functions, procedures, and types which do not require the use of state held across multiple invocations or the sharing of state across multiple user sessions. 此外,如先前所述,共用狀態的存在可能會導致嚴重的例外狀況,影響應用程式的延展性和可靠性。Further, as described earlier, the presence of shared state can cause critical exceptions that impact the scalability and the reliability of the application.

基於這些考量,SQL Server 不允許使用靜態變數和靜態資料成員。Given these considerations, SQL Server disallows the use of static variables and static data members. 對於 SAFE 及 EXTERNAL-ACCESS 組件,SQL Server 會在 CREATE ASSEMBLY 時,檢查組件的中繼資料,並且如果它找到使用靜態資料成員和變數,便讓這類組件的建立作業失敗。For SAFE and EXTERNAL-ACCESS assemblies, SQL Server examines the metadata of the assembly at CREATE ASSEMBLY time, and fails the creation of such assemblies if it finds the use of static data members and variables.

請參閱See also