A Permanent Javascript Program

Javascript programs are almost always used in webpages. So to store a Javascript program permanently and run it when we want it, we need to embed our program in a web page — for us it'll be the simplest of webpages. Use Notepad (or any other text editor) to produce the text file ex0.html shown below:

ex0.html
<html>
<body>
<script type="text/javascript">
// This program converts Fahrenheit to Celsius
var fromTemp = 0;
var toTemp = 0;
fromTemp = prompt("Enter temperature in Fahrenheit.");
toTemp = (fromTemp - 32)*5/9;
alert(fromTemp + " degrees Fahrenheit is " + toTemp + " degrees celsius");
</script>
</body>
</html>
The important thing to notice is that all we really need to do is take the javascript program and surround it by:
<html>
<body>
<script type="text/javascript">

</script>
</body>
</html>
In fact, that's all we ever really have to do.

Truly there's nothing new under the sun. If you look at the URL bar in chrome after you've opened the file, you see file:// followed by ... the full path to your file. In fact, you could type that into the URL and skip the control-o thing!
To run our script, all we need to do is open up ex0.html in the browser. For the remainder of this lesson, let's use google-chrome to run scripts (although any browser will do). As we'll see, it has some nice features. To open the file in google chrome, press control-o and browse to ex0.html. When chrome opens the file, it'll run the program, and the prompt and alert windows will pop up. Press refresh to run the program again. You can edit the file, save your changes, and hit refresh to run the modified program. Try it: try changing "is" to "equals" in the output, for example.

Software Runs the World: How Scared Should We Be That So Much of It Is So Bad?
Fixing bugs is not a fun sexy topic, and it can be hard to do. Carefully writing code to minimize bugs and exhaustively testing code to discover bugs before software is released is even harder, and less fun. Often, even very large companies produce software riddled with bugs. This Atlantic Monthly article talks about the catastrophic impact of badly written software in the financial sector.

Debugging with Google Chrome's Developer Tools

In an ideal world, every program I wrote or modified would work perfectly from the very start. However, it never works that way for me, and it probably won't for you either. I make mistakes, or in proper computer terms, my programs have "bugs". Let's see what happens if we purposely introduce a bug. Modify ex0.html by replacing
toTemp = (fromTemp - 32)*5/9;
with
toTemp = (fromTemp -* 32)*5/9;
which will, of course, cause problems. Now refresh chrome, and what happens? A whole lotta nothing! Nothing happened, which means that there's a problem, but we're not given much of a clue as to where the problem lies!

The reason I'm asking you to use chrome for this exercise is that it has a nice Javascript debugger built in. Click on the wrench icon in the top right corner and choose Tools / Developer Tools from the resulting menu and submenu. Click on the Console tab and chrome's debugger tells you what the error is and where! Moreover, if you click on the linked line number, it'll show you the Javascript code and precisely where the error is. This kind of error, i.e. when the browser won't even try running your program because it has some kind of structural problem, is called a syntax error.

Go ahead and fix ex0.html by taking out the spurious *, and save. Now when you refresh, the program will run normally. Assuming you still have Developer Tools open, choose the Sources tab, click on the triangle in the upper-left corner of the tab window, select ex0.html, and click on the line number 8, the line you just fixed, in the source code that pops up. You should see a blue arrow at that line number. Now refresh the page. The program will start, but stop executing at exactly that line. You've added what's called a breakpoint. If you click on the console button you'll pop up a Javascript interpreter. You can type expressions using the existing variables and find out their values. In fact, you can enter any Javascript you want here! This can be a very helpful tool when your program doesn't do what you want. By clicking the Step over next function call button , you can continue on in your program a statement at a time.

if statements

