© Marius Iulian Mihailescu and Stefania Loredana Nita 2021
M. I. Mihailescu, S. L. NitaPro Cryptography and Cryptanalysis https://doi.org/10.1007/978-1-4842-6367-9_8

8. Overview of the Security.Cryptography Namespace

Marius Iulian Mihailescu1   and Stefania Loredana Nita1
(1)
Bucharest, Romania
 

This chapter offers a quick overview of the main classes, structs, and enums of the System.Security.Cryptography namespace, including cryptographic services, secure encoding and decoding process of the data, and many other operations, such as hashing, generation of random numbers, and message authentication. More details about cryptographic services and their implementations can be seen in Chapter 7.

The goal of this chapter is to provide a comprehensive roadmap for professionals, offering a clear overview of the cryptographic services in the.NET Framework.

Classes

Table 8-1 lists the main classes that deal with the implementation and encapsulation process of cryptographic algorithms, which are in Cryptography Next Generation (CNG).
Table 8-1

System.Security.Cryptography Namespace

Class

Description

AesCng

Implements support for CNG for the Advanced Encryption (AES) algorithm

CngAlgorithm

Encapsulates the name of an encryption algorithm

CngAlgorithmGroup

The same as CngAlgorithm, but the encapsulation is done for a group of encryption algorithms

CngKey

Defining the functionalities of the cryptographic keys used with CNG

CngKeyBlobFormat

The key is declared as the BLOB format and is used with CNG objects.

CngKeyCreationParameters

Advanced support for properties regarding the key creation

CngPropertyCollection

Provides strong support for a typed collection related to CNG properties

CngProvider

The name of the key storage provider (KSP) is encapsulated in order to be used further with CNG objects.

CngUIPolicy

An optional configuration parameter for the user interface (UI) CNG displays when a protected key is being accessed. It also provides encapsulation for the configuration.

DSACng

Support for the CNG implementation of the Digital Signature Algorithm (DSA)

DSAOpenSsl

Offers implementation for DSA with OpenSSL support

ECDiffieHellmanCng

Offers support for the CNG implementation of the Elliptic Curve Diffie-Hellman (ECDH) algorithm. The class’ purpose is to perform cryptographic operations.

ECDiffieHellmanCngPublicKey

Creates a public key for ECDH which can be used with the ECDiffieHellmanCng class

ECDiffieHellmanOpenSsl

Offers support for the implementation of the Elliptic Curve Diffie-Hellman (ECDH) algorithm supported by OpenSSL

ECDsaCng

Offers CNG support and implementation for ECDSA

ECDsaOpenSsl

Offers support for the implementation of the Elliptic Curve Digital Signature Algorithm (ECDSA) based on OpenSSL

ProtectedData

Offers methods for encrypting and decrypting data. The class cannot be inherited.

RSACng

Offers CNG support and implementation for the RSA algorithm

RSAOpenSsl

Offers support and implementations for RSA with OpenSSL support

SafeEvpPKeyHandle

Represents a special pointer (EVP_PKEY*) for OpenSSL

TripleDESCng

Offers CNG support and implementation for the Triple Data Encryption Standard (3DES) algorithm

Structs

Table 8-2 shows one of the most important structs that deal with the encapsulation of the properties of CNG key providers.
Table 8-2

Structs within the System.Security.Cryptography Namespace

Struct

Description

CngProperty

It provides encapsulation for the property of a CNG key or provider.

Enums

.NET Framework, starting with 3.5 and related to cryptography and security mechanisms, has a set of enums that offer important options for dealing with policies, key creation, and handling cryptographic operations. Table 8-3 mentions the main important enums that can be found within the System.Security.Cryptography namespace.
Table 8-3

Enums within the System.Security.Cryptography Namespace

Enum

Description

CngExportPolicies

Key export policies for a cryptographic key

CngKeyCreationOptions

Options for key creations

CngKeyHandleOpenOptions

Options for opening key handles

CngKeyOpenOptions

Options for opening a key

CngKeyUsages

Cryptographic operations for CNG keys that are used with it

CngPropertyOptions

CNG key property options

CngUIProtectionLevels

Protection level related to the key used in a user interface and its scenarios

DataProtectionScope

Gets the scope of the data protection that can be applied using the Protect(Byte[], Byte[], DataProtectionScope) method

ECKeyXmlFormat

Defines and offers support for XML serialization formats for elliptic curve keys

Security Model in .NET Framework

Figure 8-1 shows a general security model that offers a quick overview on how role-based security plays an important role in the authentication process. The authentication process plays a vital role due to the spread of the most important components of the security architecture, such as the application domain, the verification process, and code access security.
../images/493660_1_En_8_Chapter/493660_1_En_8_Fig1_HTML.jpg
Figure 8-1

