Delen via


Securing Method Access

Some methods might not be suitable to allow arbitrary untrusted code to call. Such methods pose several risks: The method might provide some restricted information; it might believe any information passed to it; it might not do error checking on the parameters; or with the wrong parameters, it might malfunction or do something harmful. You should be aware of these cases and take action to help protect the method.

In some cases, you might need to restrict methods that are not intended for public use but still must be public. For example, you might have an interface that needs to be called across your own DLLs and hence must be public, but you do not want to expose it publicly to prevent customers from using it or to prevent malicious code from exploiting the entry point into your component. Another common reason to restrict a method not intended for public use (but that must be public) is to avoid having to document and support what might be a very internal interface.

Managed code offers several ways to restrict method access:

  • Limit the scope of accessibility to the class, assembly, or derived classes, if they can be trusted. This is the simplest way to limit method access. Note that, in general, derived classes can be less trustworthy than the class they derive from, though in some cases they share the parent class's identity. In particular, do not infer trust from the keyword protected, which is not necessarily used in the security context.

  • Limit the method access to callers of a specified identity--essentially, any particular evidence (strong name, publisher, zone, and so on) you choose.

  • Limit the method access to callers having whatever permissions you select.

Similarly, declarative security allows you to control inheritance of classes. You can use InheritanceDemand to do the following:

  • Require derived classes to have a specified identity or permission.

  • Require derived classes that override specific methods to have a specified identity or permission.

The following example shows how to help protect a public class for limited access by requiring that callers be signed with a particular strong name. This example uses the StrongNameIdentityPermissionAttribute with a Demand for the strong name. For task-based information on how to sign an assembly with a strong name, see Creating and Using Strong-Named Assemblies.

<StrongNameIdentityPermissionAttribute(SecurityAction.Demand, PublicKey := "…hex…", Name := "App1", Version := "0.0.0.0")>  _
Public Class Class1
End Class
[StrongNameIdentityPermissionAttribute(SecurityAction.Demand, PublicKey="…hex…", Name="App1", Version="0.0.0.0")]
public class Class1
{

} 

See Also

Other Resources

Secure Coding Guidelines