Suppose we want to add on to ex0.html. Suppose we want to let the user enter either F or C as units and then convert to the other unit. We might start off like this:
// This program converts between Fahrenheit and Celsius
var fromTemp =  prompt('Enter temperature');
var fromUnits = prompt('Enter units');
var toTemp;
var toUnits;
The problem is, what we do next depends on whether fromUnits is "C" or "F". We can test whether fromUnits is "F" using the ==, which returns true if what's on its left and right are equal, and false otherwise. So, fromUnits == "F" is true if and only if fromUnits is "F". Next we need a way to say "if this thing is true do one thing, else the other thing". There is a special kind of statement, the if statement that does exactly that:
Every programming language has an "if" construct. In Javascript, as with most others, you can drop the "else" and its block if you want to. The { }'s are optional, by the way, if there is exactly one statement in the block. Don't make use of this!
if (fromUnits == "F")
{
  toTemp = (fromTemp - 32)*5/9;
  toUnits = "C";
}
else
{
  toTemp = fromTemp*9/5 + 32;
  toUnits = "F"
}
The { }'s demarcate what are called blocks. You can stick as many statements in the block as you like — including other if-statements! Now we can finish off the whole program!

The power of the if statement is well understood, and having the ability for operators to define system behavior through the use of programming languages is a key part of adaptable and configurable systems. One of the key strengths of the Aegis Combat System is the ability for operators to define system behavior through if statements. Operators use if statements to identify threats, alert operators to take action, and control engagements.
ex1.html
<html>
<body>
<script type="text/javascript">
// This program converts between Fahrenheit and Celsius
var fromTemp =  prompt('Enter temperature');
var fromUnits = prompt('Enter units');
var toTemp;
var toUnits;

// Do the conversion
if (fromUnits == "F")
{
  toTemp = (fromTemp - 32)*5/9;
  toUnits = "C";
}
else
{
  toTemp = fromTemp*9/5 + 32;
  toUnits = "F"
}

// Display result
alert(fromTemp + fromUnits + " = " + toTemp + toUnits);
</script>
</body>
</html>

Modify this program so that units in the answer are written out in their full names: Celsius and Fahrenheit.

Comparison Operators: ==, !=, <, >, <=, >=

The == is an example of a comparison operator. It means "equals", and its cousin != means "does not equal". These operators work with any two values, regardless of their type, and more or less do what you'd expect. Note, however, that automatic type conversions take place before the comparison, so 0 == "0" gives true.

The other comparison operators are: < ← less than, > ← greater than, <= ← less than or equal to, and >= ← greater than or equal to. On numbers they operate just like you'd expect. Perhaps surprisingly, they also operate on strings. If variables foo and bar contain strings, foo < bar is true if and only if the string foo comes before bar in alphabetical order. The same logic goes for the other operators. So, for example:

"ab" < "ba"
→ true
"ab" < "ac"
→ true
"ab" < "aa"
→ false
"ab" > "ab"
→ false
"ab" >= "ab"
→ true

The typeof a comparison expression is Boolean, i.e. true or false.

A simple Guess a number game

The following program uses comparison and if's to implement a simple "guess a number" game.
ex2.html
<html>
<body>
<script type="text/javascript">
// This program compares input values
var inputNum =  prompt('Enter a number');
var specialNum = 4;

// Do the comparison
if (inputNum < specialNum)
{
  alert("You guessed too low.");
}
else if (inputNum > specialNum)
{
    alert("You guessed too high.");
}
else
{
    alert("You are a winner!");
}
</script>
</body>
</html>
If you enter 2, it outputs "You guessed too low." If you enter 7, it outputs "You guessed too high." If you enter 4, it outputs "You are a winner!". Here's an interesting question: what if you enter something like hello, something that isn't even a number? Turns out that comparing a string like "hello", which cannot be interpreted as a number, with an actual number using <, >, <=, or >= always produces false. If you trace through the code, you'll see that this means the program will consider you a winner! That's a problem.

It's very hard to write programs that deal gracefully with unanticipated input. The author of the above program didn't anticipate that some user might not enter a number, so he didn't make sure the program would do something sensible in that case. Many security problems boil down to exactly this: an attacker presents a program with strange input that the programmer didn't anticipate and which, as a result, the program doesn't handle safely. In this example it allowed an attacker to win a game without actually guessing the right number. In many cases the consequences of similar bugs have been a lot greater.

