Ler em inglês

Compartilhar via


HostProtectionAttribute Classe

Definição

Cuidado

Code Access Security is not supported or honored by the runtime.

Permite o uso de ações de segurança declarativas para determinar os requisitos de proteção do host. Essa classe não pode ser herdada.

[System.AttributeUsage(System.AttributeTargets.Assembly | System.AttributeTargets.Class | System.AttributeTargets.Constructor | System.AttributeTargets.Delegate | System.AttributeTargets.Method | System.AttributeTargets.Struct, AllowMultiple=true, Inherited=false)]
[System.Obsolete("Code Access Security is not supported or honored by the runtime.", DiagnosticId="SYSLIB0003", UrlFormat="https://aka.ms/dotnet-warnings/{0}")]
public sealed class HostProtectionAttribute : System.Security.Permissions.CodeAccessSecurityAttribute
[System.AttributeUsage(System.AttributeTargets.Assembly | System.AttributeTargets.Class | System.AttributeTargets.Constructor | System.AttributeTargets.Delegate | System.AttributeTargets.Method | System.AttributeTargets.Struct, AllowMultiple=true, Inherited=false)]
[System.Runtime.InteropServices.ComVisible(true)]
[System.Serializable]
public sealed class HostProtectionAttribute : System.Security.Permissions.CodeAccessSecurityAttribute
[System.AttributeUsage(System.AttributeTargets.Assembly | System.AttributeTargets.Class | System.AttributeTargets.Constructor | System.AttributeTargets.Delegate | System.AttributeTargets.Method | System.AttributeTargets.Struct, AllowMultiple=true, Inherited=false)]
public sealed class HostProtectionAttribute : System.Security.Permissions.CodeAccessSecurityAttribute
Herança
Atributos

Exemplos

O exemplo de código a seguir ilustra o uso do HostProtectionAttribute atributo com uma variedade de HostProtectionResource valores.

using System;
using System.IO;
using System.Threading;
using System.Security;
using System.Security.Policy;
using System.Security.Principal;
using System.Security.Permissions;
using System.Diagnostics;
using System.ComponentModel;
using System.Windows.Forms;

// If this application is run on a server that implements host protection, the 
// HostProtectionAttribute attribute is applied. If the application is run on   
// a server that is not host-protected, the attribute evaporates; it is not  
// detected and therefore not applied. Host protection can be configured with  
// members of the HostProtectionResource enumeration to customize the  
// protection offered.
// The primary intent of this sample is to show situations in which the 
// HostProtectionAttribute attribute might be meaningfully used. The  
// environment required to demonstrate a particular behavior is
// too complex to invoke within the scope of this sample.

class HostProtectionExample
{
    public static int Success = 100;
    
    // Use the enumeration flags to indicate that this method exposes 
    // shared state and self-affecting process management.
    // Either of the following attribute statements can be used to set the
    // resource flags.
    [HostProtectionAttribute(SharedState = true, 
        SelfAffectingProcessMgmt = true)]
    [HostProtectionAttribute(Resources = HostProtectionResource.SharedState |
         HostProtectionResource.SelfAffectingProcessMgmt)]
    private static void Exit(string Message, int Code)
    {
        // Exit the sample when an exception is thrown.
        Console.WriteLine("\nFAILED: " + Message + " " + Code.ToString());
        Environment.ExitCode = Code;
        Environment.Exit(Code);
    }

    // Use the enumeration flags to indicate that this method exposes shared 
    // state, self-affecting process management, and self-affecting threading.
    [HostProtectionAttribute(SharedState=true, SelfAffectingProcessMgmt=true,
         SelfAffectingThreading=true, UI=true)]
    // This method allows the user to quit the sample.
    private static void ExecuteBreak()
    {
        Console.WriteLine("Executing Debugger.Break.");
        Debugger.Break();
        Debugger.Log(1,"info","test message");
    }
    
    // Use the enumeration flags to indicate that this method exposes shared 
    // state, self-affecting threading, and the security infrastructure.
    [HostProtectionAttribute(SharedState=true, SelfAffectingThreading=true,
         SecurityInfrastructure=true)]
    // ApplyIdentity sets the current identity.
    private static int ApplyIdentity()
    {
        string[] roles = {"User"};
        try
        {
            AppDomain mAD = AppDomain.CurrentDomain;
            GenericPrincipal mGenPr = 
                new GenericPrincipal(WindowsIdentity.GetCurrent(), roles);
            mAD.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
            mAD.SetThreadPrincipal(mGenPr);
            return Success;
        }
        catch (Exception e)
        {
            Exit(e.ToString(), 5);
        }
        return 0;
    }

