Wednesday, January 20, 2016

We continue discussing the paper "Shielding applications from an untrusted cloud with Haven,” written by Andrew Baumann, Marcus Peinado, and Galen Hunt. We were discussing how Haven mitigates lago attacks from a malicious host by narrowing down the OS calls, implementing a user mode runtime and by checking the parameters and return values of calls. In the event of an attack, the shield handles incorrect host behavior by panicking. It emits a short debug message, requests the host to terminate its process, and rejects subsequent attempts to enter the enclave. The interface at the enclave boundary that checks the correctness of all operations also enables a policy/mechanism separation. The guest controls policy for virtual resources ( virtual address allocation, threads, etc.), while the host manages policy only for physical resources (e.g. memory and CPU time). This is a classic design pattern that lets the host govern the state and restricts it to resource allocation and release. Since the host is responsible only for the physical resources, attacks and surface area is significantly reduced. Besides it takes the volatility out of the host, while enabling those changes with easy to modify policies by the guest. The policies can all be dropped and reloaded  at will while the server keeps track of only its state. The server doesn't even need to keep track of the changes to the allocations because policies can be dynamically mapped to resources. The combination of policy with the mechanism complement each other for the resource management.In this case, the implementation and verification becomes even more efficient with a minimalistic interface that is expressed as Drawbridge ABI. Specifically, this interface provides the following operations:
it calls to commit, free and protect specific page,
it manages threads and signals
it performs I/O streams to access untrusted storage and network and
it is a source of system time.
Haven augments the Drawbridge  ABI with this untrusted interface and an untrusted runtime outside the enclave. This runtime creates the enclave, loads the shield and forwards calls between the enclave and the host OS.

Tuesday, January 19, 2016

We continue discussing the paper "Shielding applications from an untrusted cloud with Haven,” written by Andrew Baumann, Marcus Peinado, and Galen Hunt. Today we discuss Haven design that extends the Drawbridge. The shield module implements the Drawbridge ABI which the LibOS requires. The LibOS provides a limited subset of core OS functions.The shield module provides a user mode implementation of memory management, file system, thread synchronization . It emulates the operating system and acts as a trusted bootloader for the LibOS and the application. It mitigates lago attacks from outside the enclave. It does this by validating all parameters and results passed across a narrow interface with the untrusted runtime. For example it validates that the parameters of upcalls and the results of the downcall agree with their specification. Many OS call parameters take buffer and size and validations include the check such as the number of bytes read cannot be more than the requested size. Similarly error codes must be within an acceptable list for specific downcalls. Both hardware and software can be leveraged to perform additional validation.
#codingexercise
Given a 2D array of R rows and C columns filled with N elements such that inner walls within the array have fewer elements on either side, find the number of such walls that that have elements on both sides
Solution. The boundaries are the starting points and that too the corners followed by alternate penultimate boundary of elements until the center and then the rest .The walls of the boundary can be enumerated as vertical as to the right of the element or horizontal as below the element leaving those walls that are on the boundary the horizontal floors of the last row and the vertical floors of the last column. If a wall has elements on both sides, it is counted. The count of these walls is returned.

Monday, January 18, 2016

