Layered Protection
I was watching Herb Sutter’s talk on the changes to C++. At one point in his slides, he showed this piece of code.
auto f1(){
char a[] = {'s', 'e', 'c', 'r', 'e', 't'};
}
auto f2(){
char a[6]; // or std::array<char, 6>
print(a);
}
int main(){
f1();
f2();
}
It reminded me of the fact that a lot of programmers these days wouldn't be able to see the issue here. Those working with high-level programming languages like Python, or garbage collected languages like C# or Java, might not even see a potential vulnerability.
For such programmers, there are two gaps here. The first one, is how the memory is allocated and deallocated by the operating system. The second, related, but a not directly relevant here, is the difference between stack versus heap allocation.
In this program, when the first function is called, it first creates an array with "secret" on it. Then, when the second function is called, Herb points out that in older C++ versions you might see "secret" rather than random values.
This is because, when the first function goes out of scope, the reference to the location is removed, but not the actual values themselves. So, there is a high chance that the new array is assigned the start pointer at the same location, thus, "leaking" the secret.
It reminded me of why, operating systems control allocation, and de-allocation of memories. In this code, the code itself is insecure by its nature. Thus, even if the code itself leaks its own secrets, no other program can access it. The memory allocated to the program is "guarded" by the operating systems.
An improvement to the C++ standard, and better compilers, can help us avoid such vulnerabilities. It reminds me of the quote in cyber-security, "security in layers". To make the system secure at each layers. The program, the compiler, the operating system.
What happens if the operating system itself has a bug. If a program is vulnerable to the way the program is compiled and assigned memory it would mean that the operating system itself would not be immune to it. And, if OS was a layer there is another layer below — the actual machine code that is run on the processors. If you know about the Meltdown and Spectre exploits, then you know what I am talking about.
So, at each layer we are vulnerable to the design of the program itself. All we can do is try our best to secure each layer, and if we are successful, our system is a bit more secure.