    // The following method is started on a separate thread.
    public static void WatchFileEvents()
    {
        try
        {
            Console.WriteLine("In the child thread.");
            FileSystemWatcher watcher = new FileSystemWatcher();
            watcher.Path = "C:\\Temp";
            
            // Watch for changes in LastAccess and LastWrite times, and
            // name changes to files or directories.
            watcher.NotifyFilter = NotifyFilters.LastAccess 
                | NotifyFilters.LastWrite
                | NotifyFilters.FileName | NotifyFilters.DirectoryName;
            
            // Watch only text files.
            watcher.Filter = "*.txt";

            // Add event handlers.
            watcher.Changed += new FileSystemEventHandler(OnChanged);
            watcher.Created += new FileSystemEventHandler(OnChanged);
            watcher.Deleted += new FileSystemEventHandler(OnChanged);
            
            // Begin watching.
            watcher.EnableRaisingEvents = true;

            // Wait for the user to quit the program.
            Console.WriteLine("Event handlers have been enabled.");
            while(Console.Read()!='q');
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
    }

    // Use the enumeration flags to indicate that this method exposes 
    // synchronization and external threading.
    [HostProtectionAttribute(Synchronization=true, ExternalThreading=true)]
    private static void StartThread()
    {
        Thread t = new Thread(new ThreadStart(WatchFileEvents));
        
        // Start the new thread. On a uniprocessor, the thread is not given
        // any processor time until the main thread yields the processor.
        t.Start();
        
        // Give the new thread a chance to execute.
        Thread.Sleep(1000);
    }

    // Call methods that show the use of the HostProtectionResource enumeration.
    [HostProtectionAttribute(Resources=HostProtectionResource.All)]
    static int Main(string [] args)
    {
        try
        {
            // Show use of the HostProtectionResource.SharedState,
            // HostProtectionResource.SelfAffectingThreading, and
            // HostProtectionResource.Security enumeration values.
            ApplyIdentity();
            Directory.CreateDirectory("C:\\Temp");
            
            // Show use of the HostProtectionResource.Synchronization and
            // HostProtectionResource.ExternalThreading enumeration values.
            StartThread();
            Console.WriteLine("In the main thread.");
            Console.WriteLine("Deleting and creating 'MyTestFile.txt'.");
            if (File.Exists("C:\\Temp\\MyTestFile.txt"))
            {
                File.Delete("C:\\Temp\\MyTestFile.txt");
            }

            StreamWriter sr = File.CreateText("C:\\Temp\\MyTestFile.txt");
            sr.WriteLine ("This is my file.");
            sr.Close();
            Thread.Sleep(1000);
            
            // Show use of the HostProtectionResource.SharedState,
            // HostProtectionResource.SelfProcessMgmt,
            // HostProtectionResource.SelfAffectingThreading, and
            // HostProtectionResource.UI enumeration values.
            ExecuteBreak();
            
            // Show the use of the 
            // HostProtectionResource.ExternalProcessManagement 
            // enumeration value.
            MyControl myControl = new MyControl ();
            Console.WriteLine ("Enter 'q' to quit the sample.");
            return 100;
        }
        catch (Exception e)
        {
            Exit(e.ToString(), 0);
            return 0;
        }
    }

    // Define the event handlers.
    private static void OnChanged(object source, FileSystemEventArgs e)
    {
        // Specify whether a file is changed, created, or deleted.
        Console.WriteLine("In the OnChanged event handler.");
        Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType);
    }
}

// The following class is an example of code that exposes 
// external process management.
// Add the LicenseProviderAttribute to the control.
[LicenseProvider (typeof(LicFileLicenseProvider))]
public class MyControl : System.Windows.Forms.Control
{
    // Create a new, null license.
    private License license = null;

    [HostProtection (ExternalProcessMgmt = true)]
    public MyControl ()
    {
        // Determine if a valid license can be granted.
        bool isValid = LicenseManager.IsValid (typeof(MyControl));
        Console.WriteLine ("The result of the IsValid method call is " + 
            isValid.ToString ());
    }

    protected override void Dispose (bool disposing)
    {
        if (disposing)
        {
            if (license != null)
            {
                license.Dispose ();
                license = null;
            }
        }
    }
}

Comentários

Cuidado

O CAS (Segurança de Acesso do Código) foi preterido em todas as versões do .NET Framework e do .NET. As versões recentes do .NET não aceitam anotações de CAS e produzem erros caso as APIs relacionadas ao CAS sejam usadas. Os desenvolvedores devem buscar meios alternativos de realizar tarefas de segurança.

Esse atributo afeta apenas aplicativos não gerenciados que hospedam o common language runtime e implementam a proteção de host, como SQL Server. Se o código for executado em um aplicativo cliente ou em um servidor que não seja protegido pelo host, o atributo "evapora"; ele não é detectado e, portanto, não é aplicado. Quando aplicada, os resultados de ação de segurança na criação de uma demanda de link baseada nos recursos de host que a classe ou método expõe.

Importante

O objetivo desse atributo é impor diretrizes de modelo de programação específicas do host, mas não o comportamento de segurança. Embora uma demanda de link seja usada para verificar a conformidade com requisitos de modelo de programação, o HostProtectionAttribute não é uma permissão de segurança.