We continue discussing the paper "Shielding applications from an untrusted cloud with Haven,” written by Andrew Baumann, Marcus Peinado, and Galen Hunt. We were discussing sandboxing. SGX was designed to protect limited subsets of application logic. Haven makes it usable for unmodified application binaries. This was difficult because applications load code and data at runtime, dynamically allocate and change protection on virtual memory, execute arbitrary user-mode instructions including some not supported by SGX, raise and handle exceptions and use thread local storage. If the application needs to use memory, it is done via LibOS. If the application need to use unsupported instructions, they are emulated. if the application has exceptions from execution. they are validate and handled within an enclave. Haven extends the Drawbridge - a shield module below the LibOS in the enclave and an untrusted runtime outside the enclave. This design implements a shielded runtime in the enclave by calling out to the untrusted host. In fact, this design may apply to LibOS in Linux and not just windows. Both picoprocess and LibOS can be used in Linux with a similar design because the design improves what is available on both platforms for a shielded execution.
#codinginterview
There's a line of B barbers where you have to take a haircut but you are the N'th person standing in a line and the shop has just opened. Each of the barber cuts hair such that the kth barber takes exactly Mk time and doesn't take a break. Mk's are multiples of each other. Which one will cut your hair ?
Answer:
B=2 N =4
M0 = 10, M1 = 5
Answer is 1. First barber.Because at the end of ten minutes three people would have cut their hair and so the next person would go to first barber.
Similarly B= 3 N = 12, M0,..Mk = 7,7,7
Answer is 3 Third barber) Because at the end of seven minutes, three people would have cut their hair and after four iterations, the last barber would have taken the last one.
B= 3 N =8
M0 ..Mk = 4 2 1
Answer is 1 because at the end of four minutes, seven people would have cut their hair and so the next person goes to first barber.
int GetBarber(int B, int N, List<int>M)
{
assert (M.Any(x => x<= 0) == false);
int max = M.Max();
int count = 0;
foreach (int I in M) count+= max/I;
return N%count == 0 ? B : N%count;
}

Sunday, January 17, 2016

We continue discussing the paper "Shielding applications from an untrusted cloud with Haven,” written by Andrew Baumann, Marcus Peinado, and Galen Hunt. We discussed instructions with Intel SGX Today we look at the Drawbridge. It is a system that supports low-overhead sandboxing of Windows applications comprising of a picoprocess or library OS.  The picoprocess is an isolation within the hardware address space but with no access to traditional OS services. Instead it uses a narrow ABI of OS primitives using a security monitor. The LibOS is a version of Windows refactored to run as a set of libraries within the picoprocess, depending only on the ABI. It consists of lightly modified binaries for most user-mode and some kernel components of Windows, and a "user-mode kernel" that implements  the interfaces on which they depend. Together they enable sandboxing of the unmodified windows application. This is at par with VM security but with substantially lower overhead. By sandboxing, it is implied that Drawbridge protects the host from an untrusted guest. Complimentary to this Haven shields the execution of the application and LibOS from an untrusted host, thereby enabling mutual distrust between host and guest. Haven is built on instruction level isolation mechanism of Intel SGX. Let us look at how it protects the application from the malicious host OS The first of these is a class of attacks called the lago attacks.  The application makes an assumption that OS will perform correctly. The malicious OS violates this by not only resulting incorrect results from system calls but also seek to expose bugs in the application. The end result is the application crashes but further more sophisticated harm can also be done with such things as data corruption. For example, it may allocate valid but abnormally high virtual addresses., return unexpected error codes from system calls, or simply fail calls that an application naively assumes will succeed. Haven counteracts this by limiting the scope using a LibOS within the enclaveSince the LibOS is under user control, it can be arbitrarily inspected or tested online. Since the LibOS is under user control, and can be arbitrarily tested or inspected offline, it is not malicious. Second with the reduced interface, corrective techniques can be used to implement these OS primitives against a malicious host. This can be done with careful defensive coding, exhaustive validation of untrusted inputs, and encryption or integrity protection of any private data exposed to untrusted code.
#codingexercise
There is a set of sentences appearing below where the letters have been replaced with substitutes. The substitutes are one to one and onto mapped. meaning that the mappings are bidirectional between the meaningful and transformed letters. For example, we are given "a zoo" with letter replacements 'a' with 'y', 'z' with 'q' and 'o' with 'e'  yielding "y qee".  We start out with a meaningful phrase or sentence and we translate to the transformed set. If we are given the following samples, write code to translate any given transformed string.
 ejp mysljylc kd kxveddknmc re jsicpdrysi
rbcpc ypc rtcsra dkh wyfrepkym veddknkmkrkcd
de kr kd eoya kw aej tysr re ujdr lkgc jv
Case #1: our language is impossible to understand
Case #2: there are twenty six factorial possibilities
Case #3: so it is okay if you want to just give up
void Train(string transforms, string actual, ref Hashtable<char, char> h)
{
for (int I = 0; I < transforms.length; i++)
{
  if (transforms[I] != " " && h.ContainsKey(transforms[I]) == false))
 {
           h.Add(transforms[I], actual[I]);
 }
}
}
// q and z may still be missing from Hashtable