.NET Framework security architecture with role-based security

Looking at the components that form the security architecture during the process of implementing cryptographic mechanisms, it’s important to understand the definitions and borders of each of the components. The application domain provides a certain level of isolating processes and is necessary to make sure that the code running in the application cannot be affected by an adversary. Based on this aspect, the isolation boundary within the application domain provides an isolation boundary for security, reliability, and versioning. Most of the application domains are created during the runtime hosts.

In Figure 8-2, you can see the main components on which the role-based security is focused, such as authentication, authorization and, principal and identity.
../images/493660_1_En_8_Chapter/493660_1_En_8_Fig2_HTML.jpg
Figure 8-2

.NET Framework security architecture with role-based security

In Figure 8-3, the components of the application domain should be treated with maximum responsibility during the implementation process. During the implementation, there is a Boolean property called IsFullyTrusted.
../images/493660_1_En_8_Chapter/493660_1_En_8_Fig3_HTML.jpg
Figure 8-3

.NET Framework security architecture with application domain components

Achieving the goal of the first components, fully trusted and partially trusted, Listing 8-1 shows how such a process can be implemented and transposed in a real case. The same method and procedure can be used to prove if it is heterogeneous, homogeneous, or sandboxing by application domain. See Figure 8-4 for the output.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FullyOrPartiallyTrustedExample
{
    class Program
    {
        public class InstanceWorker : MarshalByRefObject
        {
            static void Main()
            {
                InstanceWorker iw = new InstanceWorker();
                iw.RunningTestIfItIsFullyTrusted();
                AppDomain adSandbox = GetInternetSandbox();
                iw = (InstanceWorker)
                        adSandbox.CreateInstanceAndUnwrap(
                        typeof(InstanceWorker).Assembly.FullName,
                        typeof(InstanceWorker).FullName);
                iw.RunningTestIfItIsFullyTrusted();
            }
            public void RunningTestIfItIsFullyTrusted()
            {
                AppDomain app_domain = AppDomain.CurrentDomain;
                Console.WriteLine(" Application domain '{0}': IsFullyTrusted = {1}", app_domain.FriendlyName, app_domain.IsFullyTrusted);
                Console.WriteLine("IsFullyTrusted = {0} for the current assembly", typeof(InstanceWorker).Assembly.IsFullyTrusted);
                Console.WriteLine("IsFullyTrusted = {0} for mscorlib", typeof(int).Assembly.IsFullyTrusted);
            }
            static AppDomain GetInternetSandbox()
            {
                System.Security.Policy.Evidence theEvidenceOfHost = new System.Security.Policy.Evidence();
                theEvidenceOfHost.AddHostEvidence(new System.Security.Policy.Zone(System.Security.SecurityZone.Internet));
                System.Security.PermissionSet thePermissionSet = System.Security.SecurityManager.GetStandardSandbox(theEvidenceOfHost);
                AppDomainSetup appDomainSetup = new AppDomainSetup
                {
                    ApplicationBase = System.IO.Directory.GetCurrentDirectory()
                };
                return AppDomain.CreateDomain("Sandbox", theEvidenceOfHost, appDomainSetup, thePermissionSet, null);
            }
        }
    }
}
Listing 8-1

Fully Trusted or Partially Trusted Example

../images/493660_1_En_8_Chapter/493660_1_En_8_Fig4_HTML.jpg
Figure 8-4

The output of the application domain

In Figure 8-5, you can see which components and modules are involved the verification process. You can see that the verification process looks like a collection of steps, C# compilation, JIT compilation, Native Image Generator and PEVerify Tool. In the following sections, we will analyze the most important components listed above.
../images/493660_1_En_8_Chapter/493660_1_En_8_Fig5_HTML.jpg
Figure 8-5

.NET Framework security architecture with the verification process components

The JIT compilation (see Figure 8-6) is a complex process with vital points that can be exploited to gain access to different parts of the application. The goal of the JIT compilation is to speed up the execution of the code and to provide support for multiple platforms. The support is tricky since it can expose and create security breaches into the system.
../images/493660_1_En_8_Chapter/493660_1_En_8_Fig6_HTML.jpg
Figure 8-6

JIT compilation process

Many security specialists and professionals consider this a gap in the process of assuring the security of the application because of the multiple points that can be exploited by an attacker, such as dissembling .exe or .dll files with the proper tools and proceeding with software obfuscation attacks.