We can fix this particular problem with the program, but it makes the program more complicated. Here's one possibility. It makes use of the fact that if s is a string that can't be reasonably interpreted as a number, Number(s) returns a special value NaN, which means "not a number". The isNaN( ) function allows us to test whether an object is in fact NaN.
// This program compares input values
var inputNum =  prompt('Enter a number');
var specialNum = 4;

if (isNaN(Number(inputNum)))
{
  alert("Enter a number, doofus, not '" + inputNum + "'!");
}
else
{
  // Do the comparison
  if (inputNum < specialNum)
  {
    alert("You guessed too low.");
  }
  else
  {
    if (inputNum > specialNum)
    {
      alert("You guessed too high.");
    }
    else
    {
      alert("You are a winner!");
    }
  }

Boolean operators: &&, ||, !

Suppose we want to modify our temperature conversion program so that it assumes the fromTemp is in Fahrenheit if the user enters "F" or "f" as units. We need a way to express "or". Javascript has boolean operators, i.e. operators that operate on values of type Boolean. They are Using ||, we can rewrite the "if" from ex0.html as
It's a common mistake to write the expression
fromUnits == "F" || "f"
. This doesn't do at all what you think. You see, you'd be asking for the || of two strings, not two booleans, and what that would mean is something we haven't talked about ... and won't!
if (fromUnits == "F" || fromUnits == "f")
{
  toTemp = (fromTemp - 32)*5/9;
  toUnits = "C";
}
else
{
  toTemp = fromT*9/5 + 32;
  toUnits = "F"
}

Question: suppose you had a variable x. How would you test whether 0 ≤ x ≤ 1? click for answer.

Dealing with Unexpected Input

a weird answer isn't a security flaw, but a somewhat more complex program is needed to show how the same idea can lead to real security problems. We'll get there!
One of the most common kind of security flaw is that programs expect users to behave responsibly, or at least rationally. When users out of inattentiveness, or malice don't do what the program expects, bad things happen. Here are two simple examples of programs that give weird answers when the user inputs something unexpected.

Directionsex3.html
  1. Create a the file ex3.html as shown the right.
  2. Run the program with some reasonable numbers and make sure it works
  3. Run it with 0 for gallons used. What happened? What's the problem?
  4. Modify the program so that an error message is displayed if either the miles of the gallons are zero or negative. Otherwise, the program should display the mpg as it already does.
Now you've fixed the program so that it behaves well for any input, right? Well ... what if the user enters a string that isn't a number? Or nothing? If you want to go that extra mile, try
Number(miles)
If it gives NaN, the user didn't enter a proper number. Except that Number("") = 0, so you have to check that specially. Whew! Can you see why so many programs fail to check for every possible kind of bad input!
<html>
<body>
<script type="text/javascript">
// Get miles and gallons from user
var miles = prompt("Enter miles travelled");        
var gallons = prompt("Enter gallons used");

// Compute mpg
var mpg = miles/gallons;

// Display result
alert("mpg = " + mpg);
</script>
</body>
</html>

Directionsex4.html
  1. Create a the file ex4.html as shown the right.
  2. Run the program with some reasonable numbers and make sure it works
  3. What happens if you enter 133? 13? 0? Nothing?
  4. Modify the program so that it gives an error message if the user enters something that is not the ASCII value of a printable character.
Now you've completely fixed the program, right?
<html>
<body>
<script type="text/javascript">
// Get ASCII value from user
var a = prompt("Enter ASCII number");

// Get the letter from the number
var s = String.fromCharCode(a);

// Display result
alert("ASCII value " + a + " gives character '" + s + "'");
</script>
</body>
</html>

Security Evaluation of IT Products


DoD Instruction 8500.2 states that any information technology products to be used on systems with classified data must be evaluated using an international standard of security evaluation called Common Criteria (CC). These evaluations could take up to 2 years and may cost hundreds of thousands of dollars. Once the evaluation is complete, the product is not guaranteed to be secure. It is merely evaluated using expected criteria.