string Test(string candidate, ref Hashtable<char, char>h)
{
if (h.Count() != 26)
{
foreach (char c in "abcdefghijklmnopqrstuvwxyz")
{
if (h.ContainsKey(c) == false)
   h.Add(c, "_");
}
}
var ret = new stringbuilder(candidate);
for (int I = 0; I < candidate.length; i++)
{
  if (candidate[I] != " ")
 {
           ret[I] = h[candidate[I]];
}
return ret.ToString();
}

Saturday, January 16, 2016

We continue discussing the paper "Shielding applications from an untrusted cloud with Haven,” written by Andrew Baumann, Marcus Peinado, and Galen Hunt. We discussed enclave entry and exit with Intel SGX. We continue with another instruction ERESUME. This comes in useful when there's an exception. Consider the usual working of the OS when an exception occurs. The state of the registers would be saved for later use. When the exception occurs, the context and exception records are created. In Haven, we cannot trust the OS with register state, so the SGX saves the full context and information about the cause of the exit in the thread control structure (TCS) and replaces it with a synthetic context. When the enclave is resumed on the TCS, this entry point must be different from the usual entry and hence the instruction ERESUME is used which restores the last saved context. Alternatively, the OS can re-enter the enclave and this is an opportunity for the OS to inspect and modify its own state. If it doesn't match, an exception can be reported and the enclave must handle it which in this case could be the panic response. SGX is an imperfect implementation of shielded execution. If the OS can see the internal state of the enclave such as the exception vector or in the case of a page fault, the type of access and the base address of the page. It allows the OS to retain control over the resource management i.e CPU time and memory. It can deny service to the enclave but cannot cause it to execute incorrectly. SGX does not allow enclave pages to be added after creation nor EPC permissions changed
We now review dynamic memory allocation. Initially SGX did not allow pages to be added or permissions to be modified. This was limiting for the unmodified applications. Consider the database server as an example that reserves several pages. In SGXv2, there is a co-operative mode between the OS and the enclave by which enclave pages can be added or removed and their permissions modified.
SGX includes additional instructions such as EMODT, EMODPR, EBLOCK, ETRACK and EACCEPT to enable this.
The shield module in Haven works with Drawbridge which is a system supporting low-overhead sandboxing of Windows applications. Drawbridge consists of two core mechanisms, both of which Haven leverages, the pico process and the library OS.  The picoprocess is a secure isolation container constructed from a hardware address space. It does not interact with the OS services or system call. Instead it uses an ABI of a few down calls(40) and even fewer up calls(3).
#codingexercise
An alien language consists of words where every word consists L lowercase letters  and there are exactly D words in the language. However, the letters comprising  the words may have signal loss so we can only represent them as (ab)d(dc) for the L tokens where ab means either a or b and dc means either d or c. and the pattern stands for add, adc, bdd, bdc
We are given L as 3 and D as the following: ["abc", "bca", "dac", "dbc", "cba"]
(ab)(bc)(ca)
int GetCountOfMatchingWords(string pattern, List<string> D, int L)
{
var parts = pattern.split(new char[] {"(", ")"});
var tokens = new List<string>(parts);
tokens = tokens.Where(s => !string.IsNullOrWhitespace(s)).ToList();
assert (token.Count == L);
var results = new List<string> ();
Stringbuilder b;
Combine(tokens, ref results, D, b, 0,0);
return results.Count();
}

Void Combine (List<string> tokens, ref List<string> results, List<string> D, StringBuilder b, int part, int level) 
{ 
   For (int i  = start; i < tokens.Counti++) 
{
    for (int j = 0; j < tokens[i].Count; j++)
   {  
       If (b.Length == tokens.Count) { if (D.Contains(b)) {results.Add(b);} }
       b[level] = tokens[i][j]; 
       If (I < tokens.Count) 
            Combine(tokens, ref results, D,b, start+1,level+1);
       B[level] = ‘/0’; 
   }
}
} 

Friday, January 15, 2016

We continue discussing the paper "Shielding applications from an untrusted cloud with Haven,” written by Andrew Baumann, Marcus Peinado, and Galen Hunt. We were discussing the Intel SGX. SGX protects the confidentiality and integrity of pages in an enclave.  The pages are allocated by the OS but must occupy a specific region of physical memory: the enclave page cache.  Just like the RAM backing it, EPC is a limited resource. Therefore SGX enables OS to virtualize EPC by paging its contents to other storage. While this might be considered risky, the contents of the evicted page are actually written to an encrypted buffer. The OS may relocate this but the hardware keeps a version number for that page and requires the OS to follow a hardware verified protocol to ensure that TLB shootdown has completed.
SGX supports  CPU based attestation by which a remote system can establish shared secrets that allows it to set up an end to end encrypted channel with the enclave. When the enclave is created,  a secure hash known as a 'measurement' is established of the enclave's initial state. The enclave may later retrieve a report signed by the processor that proves its identity to and communicates a unique value (such as a publickey) with another local enclave. Using a trusted quoting enclave, this mechanism can be leveraged to obtain an attestation known as a quote  which proves to the remote system that the report comes from an enclave running on a genuine SGX implementation.
SGX therefore protects the contents and integrity of the memory mappings. SGX also mediates transitions into and out of the enclave using a thread control structure When user code begins executing an enclave, it invokes EENTER on an idle TCS at which point the enclave code might access enclave pages according to the protection model above. This continues in the enclave mode until the user code explicitly leaves by invoking EEXIT or an exception or interrupt returns control to the OS  which is called an asynchronous exit EENTER and EEXIT mark explicit access and they make sure the inputs are validated and there's proper cleanup of registers.
#coding exercise
You are given a store credit of N dollars and a list of prices of different items the store sells. Find the positions of two items on that list that add up to N assuming that there will be a solution in that list.
void printSelections(List<int> prices)
{
var wantedpair = new Hashtable<int, int>();

for (int i = 0; i < prices.Count(); i++)
{
   if (wantedpair.ContainsKey(prices[I])){
          Console.WriteLine("Items at {0} and {1} total N in price", wantedpair[prices[i]], i);
          return;
   }else{
    wantedpair.Add(N-prices[I], I);
   }
}
}
 

Thursday, January 14, 2016

#coding exercise
You are given a store credit of N dollars and a list of prices of different items the store sells. Find the positions of two items on that list that add up to N assuming that there will be a solution in that list.
void printSelections(List<int> prices)
{
for (int i = 0; i < prices.Count(); i++)
{
for (int j =0; j < prices.Count(); j++)
{
   if (i != j && prices [i] + prices[j] == N){
          Console.WriteLine("Items at {0} and {1} total N in price", prices[i], prices[j]);
       return;
   }
}
}
}

We continue discussing the paper "Shielding applications from an untrusted cloud with Haven,” written by Andrew Baumann, Marcus Peinado, and Galen Hunt.
We discuss Intel SGX now. SGX protects the confidentiality and integrity of pages in an enclave which is a region of user mode address space. when it is cache-resident,  enclave data is protected by CPU access controls - the TLB but when it is written to memory, it is encrypted and if the data is modified, it will fail to load signaling a fault.
When the enclave is setup, the page mappings are done by SGX and a shadow state for each page is maintained. Enclaves are created by an ECREATE instruction which initializes a control structure in protected memory. Once an enclave is create, pages of memory are added with an EADD instruction. The pages continue to be allocated by the OS but they must occupy a specific region of physical memory - the enclave page cache.  For each EPC page, the hardware tracks its type, the enclave to which it is mapped, the virtual address within the enclave, and permissions (read, write and execute). On each enclave page access, after walking the page table, SGX ensures that the processor is in enclave mode, the page belongs to EPC and is correctly typed, the current enclave maps the page at the accessed virtual address space and the access agrees with the page permissions.