RU beehive logo ITEC dept promo banner
ITEC 380
2020spring
ibarland

immutable data
pros and cons

In the course of writing our videogame, we (hopefully) learned:

Immutable data: disadvantages

Compare move-truck with an imperative version that just re-assigns to a field. This requires much more memory (allocate a whole new truck), and more time (we have to copy all the fields over, rather than just assign to one field). For a struct with 20 fields, this is a slowdown of perhaps 20x, plus more time for memory allocation and garbage collection.

Certainly, this seems expensive, but a we can also make the following observations:

Immutable data: advantages

Secure Programming

Mutability can become a security hole. (We'll assume we're using Java, for the moment.) Imagine the following:

In an operating system, you certainly want to know who all your users are — String[] usernames = { ... };. And of course you wouldn't make this a public-field/variable, because you don't want other code to assign to it! But you may want to let other people know all the users, so it might be plausible that you'd include a getter, String[] getUsernames() { return usernames; }.

What's the problem? Aliasing + Mutability! An attacker can go ahead:

      String[] theUsers = getUsernames();
      getUserNames[2] = "hax0r";
    
at this point, the OS now thinks that hax0r is a known, registered user — oops!
Secure Programming principle: Don't give references to your own data-structures, to untrusted code! Instead, make a copy.
So we'll change our function to be String[] getUsernames() { return Arrays.copy(usernames); }. Now an attacker can get a copy of the array, and if they assign into the array that's fine, they're only assigning to their own copy.

But our problems may not be over yet! If we are in a language like C (or many others), strings are mutable. So an attacker can still weasel their way into the system's trust:

      String[] theUsers = getUsernames();
      getUserNames[2][0] = 'h';
      getUserNames[2][1] = 'a';
      getUserNames[2][2] = 'x';
      getUserNames[2][3] = '0';
      getUserNames[2][4] = 'r';
      getUserNames[2][5] = '\0';
    
Secure Programming principle, cont.: Remember to make a deep copy!
Note that Java is not susceptible to this latter attack. Why not? Java's Strings are immutable!


logo for creative commons by-attribution license
This page licensed CC-BY 4.0 Ian Barland
Page last generated
Please mail any suggestions
(incl. typos, broken links)
to ibarlandradford.edu
Rendered by Racket.