Java Security, C#, .NET, and Code Contracts
Java Security
- Compiler checks program syntax and prevents:
- Violating access restrictions (e.g., accessing private methods).
- Overriding final methods.
- Type mismatch errors.
- Illegal data conversions.
- Reading uninitialized variables.
- Compilation turns
.java
files into.class
files. - Checks must be performed at the bytecode level because
.class
files can be modified.
Bytecode Structure
- Bytecode verification performs checks similar to the compiler before execution.
- Exceptions during execution:
ClassCastException
: Casting to an incompatible class.NullPointerException
: Using null objects.ArrayIndexOutOfBoundsException
: Illegal array index.StringIndexOutOfBoundsException
: Illegal string index.
Java Application Security Context
.class
files on a JVM have less access than.exe
files.- JVM executes untrusted code.
- Applets: Programs running in web browsers (now largely replaced).
- Servlets: Run on a web server within the same JVM.
- APIs: Including open-source APIs, execute within the same JVM.
Java CERT Coding Rules
- Object Orientation:
- Limit field accessibility.
- Provide copy functionality for mutable classes.
- Methods:
- Security check methods should be private or final.
- Do not increase accessibility of overridden methods.
- Ensure constructors do not call overridable methods.
- Exceptions:
- Do not suppress exceptions.
- Do not expose sensitive information in exceptions.
Security Manager
Sandbox components:
- Bytecode verifier: Static checks.
- Class loader: Loads classes on demand (once).
- Security manager: Decides resource access.
Java API security check example:
Security Manager sm = System.getSecurityManager(); if (sm != null) sm.checkRead(“file.txt”); Default implementation of a check method FilePermission perm = new FilePermission(filename, "read"); AccessController.checkPermission(perm);
Alternative Security Managers
- Absence of
SecurityManager
implies no restrictions (null check). - Different applications use specific security managers.
- Applet viewers have restrictive security managers.
- Signed applets can receive extra permissions cryptographically.
checkPermission
either returns quietly or throws aSecurityException
.- To change the security manager:
- Define a subclass of
SecurityManager
. - Override methods.
- Set the new security manager using
System.setSecurityManager(sm)
.
- Define a subclass of
Methods of Security Manager to Override
checkAccept(String host, int port)
checkAccess(Thread thread)
checkCreateClassLoader()
checkDelete(String filename)
checkRead(FileDescriptor filedescriptor)
checkWrite(FileDescriptor filedescriptor)
checkExec(String command)
checkExit(int status)
checkPropertyAccess(String key, String def)
checkSetFactory()
checkTopLevelWindow(Object window)
Introduction to C
- Keywords reused from Java in C#:
- Control flow:
if
,else
,do
,while
,for
,switch
,case
,default
,break
,continue
,try
,catch
,finally
,throw
- Operators:
.
,()
,[]
,*/%
,+-
,<
,==
,&&
,||
,=
- Primitive types:
bool
(true
,false
),byte
,char
,int
,long
,float
,double
- Classes and objects:
class
,interface
,abstract
,static
,volatile
,new
,null
,this
- Methods:
public
,private
,protected
,void
,return
- Control flow:
Keywords Changed in C
extends
,implements
become:
super
becomesbase
final
becomesreadonly
,sealed
import
becomesusing
package
becomesnamespace {...}
instanceof
becomesis
@Attribute
becomes[Annotation]
(override is C# keyword)
Hello World in C
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace Rextester
{
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Hello, world!");
}
}
}
Properties in C
Without Properties:
class C { private int x; public int getX(){ return x; } public void setX(int x){ this.x = x; } } C c = new C(); c.setX(5); int y = c.getX();
With Properties:
class C { private int x; public int X { get {return x;} set {x=value;} } } C c = new C(); c.X = 5; int y = c.X;
C# Features Where Java Caught Up
- Generics: C#
List<T>
has a!0[]
array. Java uses type erasure. - Switch with strings.
- Try-with-resources (≡ C#’s using statement).
- Enumerated types.
- Enhanced for loop (≡ C#’s foreach loop).
- Varargs (≡ C#’s params keyword).
- Static imports (≡ C#’s using extension methods).
- Lambda expressions.
- Autoboxing and autounboxing are not needed in C#.
Examples
Using statement:
using (FileStream fs = File.OpenRead(path)) using (StreamReader sr = new StreamReader(fs)) { string line; while ((line = sr.ReadLine()) != null) { Console.WriteLine(line); } }
Enum:
enum TrafficLightColour {Red, RedAmber, Green, Amber}; TrafficLightColour tlc = TrafficLightColour.Red;
Foreach loop:
string[] presidents = new string[] { “Washington”, “Jefferson”, “Lincoln”, “Roosevelt” }; foreach (string president in presidents) { Console.WriteLine(president); }
Params keyword:
public static void SumList(params int[] list)
Lambda expressions:
int[] somevalues = { 10, 20, 5, 2, 40, 1 }; int numberOfLargeValues = somevalues.Count(x => x >10);
Code Contracts
Example Program with Code Contracts:
using System.Diagnostics.Contracts; public class BankExample { public const int MAX = 1000; private int balance; public int Balance { get { return balance; } }
}[ContractInvariantMethod] private void ObjectInvariant () { Contract.Invariant(balance >= 0 && balance <= MAX); } public void Credit(int amount) { Contract.Requires(amount > 0); Contract.Requires(amount + Balance <= MAX); Contract.Ensures(balance == Contract.OldValue(balance) + amount); balance += amount; }
Methods of
Contract
:Contract.Requires(bexp)
: Precondition.Contract.Requires<TException>(bexp)
: Precondition with exception type.Contract.Ensures(bexp)
: Postcondition.Contract.EnsuresOnThrow<TException>(bexp)
: Condition for abnormal termination.Contract.Invariant(bexp)
: Invariant expression.Contract.Assert(bexp)
: Assertion.Contract.Assume(bexp)
: Assumption.- All can take an error string argument.
Contract.OldValue(var)
: Value at method start.Contract.Result()
: Return value.
Contract.ForAll
andContract.Exists
:public class Program { public static void Main(string[] args) { Console.WriteLine(Contract.ForAll(0,3,i => i > -1)); List<int> list = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; Console.WriteLine(Contract.ForAll(list, i => i > -1)); Console.WriteLine(Contract.Exists(list, i => i > -1)); } }
.NET
- Conventional Platforms:
- Platform Definition: An environment on which software is designed to run.
- Examples:
- Hardware only (embedded system).
- Hardware plus operating system.
a.out
pluscrt0.o
(startup routines) →.exe
file with machine code.- x86 series.
- Registers:
eax
,ebx
,ecx
,edx
,esi
,edi
(general purpose). esp
(stack pointer),ebp
(base pointer).- Instructions: Data movement (
mov
), arithmetic/logic (add
), control flow (jmp
,j??
).
- Registers:
Platforms Built on Top of Other Platforms
- .NET Platform:
- CLR (Common Language Runtime) based on a virtual machine.
- FCL (Foundation Class Library).
- Initially for Microsoft Windows only.
- Targeted by compilers for various languages.
- Java Platform:
- JRE (Java Runtime Environment) based on JVM (Java Virtual Machine).
- JCL (Java Class Library).
- Multi-OS and multi-hardware support ("write once run anywhere").
- Targeted by Java compilers.
- Dalvik VM / Android Runtime on Android.
- Parrot VM for Python.
Virtual Machines Languages
Original Code:
int z = x + y;
int z = x + y;
JVM Bytecode:
iload_0 iload_1 iadd istore_2
CLR’s CIL (Common Intermediate Language):
ldloc.0 ldloc.1 add stloc.2
Local variables in registers are pushed, manipulated, and popped from an operand stack.
Code is sandboxed based on origin for security.
Bytecode Verification
Compiled Java bytecode passes verification.
Modified bytecode can cause verification failures.
Example:
Original Java code:
int i = 0; if (i==0){ i=1; }
Original Bytecode:
0: iconst_0 1: istore_1 2: iload_1 3: ifne 8 6: iconst_1 7: istore_1 8: return
Altered Bytecode:
0: iconst_0 1: istore_1 2: iload_1 3: ifne 8 6: fconst_1 7: fstore_1 8: return
Stackmap indicates local variable 1 holds an integer at line 8.
Bytecode Verification Failure Output
- Error:
java.lang.VerifyError: Instruction type does not match stack map
- Reason:
Type float (current frame, locals[1]) is not assignable to integer (stack map, locals[1])
JVM and CLR Similarities
- Both use an intermediate language (CIL/bytecode).
- CIL/bytecode methods are compiled “just-in-time”.
- Can be assembled/disassembled from/to human-readable form.
- Use same types as Java/C#.
- Type-checking prevents misuse (e.g., numbers as addresses).
- Instructions specific to high-level languages.
- JVM Examples:
new
,putfield
,getfield
,invokevirtual
,ireturn
,newarray
,iaload
,iastore
,d2f
.
- JVM Examples:
- Automatic garbage collection.
- Linear heap allocation with garbage collection.
Foundation Class Library (FCL)
- Analogous to Java Class Library (JCL).
- Includes:
System.Collections
:ICollection
,IList
,IDictionary
,ArrayList
,Array
,BitArray
,Queue
,Stack
,Hashtable
,SortedList
.System.IO
:FileStream
,NetworkStream
,StreamReader
,StreamWriter
,Directory
,File
.System.Threading
System.Net
:IPAddress
,Socket
,WebRequest
,WebResponse
.System.Reflection
:FieldInfo
,MethodInfo
,ConstructorInfo
.System.Windows.Forms
:Control
,Form
.System.XML
:XMLNode
,XMLDocument
.
Assemblies
- Assemblies are program components (in Global Assembly Cache).
- Contain:
- Classes.
- Resources (e.g., images).
- Manifest (table of contents).
- Metadata.
- Bundled as
.exe
or.dll
files. - Include version numbers to prevent "DLL hell".
- Java creates
.class
files for each class (including inner classes) and packages them into.jar
files.
Cross-Language Programming
- Methods in one language can call methods (even extend classes) in another.
- Example:
C++/CLI
(system back-end),VB.NET
(user interface),F#
(concurrency). - CLI (Common Language Infrastructure) enables this.
- Common Type System (CTS): Defines type representation.
- Common Language Specification (CLS): Defines a minimal required subset.
- Virtual Execution System (VES): Implemented as CLR.
- Metadata in assembly files describes types, fields, methods, and parameters.
- Successor to
DCOM
andCORBA
.