Professional Documents
Culture Documents
Mark Sapossnek
CS 594 Computer Science Department Metropolitan College Boston University
Prerequisites
Overview of .NET
Learning Objectives
Understand the breadth of services that the Common Language Runtime provides
Agenda
What Is the CLR? Assemblies Execution Model Interoperability Security
Web Forms Web Services Windows applications Development Debugging Deployment Maintenance
Common Language Specification ASP.NET: Web Services and Web Forms Windows Forms
Deep cross-language interoperability Increased productivity Simple, reliable deployment Fewer versioning problems NO MORE DLL HELL
Deployment services
Run-time services
Metadata Transparent proxies Memory management Consistent exception handling Designers and wizards Debuggers Profilers
Increased productivity
DLL Hell
Object remoting Events Multiple RTOSes Same tools used for desktop
Consistent framework raises the abstraction layer Gradual transition from simplicity to full power Less training, greater productivity
Object-oriented in flavor Procedural languages well supported Functional languages possible Rules for wide reach All .NET Framework functionality available
Mapping of data types: Programming language Framework JIT compiles intermediate language (MSIL) into native code Highly optimized for platform or device
Garbage collector Permission and policy-based security Exceptions Threading Reflection Diagnostics and profiling
Type Checker
Security Engine MSIL to Native Compilers (JIT) Code Manager
Exception Manager
Debug Engine Garbage Collector (GC)
Class Loader
Includes the Common Language Runtime and a subset of the .NET Framework classes
http://msdn.microsoft.com/net/ecma/ http://www.ecma.ch
Agenda
What Is the CLR? Assemblies Execution Model Interoperability Security
Assemblies
Overview
Contains code and metadata Assemblies function as:
Unit of deployment Type boundary Security boundary Reference scope boundary Version boundary Unit of side-by-side execution
Assemblies
Overview
Assemblies can be:
Dynamic
.NET Framework SDK Visual Studio.NET Your own code
Dynamic assemblies
Assemblies
Components of an Assembly
Manifest
Type metadata
Managed code
Resources
Assemblies
Components of an Assembly
ParcelTracker.DLL Manifest Type Metadata MSIL Resources
Assemblies
Components of an Assembly
An assembly is a logical unit, not physical
Assemblies
Components of an Assembly
A single-file assembly
A multi-file assembly
File2.dll
Metadata MSIL
File1.dll
Manifest Metadata MSIL
Graphic.jpg
Resource
Logo.gif
Resource
File3.dll
Manifest
Assemblies
Assembly Generation Tool: al.exe
Takes one or more files (containing either MSIL or resource files) and produces a file with an assembly manifest. When compiling a C# file, you can specify that it create a module instead of an assembly by using /target:module.
Assemblies
Manifest
Manifest contains:
Identity information
Assemblies
Manifest and Metadata
Type Descriptions Name Version Culture Other assemblies Security Permissions Exported Types Assembly Description Classes Base classes Implemented interfaces Data members Methods
Manifest
Metadata
Assemblies
Attributes
Assemblies
Demo: ILDASM.EXE
Allows you to inspect the metadata and disassembled IL code in an assembly Great way to see whats really going on Use ildasm /? to see the various options
Assemblies
Metadata
Key to simpler programming model Generated automatically
Assemblies
Metadata: Creation and Use
Serialization
(e.g. SOAP)
Source Code
Compiler
Reflection Designers
Debugger
Assembly
(Manifest, metadata and code)
Profiler
Schema Generator
Assemblies
Compilers Use Metadata
For cross-language data type import Emit metadata with output code
Describe types defined and used Record external assemblies referenced Record version information Obsolete CLS compliance Compiled for debugging Language-specific markers
Assemblies
Other Tools Use Metadata
Designer behavior
Category Description
Designer extensibility
Assemblies
Global Assembly Cache
A set of assemblies that can be referenced by any application on a machine Should be used only when needed
Located at %SystemRoot%\assembly
(c:\winnt\assembly)
Installer program gacutil.exe Windows Explorer
Add assemblies by
Assembly Cache Viewer (shfusion.dll) is a shell extension for GAC that is installed with the .NET Framework SDK
Assemblies
Strong Names
Strong names identify an assembly
Contains text name, version, culture, public key, and digital signature
No one else can create a new version of your assembly Guarantees that contents of an assembly didnt change since it was built
Assemblies
Strong Names
To sign an assembly with a strong name:
Use Assembly Generation tool: al.exe Use assembly attributes (AssemblyKeyFileAttribute or AssemblyKeyNameAttribute) To generate a key pair use the Strong Name tool: sn.exe
Assemblies
Demo: Installing an Assembly in GAC
Create assembly Sign assembly with key from sn.exe Install into GAC via gacutil.exe, Assembly Cache Viewer and .NET Framework Configuration Tool
Assemblies
Signcode
A strong name identifies an assembly but it does not authenticate an assembly
Assemblies
Signcode
To use signcode:
Obtain a Software Publisher Certificate (.spc) Use signcode.exe to sign the assembly For an assembly, you sign the file containing the manifest
Assemblies
How Do You Obtain a Certificate?
Purchase one from a well known Certificate Authority (such as Verisign) Create your own
For testing purposes only Use Makecert.exe to create a X.509 certificate Use cert2spc.exe to generate an SPC from a X.509 certificate
Assemblies
Strong Names and Signcode
Strong names and signcode provide different, complimentary levels of protection You can assign a strong name or assign a signcode signature to an assembly, or both When using both, the strong name must be assigned first
Assemblies
Signcode
Specify what permissions your assembly needs
Assemblies
Deployment
Unit of deployment
One or more files, independent of packaging Self-describing via manifest and metadata Captured by compiler Policy per-application as well as per-machine Assemblies are granted permissions Methods can demand proof that a permission has been granted to entire call chain Types named relative to assembly
Versioning
Security boundary
Assemblies
Deployment
Applications are configurable units
One or more assemblies Application-specific files or data Their logical name and the application that loads them
Private version preferred to shared version Version policy can be per application
Assemblies
MSIL
Microsoft Intermediate Language
.assembly hello {} .assembly extern mscorlib {} .method static public void main() il managed { .entrypoint .maxstack 1 ldstr "Hello World from IL!" call void [mscorlib]System.Console::WriteLine(class System.String) ret }
Assemblies
MSIL
Compiled with ilasm.exe MSIL was designed for the CLR
Object-oriented (primitives are not special) Designed for the Common Type System Does not embed type information
See documentation in
\FrameworkSDK\Tool Developers Guide\docs
Agenda
What Is the CLR? Assemblies Execution Model Interoperability Security
Execution Model
Create Assembly
Source Code
Assembly
Compiler
C++, C#, VB or any .NET language
csc.exe or vbc.exe
DLL or EXE
Execution Model
Source Code
VB Compiler Assembly C# Compiler Assembly C++ Compiler Assembly
MSIL
Ngen
Native Code
Managed Code
Unmanaged Code
Execution Model
Compiling IL to Native Code
JIT compiler
Generates optimized native code Compiled when a method is first called Includes verification of IL code Install-time native code generation Used when assembly is installed on machine Reduces start-up time Native code has version checks and reverts to run-time JIT if they fail
Ngen.exe
Execution Model
Run-Time Hosts
ASP.NET Internet Explorer Shell executables More in future
Execution Model
Binding to Assemblies
An application consists of one or more assemblies. How does one assembly bind to another?
Easier software deployment, updates and removal Multiple versions of an assembly can even be used by the same application
Execution Model
Application Domains
Traditionally, processes were used to isolate applications running on the same computer
Isolates failure of one application Isolates memory Uses more resources If needed, inter-process calls can be expensive
Problems
Execution Model
Application Domains
.NET introduces Application Domains, which allow you to run multiple applications within the same process Enabled by code verification
Managed by the System.AppDomain class Common assemblies can be shared across domains or can be specific to a domain
Execution Model
Application Domains
Benefits:
Application domains are isolated Faults are isolated Individual applications can be stopped without stopping the process Can configure each application domain independently Can configure security for each domain Cross-domain calls can be done through proxies
Execution Model
Application Domains
Shared class data and native code
Thread
Process
App. Domain
(class data and native code)
App. Domain
Agenda
What Is the CLR? Assemblies Execution Model Interoperability Security
Interoperability
Cross Language
What languages?
Interoperability
Common Type System
Value types Classes Arrays Interfaces Delegates Nested types Enumerations Pointers
Interoperability
Common Type System
Members: fields, properties, methods, events
Abstract, virtual, final Literal, initialize-only Static, instance Public, private, family, assembly Newslot, override
Interoperability
Managed/Unmanaged
.NET provides interoperability mechanism to permit managed code to call into unmanaged code and vice versa Why?
Existing code works, why rewrite it? Calling Microsoft functionality not yet available as .NET assemblies
Interoperability
Managed/Unmanaged
Managed Unmanaged
C#
VB
MFC/ATL VB Delphi
MSVCRT
C++
Interoperability
Managed/Unmanaged
.NET Framework Type standard Assemblies Resilient Type safe Object based Exceptions Strong names COM/DLL Binary standard Type libraries Immutable Type unsafe Interface based HResults Guids
Interoperability
Managed/Unmanaged
.NET provides two mechanisms for interoperability between managed and unmanaged code:
Interoperability
P/Invoke
Provides access to static entry points in unmanaged DLLs Similar to:
Requires method definition with custom attribute Marshalls data across the boundary
Interoperability
P/Invoke
public class Win32API { [DllImport(User32.dll, EntryPoint=MessageBox)] public static extern Boolean MsgBox(); }
Interoperability
P/Invoke
[StructLayout(LayoutKind.Sequential)] Public struct OSInfo ( uint MajorVersion; uint MinorVersion; String VersionString; } public class Win32API { [DllImport(User32.dll)] public static extern Boolean GetVersionEx(OSInfo osi); }
Interoperability
P/Invoke
Transitions have overhead
Depending on type and size of data Isomorphic types (char, int, float, long, double, etc.) are cheap
Chunky calls as opposed to chatty
Interoperability
COM Integration
What is COM? What is the relationship between the CLR and COM?
Interoperability
What Is COM?
Application Code and data structures
Before COM, applications were completely separate entities with little or no integration
Interoperability
What Is COM?
COM provides a way for components to integrate. However, each component must provide the plumbing and objects cannot directly interact.
Interoperability
COM Integration
With the .NET Framework Common Language Runtime, components are built on a common substrate. No plumbing is needed and objects can directly interact.
Interoperability
COM Integration
Provides a bridge between .NET Framework and COM and vice versa Maintains programming model consistency on both sides Abstracts the inconsistencies between the two models
Interoperability
COM Integration
Using COM components from .NET
Use TlbImp.exe to generate an assembly (.DLL) that is a wrapper for a COM component Then just reference it, instantiate with new, call it, derive classes from it, catch exceptions, use reflection, etc. Dont have to know anything about COM The CLR creates a Runtime Callable Wrapper (RCW) that implements all the COM plumbing
Interoperability
COM Integration
Using .NET components from COM
Use RegAsm.exe to register all public classes in an assembly Can use TlbExp.exe to create a COM type library Use the component from COM just like any other COM component The CLR creates a COM Callable Wrapper (CCW) that implements the necessary COM interfaces (IUnknown, IDispatch, ITypeInfo, etc.) and marshalls data between managed and unmanaged code Use RegSvcs.exe to register .NET classes in COM+
Agenda
What Is the CLR? Assemblies Execution Model Interoperability Security
Security
Why Care?
Security
Design Goals
Provide a robust security system for partiallytrusted, mobile code Make it easy to:
Express fine-grained authorizations Extend and customize the system Perform security checks in user code
Never ask a user to make a security decision on the fly
No end-user UI!
Security
Code Verification
Code can only perform legal operations Encapsulation boundary is preserved
No buffer overruns
Security
Code Access Security
Code may require permissions to run Security policy determines what code is allowed to run
By machine
By user
Security
Code Access Security
Can specify the permissions needed by code
See permissions classes in the namespace: System.Security.Permissions Create a permission object, then call Demand()
By default, the CLR will ensure that all code in call chain has the necessary permissions
Security
Code Access Security
Security check Varying levels of trust Behavior constrained by least trustworthy component
Call Chain
Assembly A1 Assembly A2 Assembly A3 Assembly A4 G1 G2 G3 G4 P P P
Security
Code Access Security
Can override security checks
Assert() lets you and the code you call perform actions that you have permission to do, but your callers may not. Deny() lets you prevent downstream code from performing certain actions PermitOnly() is like Deny(), but you specify the only permissions the downstream code will have.
Security
Permissions
Permission and permission set
XML representation of permissions Protect resources and operations Characteristics of an assemblys identity
Identity permissions
Role-based permissions
Custom permissions
Security
Policy
Process of determining permissions to grant to code
Permissions granted to code, not user Grants are on a per-assembly basis Machine-wide, user-specific by default Further restrictions allowed on a per applicationdomain basis
Security
Policy
Each policy level is a collection of code groups
Code has identity in the runtime, just like users have identity in OS Permissions are associated with each code group In the group, get granted the related permissions
All Code
P
Publisher: Microsoft
Name: MS.Office
Zone: Internet
Site: XYZ.COM
Name: MS.Money
Site: localweb
Security
Policy
Policy levels: machine, user, application domain
user
machine
appdomain
Security
Tools
Code access security tool
caspol.exe cert2spc.exe, certmgr.exe , makecert.exe , chktrust.exe Shared Name utility: Sn.exe Global Assembly Cache utility: gacutil.exe View permissons requested by an assembly
Managing certificates
Managing assemblies
permview.exe
Conclusion
What Is the CLR? Assemblies Execution Model Interoperability Security
Resources
.NET Framework and the CLR by Jeffrey Richter http://msdn.microsoft.com/msdnmag/issues/0900/Framework /Framework.asp http://msdn.microsoft.com/msdnmag/issues/1000/Framework2 /Framework2.asp Garbage Collection by Jeffrey Richter http://msdn.microsoft.com/msdnmag/issues/1100/GCI/GCI.asp http://msdn.microsoft.com/msdnmag/issues/1200/GCI2/GCI2.asp Building, Packaging, Deploying by Jeffrey Richter http://msdn.microsoft.com/msdnmag/issues/01/02/buildapps /buildapps.asp http://msdn.microsoft.com/msdnmag/issues/01/03/buildapps2 /buildapps2.asp
Resources
Security article by Keith Brown http://msdn.microsoft.com/msdnmag/issues/01/02/CAS/CAS.asp ECMA CLI Standardization http://msdn.microsoft.com/net/ecma/ http://www.ecma.ch