Se o host não tem requisitos de modelo de programação, as demandas de link não ocorrem.

Esse atributo identifica o seguinte:

  • Métodos ou classes que não se ajustam ao modelo de programação do host, mas são benignas.

  • Métodos ou classes que não se ajustam ao modelo de programação de host e podem levar à desestabilização do código do usuário gerenciado por servidor.

  • Métodos ou classes que não se ajustam ao modelo de programação de host e podem levar à desestabilização do processo do servidor em si.

Observação

Se você está criando uma biblioteca de classes que pode vir a ser chamada por aplicativos que podem vir a ser executados em um ambiente de host protegido, você deve aplicar esse atributo aos membros que expõem categorias de recursos HostProtectionResource. Os membros da biblioteca de classes do .NET Framework com esse atributo fazem apenas com que o chamador imediato seja verificado. O membro da biblioteca deve também causar uma verificação de seu chamador imediato da mesma maneira.

Observação

Não use o Ngen.exe (Gerador de Imagem Nativa) para criar uma imagem nativa de assemblies protegidos pelo HostProtectionAttribute. Em um ambiente de confiança total, a imagem é sempre carregada, sem considerar o HostProtectionAttributee em um ambiente de confiança parcial a imagem não é carregada.

Construtores

HostProtectionAttribute()
Obsoleto.

Inicializa uma nova instância da classe HostProtectionAttribute com valores padrão.

HostProtectionAttribute(SecurityAction)
Obsoleto.

Inicializa uma nova instância da classe HostProtectionAttribute com o valor SecurityAction especificado.

Propriedades

Action
Obsoleto.

Obtém ou define uma ação de segurança.

(Herdado de SecurityAttribute)
ExternalProcessMgmt
Obsoleto.

Obtém ou define um valor que indica se o gerenciamento de processo externo é exposto.

ExternalThreading
Obsoleto.

Obtém ou define um valor que indica se threading externo é exposto.

MayLeakOnAbort
Obsoleto.

Obtém ou define um valor que indica se recursos poderão causar vazamento de memória se a operação for encerrada.

Resources
Obsoleto.

Obtém ou define os sinalizadores que especificam as categorias de funcionalidade potencialmente prejudiciais ao host.

SecurityInfrastructure
Obsoleto.

Obtém ou define um valor que indica se a infraestrutura de segurança é exposta.

SelfAffectingProcessMgmt
Obsoleto.

Obtém ou define um valor que indica se o gerenciamento de processo autorrealizado é exposto.

SelfAffectingThreading
Obsoleto.

Obtém ou define um valor que indica se threading autorrealizado é exposto.

SharedState
Obsoleto.

Obtém ou define um valor que indica se o estado compartilhado é exposto.

Synchronization
Obsoleto.

Obtém ou define um valor que indica se a sincronização é exposta.

TypeId
Obsoleto.

Quando implementado em uma classe derivada, obtém um identificador exclusivo para este Attribute.

(Herdado de Attribute)
UI
Obsoleto.

Obtém ou define um valor que indica se a interface do usuário é exposta.

Unrestricted
Obsoleto.

Obtém ou define um valor que indica se a permissão total (irrestrita) para o recurso protegido pelo atributo é declarada.

(Herdado de SecurityAttribute)

Métodos

CreatePermission()
Obsoleto.

Cria e retorna uma nova permissão de proteção de host.

Equals(Object)
Obsoleto.

Retorna um valor que indica se essa instância é igual a um objeto especificado.

(Herdado de Attribute)
GetHashCode()
Obsoleto.

Retorna o código hash para a instância.

(Herdado de Attribute)
GetType()
Obsoleto.

Obtém o Type da instância atual.

(Herdado de Object)
IsDefaultAttribute()
Obsoleto.

Quando substituído em uma classe derivada, indica se o valor dessa instância é o valor padrão para a classe derivada.

(Herdado de Attribute)
Match(Object)
Obsoleto.

Quando substituído em uma classe derivada, retorna um valor que indica se essa instância é igual a um objeto especificado.

(Herdado de Attribute)
MemberwiseClone()
Obsoleto.

Cria uma cópia superficial do Object atual.

(Herdado de Object)
ToString()
Obsoleto.

Retorna uma cadeia de caracteres que representa o objeto atual.

(Herdado de Object)

Implantações explícitas de interface

_Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)
Obsoleto.

Mapeia um conjunto de nomes para um conjunto correspondente de identificadores de expedição.

(Herdado de Attribute)
_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)
Obsoleto.

Recupera as informações de tipo para um objeto, que pode ser usado para obter as informações de tipo para uma interface.

(Herdado de Attribute)
_Attribute.GetTypeInfoCount(UInt32)
Obsoleto.

Retorna o número de interfaces de informações do tipo que um objeto fornece (0 ou 1).

(Herdado de Attribute)
_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)
Obsoleto.

Fornece acesso a propriedades e métodos expostos por um objeto.

(Herdado de Attribute)

Aplica-se a

Confira também