Once the JIT process is completed, we can move further to the native generator image (NGEN) . NGEN is a powerful tool that improves the performance of managed applications. NGEN, which can be found as Ngen.exe, creates (compiles) native images (for example, ISO files), which contain files that are compiled in a manner specific for processors as machine code, and deploys them on the native image cache of the end user’s local computer. This is a dangerous point due to the fact that we never know who and what the users will have on their computers and if a malicious user is waiting for the proper moment to exploit in order to find their vulnerability point.

The last step is based on the PE Verify Tool or Peverify.exe. It's a very useful tool that offers an a significant amount of help to developers who are generating Microsoft Intermediate Language (MSIL), such as compiler writers, with the goal of determining if the safety requirements are met and expected with their MSIL code.

Figure 8-7 shows that we are on the last component of the .NET Framework security architecture, entitled code access security. All of its components are important and every professional developer should include them in their application in the developing process and in security analysis and design.
../images/493660_1_En_8_Chapter/493660_1_En_8_Fig7_HTML.jpg
Figure 8-7

The .NET Framework security architecture with the code access security components

Policy , permissions , and enforcement should be seen as a whole unit, as a “heart” that beats for each level of trust on different code that is running in the same application.

Getting familiarized with the following code access security concepts and mechanisms will give professionals a strong background of deep knowledge on the internal mechanisms of code access security (CAS). This being said, for writing effective applications with the purpose of targeting a common language runtime, we have the following:
  • Type-safe code: A special type of code that accesses only those types that are well-defined

  • Imperative and declarative syntax: The code that targets a common language runtime has the ability to have an interaction with the security system. The interaction is to request permissions and override certain security settings.

  • Secure class libraries: The libraries have a usage of security demands and their main goal is to ensure that those who are using and calling the library have the proper permissions to access the library and its resources.

  • Transparent code: With .NET Framework 4 professionals have the ability to determine if the code can run as security-transparent. Also, identifying permissions is one of the tasks that need to be fulfilled by determining the transparence allowance.

Declarative Security

The syntax that is used by the declarative security is based on the attributes that are used in order to insert security information within the metadata of the code written by professional developers.

To use declarative security invokes, the first step is the initialization of the data state within the permission object. Listing 8-2 shows an example of a declarative syntax. The example is very suggestive and you can provide the code invoker if you have a permission entitled UserPermission.
using System.Security.Permissions;
[UserPermission(SecurityAction.Demand, Unrestricted = true)]
public class Example
{
   public Example()
   {
      //** is beging protected by the security call
   }
   public void SomeMethodForUserA()
   {
      //** is beging protected by the security call
   }
   public void SomeOtherMethodForUserB()
   {
      //** is beging protected by the security call
   }
}
Listing 8-2

Example of Declarative Security

The SecurityAction.Demand specifies that the invokers need that permission for running the code.

Imperative Security

The syntax provided by imperative security invokes a security call to create a new instance of the object that holds the permission. The imperative security can be used to invoke demand and to override. It is very important that no requests are done. This is impossible to fulfill within imperative security.

Listing 8-3 shows an example of how the imperative syntax works for requesting the code’s caller to have a certain permission called UserPermission.
public class Example
{
   public Example()
   {
       //** the constructor of the class
   }
   public void SomeMethodForUserA()
   {
       //** UserPermission has been demanded
       //** to use imperative syntax.
       UserPermission user_permission = new UserPermission();
       user_permission.Demand();
       //** here is being protected by the security call
   }
   public void SomeOtherMethodForUserB()
   {
      //** is not being protected by the security call
   }
}
Listing 8-3

Example of Imperative Security

Conclusion

In this chapter, we discussed the System.Security.Cryptography namespace and we gave an overview of its classes, structs, and enums by pointing out their main designation. We continued our journey by explaining why professionals should work based on the .NET Framework security model, respecting their components and following the workflow as a necessary guideline.

At the end of this chapter, you will have
  • A big picture of the System.Security.Cryptography namespace

  • An understanding of the main designations of the classes, structs, and enums

  • An understanding of the vital points of the security model within .NET Framework which can lead to a security disaster

  • A clear image of how the main components work and communicate, such as the application domain, verification process, and code access security

  • An in-depth understanding of JIT compilation and its process

  • An understanding of how the verification process can expose security breaches

  • An understanding of how, when, and why to use declarative and imperative security and an overview of their importance during the implementation process

Bibliography

  1. [1]

    Sarcar Vaskaran. Interactive C#: Fundamentals, Core Concepts and Patterns. Apress, 2018.

     
  2. [2]

    Andrew Troelsen and Philip Japikse. Pro C# 7 with .NET and .NET Core. Apress, 2017.

     
  3. [3]

    Joshi Bipin. Beginning XML with C# 7: XML Processing and Data Access for C# Developers. Apress, 2017.

     
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.181.145