Slashdot Mirror


Secure Programming Cookbook for C and C++

Alex Moskalyuk writes with the review below of John Viega and Matt Messier's Secure Programming Cookbook for C and C++, a book which he says is useful -- but only if you have the background to use it. Read on for the details, including Alex's alternative reading suggestions. Secure Programming Cookbook for C and C++ author John Viega, Matt Messier pages 790 publisher O'Reilly rating 8/10 reviewer Alex Moskalyuk ISBN 0596003943 summary Real-life recipes for using secure code even in the basic algorithms

The Target Audience of the Book In the foreword to this book Gene Spafford observes that there really are four types of programmers:
  1. Those who are constantly writing buggy code, no matter what,
  2. Those who can write reasonable code, given coaching and examples,
  3. Those who write good code most of the time, but who don't fully realize their limitations,
  4. Those who really understand the language, the machine architecture, software engineering, and the application area, and who can write textbook code on a regular basis.

There are, as Spafford claims, too many people in category 3 who think they belong to the category 4, and that's the primary target audience of the book. John Viega and Matt Messier co-wrote Secure Programming Cookbook for C and C++ not with the intent of proving the necessity of application security, as they mention in the foreword, but to illustrate its application. If you're reading this book, you are probably well aware of the security needs at your workplace or in your projects, and you would like to have a large library of sample code for various operations.

The book has yet another Web site, and since John Viega didn't mind a little slashdotting during the launching stage, so he probably won't mind another link to SecureProgramming.com.

The Book Itself The structure of the book will be familiar to anyone who has read an O'Reilly Cookbook before. The "cookbook" part of the text is nothing more than a collection of solutions to common problems. The code is generally of high quality and written by an expert in the field. What's more important is the discussion section following the code, which explains why things are done in a certain way, what alternatives exist, and what are the best practices in the field.

Viega and Messier have expanded the discussion session, basically doubling the content, by introducing separate Windows and Unix sections where applicable. The reader has a chance to peruse the code for both platforms as well as read separate discussion sections, which helps in navigating the content of the book.

Microsoft platform developers, though, will only be introduced to native Win32 API -- the authors chose to ignore the STL/ATL/COM/DCOM/.NET solutions on the assumption that those could be derived by someone closely familiar with the lowest-level API available from Microsoft. Even though the discussion section is quite detailed and informative for both Unix and Windows developers, the authors do not discuss the design and architecture issues behind secure programming in C and C++. That falls outside the scope of this book; besides, John Viega co-authored Building Secure Software , where a lot of attention is paid to the philosophy of secure programming as well as initial application design with security in mind.

The Contents You can view the table of contents on the O'Reilly Publishing Web site, and with the cookbook format, it's pretty much WISYWIG -- whatever the title of the subchapter is, you will be introduced to the nature of the problem, followed by C/C++ solution, followed by the discussion of the subject with occasional URLs to relevant information on the Web.

Just to sum it up, usage of encryption, message integrity checks, symmetric and public-key cryptography and secure programming get a lot of attention. With 41 recipes (Chapters 4 and 5) on symmetric encryption and 29 (Chapters 7 and 10)on PKI-related code snippets, you can get your yearly supply of Unix and MS CryptoAPI examples.

But this book is not entirely about encryption, since current security problems are rarely caused by the encryption algorithm failures. The networking and Internet-related programming issues are covered in Chapter 8 (Authentication) and Chapter 9 (Networking). In Chapter 3, those designing Web interfaces will find some useful examples of validating the input URL and checking the SQL string against injection attacks. Admittedly, such examples would serve a better purpose in Perl/PHP/ASP, however, anyone familiar with C should be able to derive their own variations of the algorithm. Chapters 1 and 2 provide a great deal of insight into operating system specifics in regards to such system security issues as environment variables, spawning child processes, revealing memory dumps, using temp files on Windows and Unix, etc.

Off-the-beaten-path chapters include information on random numbers (the chapter is available online for free) and preventing tampering with applications. The random number chapter would be interesting to both professional programmers with good math skills and beginners in the computer programming field writing their first number-guessing C++ game. Recipes on gathering entropy and access to standard Windows/Unix APIs for random number generation are of great practical use. The application tampering chapter was probably the most informative thing for me - great collection of information, rarely found in other application or network security publications. How do you protect against software piracy by using checksums? How much time should you dedicate to software protection? What is the theory behind code obfuscation? How do you hide ASCII strings in data segment? How do you detect modern debuggers? The answers to such questions are usually fragmentary and are usually considered either intellectual property of the company or belong to a 'warez' site, where the quality of sources is questionable.

Is the Book Useful? This book is a great resource for quick look-up of readily available solution (I've read it online on Safari, so I cannot vouch for the usability of the paper edition when searching for information). I've written a Master's thesis on this topic (although my actual topic was way more narrow than the scope of this book) and still found a lot of great information. If you've never seen C/C++ code or feel uncomfortable with Unix/Windows API programming, you will probably find the Cookbook overly technical. A higher-level application security text is available for those new to the subject (besides the Building Secure Software title mentioned above, there's a great title called Writing Secure Code from Microsoft), while this book gets into dirty, nitty-gritty details.

Yeah, everyone and his brother knows how to implement a symmetric encryption algorithm, but how do you actually do it without compromising the system and introducing new possible loopholes? The cookbook answers questions like that, and, as mentioned above, provides detailed overview of programming strategies for the two most popular platforms. Taking the cookbook concept further, this book teaches you how to make a basic ham-and-cheese sandwich as well as fine cuisine. Too often the code measures for basic security and preventing buffer overflows are summarized in higher-level concepts, thus allowing the developers to make errors even with the most trivial applications. If you're a professional programmer and do not get tired by looking at sometimes profuse code examples, this book would probably be a good read from the beginning to the end. If C/C++ is not your preferred area, the usefulness of this title decreases severely, however, it might serve as a good reference.

You can purchase Secure Programming Cookbook for C and C++ from bn.com. Slashdot welcomes readers' book reviews -- to see your own review here, read the book review guidelines, then visit the submission page.

159 comments

  1. $5 cheaper and free shipping by Anonymous Coward · · Score: 1, Informative
    1. Re:$5 cheaper and free shipping by RonBurk · · Score: 1

      www.overstock.com has it cheaper than amazon, even after you pay for the shipping. Dang, wish I could make some affiliate bucks from that!

    2. Re:$5 cheaper and free shipping by Anonymous Coward · · Score: 0

      You can...just sign up at www.linkshare.com

  2. Maybe they should send one copy to... by ospirata · · Score: 4, Funny

    I would send a free copy to openssl staff

    1. Re:Maybe they should send one copy to... by Anonymous Coward · · Score: 2, Funny

      Send a few thousand to microsoft, too.

    2. Re:Maybe they should send one copy to... by NivenHuH · · Score: 1, Funny

      and perhaps to valve too! (wait.. the book doesn't cover source code leaks..)

      --
      Just when you make it idiotproof, some idiot builds a better idiot.
    3. Re:Maybe they should send one copy to... by the_archivist · · Score: 1

      I think the judge should throw this book at m$ when he finds them liable for the current class action for buggy shite against m$. The penalty should be the purchase of 10 copies per m$ employee. And they should be locked up till they have read all copies. End of todays rant about m$

      --
      while(karma less_than enough_karma){karma++}
  3. Write Secure Code: a summary by bersl2 · · Score: 0

    Don't use system(), and be careful with buffers.

    1. Re:Write Secure Code: a summary by Anonymous Coward · · Score: 0

      No, don't use system() with variable arguments, or if you must use system() with arguments, carefully check those arguments.

    2. Re:Write Secure Code: a summary by quigonn · · Score: 2, Insightful

      OK, the book is exactly the right thing for you.

      --
      A monkey is doing the real work for me.
    3. Re:Write Secure Code: a summary by viega · · Score: 1

      Even without variable arguments, a bad PATH can lead to security problems...

    4. Re:Write Secure Code: a summary by Xugumad · · Score: 2, Interesting

      Other things, just what I can remember at the moment, anyone want to remind me of what I've missed:

      • Program defensively. Don't just perform the bare minimum of checks required to make your system work, perform double, triple or even more checks where feasible.
      • Remember to encode all text correctly. This is particularly important in cases such as shell commands or SQL statements. Be careful of odd examples where multi-layered encoding is required (Javascript in HTML being a good example).
      • Never use data from the user without sanity checking it. Feel free to strip characters that aren't there ("../" in a file's name, rather than path, for example).
      • When calling external programs, use their full path. Nothing's quite as annoying as some smart ass placing an identically named file higher up the search path, that executes "rm -rf /".
      • Do not assume that because you can't figure out how to crack a cryptographic method, it's secure. Get a mathmatician, or even better a cryptoanalyst, to check it for you.
      • Security through obscurity gets a bad rep. It's a hell of a lot better than nothing, but never rely on it except where necessary (passwords are a good example of where it's necessary).
  4. This book has one page, one word: by ultrabot · · Score: 2, Funny

    Don't.

    --
    Save your wrists today - switch to Dvorak
    1. Re:This book has one page, one word: by Anonymous Coward · · Score: 0

      an old college roommate had a book for men on how to deal with women in a relationship. the chapter about how to meet her parents consisted of identical text as your post.

  5. NEWSFLASH! Never before! by Anonymous Coward · · Score: 2, Funny

    Headline: Previous Knowledge Required Before Reading Technical Book

    Film at 11.

  6. Here's how to write safe C code by Anonymous Coward · · Score: 5, Funny

    int main(void)
    {
    system("python mainapp.py");
    return 0;
    }

    1. Re:Here's how to write safe C code by Anonymous Coward · · Score: 0

      If thats an example of the sort of C you write, then you probably should stick to your toy languages and leave complicated things like C to the grown ups.

    2. Re:Here's how to write safe C code by Anonymous Coward · · Score: 0

      If that is how to write safe C code, than I hate to mention that I stuck a python trojan in your path before the system version of it. You just wiped your hard drive.

      By the way, it would be more correct to say this:
      int main(void)
      {
      return(system("python mainapp.py"));
      }

      The above code would accurately report status if, for example, python were not in the user's path. Such a feature could be useful if you wished to add this to a shell script, for example, and wanted to make sure the command succeeded and exited normally.

    3. Re:Here's how to write safe C code by stevey · · Score: 1

      I hope this isn't setuid/setgid - because if it is there's a massive security hole.

      Because you don't supply absolute paths to either 'python' or the script to execute a malicious local user could set their path to /tmp, and stick a script called "python" in ther.

      Instant privilege escalation ..

    4. Re:Here's how to write safe C code by Anonymous Coward · · Score: 0

      This method lacks support for command line arguments. And system() is defined as
      int system(const char *string);
      so you should handle the return value.

      int main(void)
      {
      return system("python mainapp.py");
      }

      cu
      reiner

      p.s. not to mention some security issues
      with this implementation.

    5. Re:Here's how to write safe C code by Nucleon500 · · Score: 1

      Am I the only one amazed that a 5-line C fragment (granted, written by AC) has what could be a critical flaws? If mainapp.py fails, app.c still returns zero, so the higher context won't ever see the error. Also, the command line isn't passed to python. Picture this: "nukecontrol --disarm && launchcontrol --fire". Nukecontrol returns -1 because it needs arguments, but the missile is launched anyway.

    6. Re:Here's how to write safe C code by sward · · Score: 1

      Shouldn't that system() call be:

      system("/usr/bin/python mainapp.py")

      ...

  7. are you kidding? by geekoid · · Score: 4, Interesting

    there are too many people in catagory 1 that think they are in catagory 4.

    funny enough, if there code was a hurricane, it would be at least a catagory 4.

    --
    The Kruger Dunning explains most post on /. http://en.wikipedia.org/wiki/Dunning%E2%80%93Kruger_effect
    1. Re:are you kidding? by Anonymous Coward · · Score: 0

      And this description describes most of the M$ developers. The top ones actually make it into category 2.

    2. Re:are you kidding? by pmz · · Score: 1

      if there code was a hurricane, it would be at least a catagory 4.

      Actually, a hurricane is a pretty highly-organized weather system. I'm not sure this analogy works all the way through.

    3. Re:are you kidding? by Anonymous Coward · · Score: 0

      Umm, try:
      their
      category

      You probably consider yourself a decent Enlish writer. You are obviously in category 2, but think you are in 4.

    4. Re:are you kidding? by Anonymous Coward · · Score: 0

      program in english then you dipshit.

  8. I don't need this by deltagreen · · Score: 4, Funny
    1. Those who are constantly writing buggy code, no matter what,
    2. Those who can write reasonable code, given coaching and examples,
    3. Those who write good code most of the time, but who don't fully realize their limitations,
    4. Those who really understand the language, the machine architecture, software engineering, and the application area, and who can write textbook code on a regular basis.
    There are, as Spafford claims, too many people in category 3 who think they belong to the category 4, and that's the primary target audience of the book.

    Well, I don't need this, since I'm in category 4. Instead of reading this nonsense, I'll go finish my Visual Basic project.

    1. Re:I don't need this by Choobius+Gothicus · · Score: 2, Funny

      Is this true? Visual Basic programmers can read?

    2. Re:I don't need this by Anonymous Coward · · Score: 0

      it appears they are. it also appears they're brave enough to admit they're VB programmers on /.

  9. are you really making money with that? by Anonymous Coward · · Score: 0

    I'm just curious...

  10. Gene Spafford forgot the zeroth group by the_B0fh · · Score: 1
    #0 Those who can't write code worth crap, but keep thinking that they can.


    Too damned many of them.


    -bofh

    1. Re:Gene Spafford forgot the zeroth group by Horny+Smurf · · Score: 1

      also known as "sourceforge project leaders."

  11. what we need by Anonymous Coward · · Score: 0

    What we really need is a simple security lib that can easily be retro-fitted to the majority of applications. The application's code wouldn't have to change, as it would be "wrapped" or protected by the "security" library. ie:

    #include <sb.h>

    (void) init_secure();

    // do stuff

    (void) done_secure();

    I mean, we've put a man on the moon, but we can't make a software library with a simple interface that solves all of our problems? Puh-leeze! I think the many-eyeballed monster that is the open-source community should turn its attention to this important issue.

    1. Re:what we need by Anonymous Coward · · Score: 0

      #include <stdio.h>
      #include <sb.h>

      int main()
      {
      char buf[32];

      init_secure();

      gets(buf);

      done_secure();
      }

      Good idea!

    2. Re:what we need by fredrik70 · · Score: 1

      and how would this work? You would have to run the c code within some kind of sandbox for this to work, intepreted style. Why not just go for java or c# then.
      There's no way you can just 'add' security by a function call to a lib. c/c++ doesn't work like that.

      --
      if (!signature) { throw std::runtime_error("No sig!"); }
  12. A fifth type of programmer... by cperciva · · Score: 4, Interesting

    There is a fifth type of programmer, not covered by the categorization mentioned above: Those who really understand the language, the machine architecture, software engineering, and the application area, and who write code which is absolutely antithetical to anything you'd find in a textbook.

    I, for example, severely abuse short-circuit evaluation -- I'll often put five or more function calls into an if() conditional, ||ing their error conditions together -- but there's nothing wrong with that; you'll never find it in a textbook, but once you're used to reading that sort of code, it is more compact, easy to understand, and easy to maintain than the alternatives.

    1. Re:A fifth type of programmer... by Anonymous Coward · · Score: 1

      "I ... severely abuse short-circuit evaluation"

      I want to tattoo that on my forehead.

    2. Re:A fifth type of programmer... by Chromodromic · · Score: 1

      I agree. I'm not sure what "textbook" code means. There are plenty of textbooks out there that have, as examples, bone-chilling examples of C++ code, and a few of those are produced by O'Reilly (see "Practical C++ Programming"). In fact, a great deal of the code I see produced by other programmers is very reasonable and tight, but isn't something I would see in a textbook at all. I think it's possible that this book author has revealed a bias toward the code of book authors ...

      --
      Chr0m0Dr0m!C
    3. Re:A fifth type of programmer... by cultobill · · Score: 1

      There's nothing wrong with that!

      Unless, of course, you are thinking about code {maintenance, reusability, readability}. But real programmers don't worry about that, right?

      --
      -- Bill "Houdini" Weiss
    4. Re:A fifth type of programmer... by rvaniwaa · · Score: 4, Insightful
      I, for example, severely abuse short-circuit evaluation -- I'll often put five or more function calls into an if() conditional, ||ing their error conditions together -- but there's nothing wrong with that; you'll never find it in a textbook, but once you're used to reading that sort of code, it is more compact, easy to understand, and easy to maintain than the alternatives.

      There is nothing wrong with that as long as the persons who are going to maintain the code are also of the fifth type of programmer. Generally, the people maintaining your code are of the second type and this code is going to confuse the hell out of them

      We had a guy on our project that wrote an if statement that had three levels of embedded ?: operators along with several function calls, several of which took parameters that were generated by ?: operators with other function calls within them. There were half a dozed each of ||, && and ! along with a few |'s and &'s thrown in for good measure.

      Yes, it was the most optimal code for this situation. However, this situation did not require that level of optimization and, when I had to fix it 2 years later because of a subtle bug that could have been obvious, I was ready to ?: the guy that wrote that code!

      --
      main(i){(10-putchar(((25208>>3*(i+=3))&7)+(i ?i-4?100:65:10)))?main(i-4):i;}
    5. Re:A fifth type of programmer... by Aardpig · · Score: 1

      Isn't this fifth type usually known as a "Perl Munger"?

      --
      Tubal-Cain smokes the white owl.
    6. Re:A fifth type of programmer... by Carbonite · · Score: 1

      Yes, it was the most optimal code for this situation.

      This code may have been optimal if the only measure was lines of code but that doesn't mean it would have executed any faster. Having fewer lines of code doesn't necessarily lead to better performance. Additionally, it can (and did in this case) lead to problems maintaining the code.

      --
      ich muß mehr Kuhglocke haben
    7. Re:A fifth type of programmer... by rvaniwaa · · Score: 1
      Yes, it was the most optimal code for this situation.
      This code may have been optimal if the only measure was lines of code but that doesn't mean it would have executed any faster. Having fewer lines of code doesn't necessarily lead to better performance. Additionally, it can (and did in this case) lead to problems maintaining the code.
      Believe it or not, it actually was faster. I checked the assember after I unraveled all of the convoluted crap that he had done and the unoptimized assember was a few statements shorter. Of course, the compiler might have optimized them to the same result but we generally run the unoptimized version of the code here so we can debug in case of failure.
      --
      main(i){(10-putchar(((25208>>3*(i+=3))&7)+(i ?i-4?100:65:10)))?main(i-4):i;}
    8. Re:A fifth type of programmer... by Black+Art · · Score: 1

      I think the textbook that is being refered to here is "The Necronomicon". ]:>

      --
      "Trademarks are the heraldry of the new feudalism."
    9. Re:A fifth type of programmer... by thockin · · Score: 1
      Debugging is twice as difficult as coding. If you write the code as cleverly as you possibly can, then you are - by definition - not smart enough to debug it.


      Kernighan and Pike


      Learn it, live it.

    10. Re:A fifth type of programmer... by gbjbaanb · · Score: 1

      believe me, comparing the debug assembler is not a big deal - you either run the debug code, with its additional instructions embedded in it, stack checks etc etc, or you run nice optimised release build code.

      Comparing what the plonker wrote with the debug code is not a big deal - I think I can guarantee the release build is faster, even if the if statements were unravelled. So the compiler is better than your example programmer. In fact, if the debug version is only slightly slower than him, he hasn't exactly gained you anything at all. (a few instructions, what.. 0.001 milliseconds difference?)

      I read a while back that you shouldn't try to optimise code to such a low level - the compiler will always do a better job of it than you can. Not only that but the time saved in maintenance is significantly greater than any time saving. Also, what you think of as optimising your code is quite often not the case - you have to think of cache lines and thread contention with modern processors, not the stuff you'd do 5 years ago.

    11. Re:A fifth type of programmer... by cerberusti · · Score: 1

      I'll often put five or more function calls into an if() conditional, ||ing their error conditions together -- but there's nothing wrong with that;

      Unless of course you care about the order in which they are called. Note that the C spec says that there is a sequence point after each conditional however,
      the order in which conditionals in an || are evaluated is not defined in the standard, as in, there is no sequence point there. so in a statement such as:

      if((Do_Something())
      ||(Do_Something_Else()))
      {
      goto Label_Error_And_Exit;
      }

      The order in which Do_Something and Do_Something_Else are called is undefined, it is compltely up to the compiler.

      --
      I'm a signature virus. Please copy me to your signature so I can replicate.
    12. Re:A fifth type of programmer... by cperciva · · Score: 1

      Note that the C spec says that there is a sequence point after each conditional however,
      the order in which conditionals in an || are evaluated is not defined in the standard, as in, there is no sequence point there.


      You must have a different copy of the C standard. My copy reads "Unlike the bitwise | operator, the || operator guarantees left-to-right evaluation; there is a sequence point after the evaluation of the first operand. If the first operand compares unequal to 0, the second operand is not evaluated."

    13. Re:A fifth type of programmer... by Josh+Booth · · Score: 1

      Yeah, but isn't || defined to evaluate left to right? It is still an operator and you could do

      int main()
      {
      int n = 5 || 0;
      printf("%i\n", n);
      return 0;
      }

      which outputs, logically, "1".

    14. Re:A fifth type of programmer... by VegeBrain · · Score: 1

      Not so fast! There may not be a sequence point there but the standard explicity says the left operand of the logical OR operator is evaluated first and only if the result is zero is the right operand evaluated. The logical AND operator is similar. If the left hand expression is false, the right hand expression is never evaulated. Most operators aren't like these two; instead the order of evaluation is not specified. The logical AND and OR operators are unique in this respect.

    15. Re:A fifth type of programmer... by betis70 · · Score: 1

      >>I read a while back that you shouldn't try to optimise code to such a low level - the compiler will always do a better job of it than you can. Not only that but the time saved in maintenance is significantly greater than any time saving.

      Reminds me of Deep C Secrets. Always loved that title (esp with the 'extinct' fish on the cover).

      --
      I forget...are we at war with Eurasia or East Asia?
    16. Re:A fifth type of programmer... by EddieSam · · Score: 1

      which outputs, logically, "1".

      On your compiler, maybe. The spec only says it'll be non-zero. Another compiler might output "42" and be just as correct.

    17. Re:A fifth type of programmer... by rvaniwaa · · Score: 1
      believe me, comparing the debug assembler is not a big deal - you either run the debug code, with its additional instructions embedded in it, stack checks etc etc, or you run nice optimised release build code.

      Comparing what the plonker wrote with the debug code is not a big deal - I think I can guarantee the release build is faster

      That would be the case except the release code is generally the code with debug... It is an odd situation but, for various reasons, we run the debug code for our release.

      I do agree with most of what you say b/c the compiler is almost always smarter than the C/C++ coder. The same is not true of an experienced assembler coder but that is another story altogether.

      --
      main(i){(10-putchar(((25208>>3*(i+=3))&7)+(i ?i-4?100:65:10)))?main(i-4):i;}
    18. Re:A fifth type of programmer... by Anonymous Coward · · Score: 0

      Actually, the standard requires that boolean expressions evaluate to 1. It's just not required that boolean expressions be 1, but these are only introduced by the programmer, not the compiler. The standard also requires that null pointers compare equal to 0, but does not require that null pointers have the value of 0 (for example, if you tried to use an int as a pointer without a cast, this wouldn't necessarily work).

    19. Re:A fifth type of programmer... by Anonymous Coward · · Score: 0

      Apparently you do not know what constitutes a textbook. Here's a hint: O'Reilly doesn't sell textbooks.

    20. Re:A fifth type of programmer... by Anonymous Coward · · Score: 0

      GCC is one of the few compilers that can put debugging information into optimized code. I think most other compilers don't because compilers do funky things that make debugging optimized code tricky as anything. However, it's still good enough for things like core dumps, which is the main use for building release code with debugging information. It's dubious that your release code needs to be extensively debugged 'live', although GCC with -g -O[] will let you do that, too.

    21. Re:A fifth type of programmer... by dolo666 · · Score: 1
      "There is nothing wrong with that as long as the persons who are going to maintain the code are also of the fifth type of programmer."
      I totally agree with this. But how many of us code just for ourselves and don't care about anyone else understanding it? How many of us use programming as a method of creativity, and express our code in the very best manner known to us, and not the best manner known to the general public?

      Is it much different in a corporate setting? Same ends, yet perhaps slightly different means!

      It seems that in a corporate setting, you would want to cover your ass-ets by obfuscating everything you can, and have a key set up so that it would unlock itself if you were treated fairly, or when you leave on good terms, as opposed to what happens 99% of the time: you get screwed by the boss over money and status, and when that happens, I say fuck 'em! They get what they deserve if they can't read it/understand it/find it!!!
      Cynical, maybe. Honest? Certainly.
    22. Re:A fifth type of programmer... by Anonymous Coward · · Score: 0

      yeah, I'd rather hire the OP than Herb Schildt.

    23. Re:A fifth type of programmer... by Chromodromic · · Score: 1

      Ohhh, please educate me, you moron. As a matter of fact, you dink, I know of at least two O'Relly books that are being used as texts in classes taught at UCI. So thanks for your input, but now you may want to go and pour yourself a nice, warm glass of shut the fuck up.

      --
      Chr0m0Dr0m!C
  13. Know what? by Anonymous Coward · · Score: 0

    I'm with you 99%.

  14. my complaints with this book by Horny+Smurf · · Score: 2, Funny
    1. It was not typeset with TeX (a secure program if ever there was one!)
    2. The authors don't advocate the use of literate programming, which is proven to produce more secure code
    3. The authors use "C" and "C++", rather than focusing on concepts via a virtual machine like MIX.
    1. Re:my complaints with this book by Anonymous Coward · · Score: 0

      Viagra. The world's most disturbing drug.

  15. Hard to sell by gusmao · · Score: 4, Funny

    There are, as Spafford claims, too many people in category 3 who think they belong to the category 4, and that's the primary target audience of the book

    People who think they are in category 4 wont buy the book, because they belive they dont need it. So who is the target audience anyway? :-)

  16. Whoa there! by D0wnsp0ut · · Score: 1
    there's a great title called Writing Secure Code from Microsoft

    Is this supposed to be some kind of joke?

    --
    "Those who would sacrifice liberty for security deserve neither!"
    1. Re:Whoa there! by bloo9298 · · Score: 1

      Very funny, of course.

      But the Howard/LeBlanc is well worth a read. Viega and Messier's book is also extremely useful, and I for one am grateful that they stuck to the Win32 API.

    2. Re:Whoa there! by cant_get_a_good_nick · · Score: 1
      Jokes aside (and you stole mine, I was going to write my own version of it:

      Great oxymorons:
      • Jumbo shrimp
      • Millitary intelligencse
      • BASIC
      • Utah Jazz
      • Writing Secure Code from Microsoft

      BASIC gets a nod because it's the only single word good oxymoron I know

      Anyways, Microsoft hires some very talented guys. A lot of their problems are marketing related. "Hey, we need to ship, I don't care how much QA you've used". Or even worse "we need to get the whole world integrated, everything shares code with everything, hey lets have our email system atomatically run scripts, because no one in an office would send malicious code inhouse, right?" and thereby grow the torrent of worms. MS is a big enough company that it can be solid in theory but fall well short in practice.

    3. Re:Whoa there! by gbjbaanb · · Score: 1

      yeah, so. Its not an oxymoron really - even if they don't follow what they preach throughout the codebase.

      Check out what they say:
      http://msdn.microsoft.com/msdnmag/issues/02/ 09/sec uritytips/default.aspx

      How about this one.. integer manipulation vulnerabilities.. not just MS code at fault here either:
      http://msdn.microsoft.com/security/secure code/colu mns/default.aspx?pull=/library/en-us/dncode/html/s ecure04102003.asp

      plenty more on the MS site.

  17. Categories ... by Chromodromic · · Score: 4, Insightful

    There are 4 types of programming book authors:

    1. Those who categorize programmers artificially for the sake of a point.

    2. Those who categorize programmers incorrectly because they don't know better, but for good reason.

    3. Those who categorize programmers because they figure that, by doing so, they will establish themselves as an authority on ranges and types of programming skill.

    4. Those who avoid categorizing programmers because they realize that it's kind of goofy to do so.

    Everyone knows that there are folks out there that can do their job better than others. But do those categories really exist? It may seem like I'm picking nits, but is there really a class of programmers that writes buggy code almost all of the time? I mean, I suppose there is, but it doesn't seem to me like they'll have a long career in software ...

    --
    Chr0m0Dr0m!C
    1. Re:Categories ... by Anonymous Coward · · Score: 0

      Trust me. They do.
      I'm fixing some stupid bugs right now written by someone who has been working at this company for many years.

      They've become entrenched, and so has their code.

    2. Re:Categories ... by Anonymous Coward · · Score: 0

      Yes, it's the class of programmers employed at Indian outsourcing firms, and they seem to be getting along quite nicely.

    3. Re:Categories ... by Anonymous Coward · · Score: 0

      Yes there really are programmers who routinly break stuff and write buggy code. I can think of two former coders at my current workplace who wolk evoke groans in my fellow testers whenever we had heard they had amended a certain section of code. Invariably that code would have a major bug in it, and it would be sent back for someone else to fix.

    4. Re:Categories ... by Anonymous Coward · · Score: 0

      I'm guessing you are younger than 25.

    5. Re:Categories ... by hankaholic · · Score: 1
      I disagree. On a somewhat more technical leve, I read his four categories as something like this:

      1. Those who use gets(), and call functions like open() without checking the return value, knowing it could bite them in the ass but thinking that nobody will notice,
      2. Those who get some of the obvious stuff (like not using gets()), but often miss other things which should be known, and often opt for less elegant techniques because they haven't read/written enough code to know what better techniques are out there.
      3. Those who write good code most of the time, but who don't really understand what security entails other than checking return values and paying attention to string management,
      4. Those who really understand the language, the machine architecture, software engineering, and the application area, and who can write textbook code on a regular basis


      I think it's a reasonable way to generalize. Those in category #1 are really amateurs, and after having been smacked in the face by their mistakes will move on to category #2, or will quit altogether.

      I've seen coders develop, and there are many in category #2, who don't realize that sometimes a
      for
      is more elegant than a
      while
      , or duplicate code in both branches of a conditional. It's not major stuff, but those people would do better to parse and create more code before worrying about reading a book written for the technically-minded.

      I'm in category #3, myself. I like to use clever techniques that simplify both the execution and the appearance of code, but all of the textbook code I've seen (including CS textbooks) ignores security in order to make the concepts they discuss more clear. Many texts say something like "Here's an example. It's not secure or robust, but it's clean and easy to understand."

      However, few texts out there explain how to move from category #3 to category #4 -- how to write secure code which retains elegance and cleanliness.

      I'm unclear here -- are you just fond of complaining, or do you have a legitimate suggestion for the author to integrate into possible future editions?
      --
      Somebody get that guy an ambulance!
    6. Re:Categories ... by Captain_Chaos · · Score: 1

      ... But do those categories really exist? ...

      Yes, they do. I'm a software engineer, and I see all of them daily at my place of work. A lot of programmers just don't give a damn. They don't try to write buggy code, it's just that they can't be bothered to spend the extra energy it takes to write good (safe, maintainable, reusable, scalable) code. They're lazy and sloppy, it's very frustrating to have to work with them (especially when you have to fix their bugs) and there seem to be a lot of them.

      I like to think that I'm in category 4 myself, although of course it's more probable that I'm a category 3...

    7. Re:Categories ... by Chromodromic · · Score: 1
      I'm unclear here -- are you just fond of complaining, or do you have a legitimate suggestion for the author to integrate into possible future editions?

      I appreciated your post, with exceptions, right up to the point where you decided to be yet another geekoid asswipe, making some sneering little point while winding tape around your glasses. I reject the notion that because an author wrote a book it's our obligation here to all be constructively helping to better his work. There are enough computer books in the world, and yes in this niche too, to stretch around the world in a line a few times, so it's perfectly legitimate to question his text. Furthermore, unless you've read the book, which I haven't, you've no better idea about the quality of the content than I do. I was questioning something excerpted from the book, while you were speculating on the book's quality and relevance as a text.

      There's more to security than checking return values, validating input, and managing strings, such as knowing your APIs and understanding points of entry. But category 4 is ridiculous. Textbook code? What the fuck is textbook code? Have you seen some of the code in textbooks? A lot of it is truly NOT secure. So what the hell does he mean? Just because some guy wrote a book doesn't mean he shouldn't be questioned and it doesn't mean that we're obligated to accept jack or shit about what he has to say. That said, I'll probably check out the book, at least mull it over in the bookstore. But I won't buy it unless I think the rest of his content isn't tilted toward marketing spooge.

      In the meantime, take your little comment and shove it up your pocket-protected ass.

      --
      Chr0m0Dr0m!C
    8. Re:Categories ... by hankaholic · · Score: 1

      Hah!

      Nice response ;)

      I agree with category 4 being bull -- as I implied, and you stated, textbook code is usually about as far from secure as you can get.

      And I don't have tape around my glasses, nor do I have a pocket protector. And I definitely agree that just because some guy wrote a book doesn't mean he's not a jackass.

      At the least, the review basically sucked. I'd probably have gotten more information from a link directly to Amazon.

      --
      Somebody get that guy an ambulance!
  18. I don't think so! by Anonymous Coward · · Score: 0

    ...there's a great title called Writing Secure Code from Microsoft

    Would you ask a starving person for opinions on food?

  19. hmmmm by chef_raekwon · · Score: 1

    if there code was a hurricane,

    i hope you dont code the way you write --
    their code

    maybe you're the reason why I keep on getting those damn out of memory errors...
    calling the wrong memory reference....

    --
    We're like rats, in some experiment! -- George Costanza
    1. Re:hmmmm by Anonymous Coward · · Score: 0

      Not only that, but speculating about an imaginary situation requires the subjunctive case. It should read "if their code were a hurricane..." I don't think I want either one of you writing my documentation.

    2. Re:hmmmm by Anonymous Coward · · Score: 0

      how to spell they're... not important for software engineering.

      knowing that "calling the wrong memory reference" makes no sense... important.

    3. Re:hmmmm by Anonymous Coward · · Score: 0

      It's called the subjunctive mood, not case. :P

    4. Re:hmmmm by Anonymous Coward · · Score: 0

      I hope you don't code the way you write

  20. Alternative Review by Sir+Haxalot · · Score: 2, Informative

    Password sniffing, spoofing, buffer overflows, and denial of service: these are only a few of the attacks on today's computer systems and networks. At the root of this epidemic is poorly written, poorly tested, and insecure code that puts everyone at risk. Clearly, today's developers need help figuring out how to write code that attackers won't be able to exploit. But writing such code is surprisingly difficult.

    Secure Programming Cookbook for C and C++ is an important new resource for developers serious about writing secure code. It contains a wealth of solutions to problems faced by those who care about the security of their applications. It covers a wide range of topics, including safe initialization, access control, input validation, symmetric and public key cryptography, cryptographic hashes and MACs, authentication and key exchange, PKI, random numbers, and anti-tampering. The rich set of code samples provided in the book's more than 200 recipes will help programmers secure the C and C++ programs they write for both Unix(R) (including Linux(R)) and Windows(R) environments. Readers will learn:

    How to avoid common programming errors, such as buffer overflows, race conditions, and format string problems

    How to properly SSL-enable applications

    How to create secure channels for client-server communication without SSL

    How to integrate Public Key Infrastructure (PKI) into applications

    Best practices for using cryptography properly

    Techniques and strategies for properly validating input to programs

    How to launch programs securely

    How to use file access mechanisms properly

    Techniques for protecting applications from reverse engineering

    The book's web site supplements the book by providing a place to post new recipes, including those written in additional languages like Perl, Java, and Python. Monthly prizes will reward the best recipes submitted by readers.

    Secure Programming Cookbook for C and C++ is destined to become an essential part of any developer's library, a code companion developers will turn to again and again as they seek to protect their systems from attackers and reduce the risks they face in today's dangerous world.

    --
    I have over 70 freaks, do you?
    1. Re:Alternative Review by Anonymous Coward · · Score: 0

      Why don't you credit the source of that review?

  21. This looks like a nice text by PureFiction · · Score: 4, Interesting

    I read the sample chapter and the table of contents, and this certainly looks like a very useful book for developers.

    The random number generation chapter is excellent. Many people overlook this necessity in cryptographic applications unaware that flaws introduced by insecurely random (i.e. predictable) enrtropy sources can render the best PKI, ciphers and authentication mechanisms crippled.

    One of the reasons I tend to drool over VIA hardware is that their MiniITX EPIA systems have support for hardware entropy on the CPU via the Nehemiah core, which is also available for a wide variety of OEM/embedded applications.

    This means you can use a highly secure entropy source (/dev/hw_random in linux for example) for all of your cryptographic applications, from GPG to ssh to the linux kernel itself (IPSEC). And best of all, you never have to worry about the entropy pool blocking, or reverting to less secure PRNG like /dev/urandom. ... I wonder if this book is out on Safari yet.

    1. Re:This looks like a nice text by flok · · Score: 1

      Like the Intel i815 chipset?

      --

      www.vanheusden.com - home of Multitail, HTTPing, CoffeeSaint, EntropyBroker, rsstail, bsod, listener, nagcon, nagi
    2. Re:This looks like a nice text by PureFiction · · Score: 1

      Like the Intel i815 chipset?

      To be fair I should have mentioned the hardware entropy solutions that both Intel (i810, i815, etc) and AMD (76x boards) have available, but they are much smaller offerings in Intel and AMD's product line. Contrast this with VIA which is making the Nehemiah core a centerpiece of existing EPIA boards, like the M10k, and forthcoming boards like the M2.

    3. Re:This looks like a nice text by quigonn · · Score: 1

      You know that not even noise diodes are secure to attacks? Even a simple lighted match (i.e. heat) near such a diode can severely influence the quality of the generated random numbers.

      --
      A monkey is doing the real work for me.
    4. Re:This looks like a nice text by PureFiction · · Score: 1

      You know that not even noise diodes are secure to attacks?

      Yes, as do hardware engineers. If you read the Cryptography Research analysis of the C3 Nehemiah entropy source you can see that it is well designed, using 4 free wheeling oscillators / ring oscillators at different frequencies.

      This raw output is then fed into a second stage where "statistical whitening" is applied to ensure that the entropy is not just random, but nicely random.

      Its a pretty interesting read: check it out!

    5. Re:This looks like a nice text by Anonymous Coward · · Score: 0

      Yeah, what he said [marketing drone eye rolling commences].

  22. Useful by KentoNET · · Score: 2, Funny

    "a book which he says is useful -- but only if you have the background to use it"

    So, uhh...it's useful, but only if you can use it...

    --
    "You tried your best and failed miserably. The lesson is...never try. Heh!" -Homer
  23. Merry Xmas by theraccoon · · Score: 1

    And it's the perfect holiday gift for that special Microsoft Programmer you know and love!

  24. You know, I just might read this... by pVoid · · Score: 4, Insightful
    This is the first slashdot book review that I've seen in a long time that I'm seriously considering buying.

    I'll tell it out loud flatly, the reason is because it's not a "my system is better then your system" kind of book from what it seems. Those are the books that annoy me the most "Well, you see, you could be using ASP, but then your app would be WAAAAAY more insecure."

    On top of that, actually seeing equivalents of the same code on both system families will be a nice intro to some, including me, for equivalent APIs that we didn't know existed in other systems.

    Btw, the Secure Coding book by microsoft is really good too (very few actual API references, so it's not really microsoft platform targeted).

  25. Brain Surgery: a summary. by DAldredge · · Score: 4, Funny

    OPEN Skull, and poke around with stick.

  26. Re:SOMEONE LET THE LOONEYS OUT OF THE OUTHOUSE AGA by Eric+Ass+Raymond · · Score: 1

    Calm down, think of Hilary Rosen and tell us a) who is Bryanna, b) what does she look like and c) why would it bed to get reamed by your boss?

  27. Some good quotes from the book's author... by tcopeland · · Score: 3, Funny

    ....can be found here. My favorite:

    "You're proposing to build a box with a light on top of it. The light is supposed to go off when you carry the box into a room that has a Unicorn in it. How do you show that it works?"

    1. Re:Some good quotes from the book's author... by viega · · Score: 1

      Matt and I aren't quite that colorful, unfortunately! Spaf wrote the foreword, but the rest of the book is probably a bit more dry than if he'd written it!

    2. Re:Some good quotes from the book's author... by Anonymous Coward · · Score: 0
      <blockquote>"You're proposing to build a box with a light on top of it. The light is supposed to go off when you carry the box into a room that has a Unicorn in it. How do you show that it works?"</blockquote>
      You carry it into a room that has a Unicorn in it. If the light goes off, it's passed the first test.

      The provision of a functional Unicorn for the first test is the job of the examiner who thought up the question in the first place.

    3. Re:Some good quotes from the book's author... by tcopeland · · Score: 1

      Oops! I misread that part of the review. Thanks for the note.

  28. Buy one and read it by melted · · Score: 2, Informative

    You'll be surprised. Guess what, the guy who wrote the book really knows how to write secure code, and the book really teaches you a lot without offering many pre-cooked examples. This is a good thing. Helps you code with security in mind.

  29. I'd love to see a 5th one by Sebby · · Score: 1
    People that can write good clean code, comments, and documentation. Not too many of those around!

    --

    AC comments get piped to /dev/null
  30. The best way to write secure software is.... by slovin8 · · Score: 0

    to use the Whitespace language!

  31. For all the idiots who think you're right... by Anonymous Coward · · Score: 5, Informative

    How much does the programming language matter?
    Posted by John Viega on Mon, Sep 15, 2003 (07:59 AM) GMT

    We've now been slashdotted. After lowering the idle connection timeout from hours to minutes, we're doing fine (famous last words). The comments are full of "C sucks" rants. I thought I'd summarize a few of my thoughts on this issue.

    Yes, C and C++ have special "features" that make adding security problems easy, even for a fairly informed and careful developer. That's impossible to deny, though the book and this site do cover mitigation strategies that can make a big difference. However, people are miscalculating by assuming that just switching to another programming language is going to make a big difference. It can make a difference, but not as big of one as people are expecting. Defensive practices can offset the problem.

    We've done a few case studies on number of defects per line of code when performing code audits. C and C++ programs have averaged 4-5 security-critical defects per thousand lines of code. Java programs still average 1-2 security-critical defect per thousand lines.

    There are plenty of problems that programming languages themselves haven't fixed. And, honestly, most of those problems should be fixed at the API level. For example, it's stupid that neither OpenSSL or Microsoft supports full certificate validation by default. The programmer has to know what security checks to perform and write the code to do them manually, instead of getting "secure by default" behavior. As a result, most applications that use SSL/TLS are vulnerable to man-in-the-middle attacks. Sure, this is a problem in some common C-based libraries, but it's just as common in the SSL implementations for other languages. Other problems such as cross-site-scripting and SQL injection affect other languages far more commonly than C and C++, since those languages aren't often used in web apps.

    In C and C++, the common security problems are relatively easy to understand, and if you are diligent and take the right preventative measures, they're not so hard to avoid. In other languages, the easy/obvious problems don't apply, but as people use high-level primitives to build complex applications, they tend to introduce complex security problems (race conditions in servlets can be quite tough to identify, and still have security implications).

    In short, you aren't likely to accidentally end up with a "secure" program, no matter which programming language you use. We're currently working on a Java Secure Programming Cookbook, and are assembling a team for a PHP Secure Programming Cookbook. There's plenty of material for both books, without question. Expect both to be at least 400 pages, without even covering all of the low-level cryptographic stuff we cover in the C/C++ version.

    At the end of the day, if you're going to be diligent, then security can be reduced to a fairly minor consideration in programming language choice.

    One final note: C++ is often perceived as being more secure than C, because it has an abstracted string type. That's not really true, even ignoring the few cases where you can still overflow using C++ strings. Basically, heap overflows are far more dangerous in C++, because lots of function pointers tend to be stored on the heap, due to the way classes and exception handling is implemented (the GOT is stored on the heap even in C programs, but C++ programs tend to have function pointers coming out of the wazoo). If an attacker can overwrite one of those pointers, then it's often possible that he can replace it with a pointer to some sort of malicious payload.

    1. Re:For all the idiots who think you're right... by Troll_Kamikaze · · Score: 1

      There was another story about this same book on Slashdot a few weeks ago. I made a snide remark about the risk amplificiation inherent in writing "secure" code in C/C++ rather than a language that disallows illegal memory operations.

      John Viega took me to task, wielding the old "you can write insecure code in any language" argument. That's true, but it's beside the point. C and C++ inherently increase the risk of security problems because they don't check buffer bounds, so the program ends up with all of the security problems that would've existed in a buffer-safe langauge, plus buffer overflow vulnerabilities. Viega was dismissive of this assertion.

      I felt vindicated a couple of weeks later when Valve's Half-Life 2 source code was stolen by a cracker who initially penetrated their network via a buffer overflow.

      The bottom line is that trying to write "secure" code in C/C++ is a bad idea. Eminent programmers with massive QA support try it, and fail almost routinely.

    2. Re:For all the idiots who think you're right... by viega · · Score: 4, Insightful

      No, I said you MISSED my point. Of course it's easier to write more secure code in other languages. There are better choices than C and C++ for most tasks. What I was arguing is that if you rely on C and C++ sucking as a crutch, then your programs are going to have security vulnerabilities in other languages, too.

      That said, something like 20% of the code out there is written in C and C++ to this day, and that's not dropping off slowly. We did this book first because there's a market for it and because it's got all the low-level solutions people can use as a foundation in any language. Next up is Java...

    3. Re:For all the idiots who think you're right... by Anonymous Coward · · Score: 0
      The bottom line is that trying to write "secure" code in C/C++ is a bad idea. Eminent programmers with massive QA support try it, and fail almost routinely.

      It depends. Some people have managed to successfully write secure code in C (qmail, djbdns, postfix, vsftpd) and others haven't (sendmail, wu-ftpd). Maybe they were just more careful and security-minded.

    4. Re:For all the idiots who think you're right... by Anonymous Coward · · Score: 0

      Hmm, 20%?
      It 'feels' more like 50-80% to me.
      Do you have any URLs on this topic?

    5. Re:For all the idiots who think you're right... by viega · · Score: 1

      Not offhand. I've tried to get concrete information, and have asked various people who "should know" at various large organizations, including gov't and corporate. The answer varies widely. I think the reality is still greater than 20%, but the .NET platform (as well as VB apps not written for VB .NET) and Java definitely have significant market share as well.

    6. Re:For all the idiots who think you're right... by dvdeug · · Score: 2, Insightful

      We've done a few case studies on number of defects per line of code when performing code audits. C and C++ programs have averaged 4-5 security-critical defects per thousand lines of code. Java programs still average 1-2 security-critical defect per thousand lines.

      [...]

      At the end of the day, if you're going to be diligent, then security can be reduced to a fairly minor consideration in programming language choice.


      You can cut security-critical defects by 50%, and that's a minor consideration?!

    7. Re:For all the idiots who think you're right... by TheLink · · Score: 1

      "4-5 security defects per thousand lines vs 1-2 security defects per thousand lines."

      How many lines of C/C++ is needed compared to other languages?

      Impact of security defect is different. Often with C/C++ the attacker gets to run arbitrary code of own _creation_. With sane languages typically the only easy way to run arbitrary code is with SQL injection, or interaction with a C/C++ program. This to me is a very important difference.

      Ease of avoidance/fix is different. Seems only very few people can code securely in C/C++ (e.g. DJB. Who else?). The people screwing up badly in the other languages typically have sloppy thinking, and fixing isn't that bad. Whereas the typical C/C++ program seems to require a programmer to be near perfect+/super paranoid in order to stop attackers from running arbitrary code.

      --
    8. Re:For all the idiots who think you're right... by Anonymous Coward · · Score: 1, Insightful

      No, it /becomes/ a minor consideration after you reduce defects by 50%.

  32. WISYWIG? by Anonymous Coward · · Score: 0

    What does that stand for? What I See you What I get? I think you'll find the acronym is WYSIWYG.

  33. Number 5? by Anonymous Coward · · Score: 0

    Doesn't claiming to be a transcendent #5 type actually make you a Number 3 (almost by definition)?

  34. Secure Programming Cookbook for Java by Anonymous Coward · · Score: 0

    Damn it!
    I realy need a book on howto write buffer-overflow free Java code!

    1. Re:Secure Programming Cookbook for Java by viega · · Score: 2, Insightful

      If only buffer overflows were the only security problem in software :-( Buffer overflows only take up a few dozen pages. Over half the book is using cryptography properly in applications. The Java cookbook will deal with a lot of issues that come up in J2EE environments, as well as the things that typically go wrong other than overflows. Buffer overflows pick up a lot of publicity, partially because security-critical ones are usually easy to leverage into the ability to execute arbitrary code. Don't let that lead you to he conclusion that there are not other security risks to software that are significant.

  35. Thanks! by viega · · Score: 4, Insightful

    Thanks for the good review. A few minor points:

    1) All of the book's code is available on our web site. The web site is probably the right place to go to to get the code, just because we can update it when there are errata (and you don't have to copy it out manually if you want to use it).

    2) This is an implementation-focused book. You're right to refer to other texts for architecture, and besides my other book, the Microsoft press book you recommend and David Wheeler's free online HOWTO are both excellent (though I personally think the O'Reilly entry into that space is poor). At the same time, we do end up covering many aspects of good architecture in the discussion. Providing the context for a good implementation requires an understanding of the architectural issues, at least to some degree.

    3) We have had several people tell us that they find the book very useful for other languages as well. I think it covers a lot of low-level implementation stuff that isn't available in other books, and is useful as long as you can READ C code. If there's anything people want to see for other languages, etc., feel free to send us email suggesting it. We will have frequent updates to this web site with new content (at least monthly). Much of the content will be for other languages.

  36. can I deserialize serialized objects in MFC by Anonymous Coward · · Score: 0

    if I don't have the class headers?

  37. Secure Programming for Ruby and Intercal by __past__ · · Score: 0, Troll
    Why do people keep writing books about "C/C++", or keep referring to it as if there was such a programming language? They are two, distinct languages with radically different problems and very different styles, used mostly for very different things by disjoint programmer communities. They have less in common than Java and C#.

    And don't argue that C is a subset of C++ - is isn't. It never really was (look at the output of "printf("%d", sizeof('x'));" for a start, never mind "#include <string.h>" vs. "#include <cstring>"), and they evolved independently since. Today, C contains lots of stuff not in C++, like variable-size arrays, some fixed-sized integer types (like "32-bit integer" or "integer as large as a pointer"), the boolean types are incompatible etc.

    One would expect that people who talk about programming languages, or even write a book about them, would know what language they are talking about.

    1. Re:Secure Programming for Ruby and Intercal by viega · · Score: 2, Interesting

      We stick to a C77 subset where possible that works across both C and C++ programs. There are some C++-specific examples for C++-specific issues.

      Mostly, the security-critical problems DO overlap, unlike your statement. C++ doesn't have massive problems with stack overflows the way C does, but trades it off for big problems in heap overflows (due to leaving all those function pointers around on the stack).

      Anyway, go read the book and come up with a VALID complaint, please.

    2. Re:Secure Programming for Ruby and Intercal by sjelkjd · · Score: 1

      Looking at the table of contents, I'd mostly agree with your assessment, however...

      >> C++ doesn't have massive problems with stack overflows the way C does, but trades it off for big problems in heap overflows (due to leaving all those function pointers around on the stack).

      What?
      Are you talking about vtables of stack allocated objects? Because aside from that I don't see how a typical c++ program would have more function pointers on the stack than a typical C program. Furthermore, what does that have to do with heap overflows?

    3. Re:Secure Programming for Ruby and Intercal by Anonymous Coward · · Score: 0

      Don't see how the complaint is invalid.

      Why not just call it "Secure Programming for C" then and get rid of the (relatively) little C++ code?

      I don't buy books with such titles because I don't code in C++. I do code in C and honestly don't want to waste my time if there is a bunch of C++ specifics that I won't use. I might leaf through it first to see how specific it is, but the title is off-putting.

      But who am I, but a potential customer. I guess I don't have a valid complaint.

    4. Re:Secure Programming for Ruby and Intercal by viega · · Score: 1

      Just a typo... s/stack/heap at the end there, and it should all make sense. ,Basically, any time you can overwrite a vtable entry, you've potentially got a problem... most C++ programmers do not understand this fact.

    5. Re:Secure Programming for Ruby and Intercal by viega · · Score: 1

      Because the code is just as relevant to C++ programmers, and there's no way O'Reilly was interested in a separate version for C++. It's a market size thing. You can not care about the C++ portions and read around it easily. Look at the sample chapter... you'll see that exactly what I said is the case... it's pretty much straight C except in some rare, well-delineated places, and the C++ programmers will still be able to find it useful.

  38. Another reason to categorize by niom · · Score: 3, Insightful

    Marketing.

    People are more likely to buy a product if they think it's specifically designed for them. Those four categories serve that purpose.

    Please observe how the description of the third category has been made as broad as it can be. Basically the author is saying that the book is not targeted at you if you are the worst programmer in the world, not a programmer, or Donald Knuth. Such an asymmetric categorization can only be for marketing purposes.

    --
    -- Repeat with me: "There is no right to profits".
  39. Anyone want to chip in... by Trailer+Trash · · Score: 1

    to help me buy a copy for Microsoft?

    1. Re:Anyone want to chip in... by viega · · Score: 3, Interesting

      I sent at least one person there a free copy ;-)

      Honestly, they've got some smart people in this space, there. They've really been making a large effort, and it takes time for stuff like that to pay off, particularly when they've got dozens of millions of lines of legacy code written before their big security push. That is, while they might have started to care about security late in the game, they're currently putting forward a huge effort. I'll reserve judgment until some unspecified future date.

  40. Summary by SHEENmaster · · Score: 1

    for those of you with MCSE certification, please be advised that does not count as "Previous Knowledge."

    The same goes for "learning facilitaters" employed in the public school system.

    --
    You can't judge a book by the way it wears its hair.
  41. heh. by pb · · Score: 1

    Ever take a look at the original code for the Bourne shell, for example? It looks like... a big shell script. Why? Well, due to a *lot* of #define abuse. It's quite scary.

    --
    pb Reply or e-mail; don't vaguely moderate.
  42. Please by bluyonder · · Score: 2, Funny


    Somebody send a copy to Microsoft...

  43. Anyone know? by HBI · · Score: 1

    Is this the same Matt Messier that was/is the MudOS maintainer?

    here

    --
    HBI's Law: Frequency of calling others Nazis is directly correlated with the likelihood of the accuser being Communist.
    1. Re:Anyone know? by ulrikp · · Score: 1

      Yes it is.

      Ulrik Petersen

    2. Re:Anyone know? by HBI · · Score: 1

      Thanks Ulrik!

      --
      HBI's Law: Frequency of calling others Nazis is directly correlated with the likelihood of the accuser being Communist.
  44. Re:SOMEONE LET THE LOONEYS OUT OF THE OUTHOUSE AGA by Anonymous Coward · · Score: 0

    Post pics of the hot mommas with big sweater meat plz. :)

  45. Random Musings by cant_get_a_good_nick · · Score: 1

    This is mostly me talking out of my ass. I never really formally studied any of these topics, just some stream of consciousness stuff that I thought of last time our workplace went down from Blaster.

    I was at lunch recently with a friend who happens to work with me. We talked about the Von Neumann programming model. Any code that runs on a current processor ends up being put into a finite state Von Neumann machine. Machines have gotten so complex now, with so many services exposed, that though it's in theory still a finite deterministic state machine, it's essentially become an infinite state machine. There are too many places for things to interact, too many places for "gee, I never thought of that". Some of these are marketing related - "so how about we have IE and Visual Basic integrated into Outlook. That will be a cool feature we can sell, and there's no way that can bite us in the ass...", some are people who fit categories 1, 2, and 3.

    Language does matter, but insomuch only as a filter. A lot damage I've seen comes from Outlook running VBS. Language choice reduces some (possibly many) of the states. But it is only a filter; at some point code has to meet silicon. C/C++ gets the worst reviews because it does the least amount of filtering. Hell, not being a filter is C's core design principle. In an old non-memory protected OS (DOS, Win16, MacOS = 9) you could essentially hit anywhere that wasn't kernel memory. Modern OSes reduce the possible states somewhat by protected memory spaces; you can't trash anyone elses code because you're in your own VM space. It also reduces some damage by shutting down the app if it knows of a bad access (out of program space) but it can't eliminate all because it only has a very course idea of the app going to an unintended state (e.g. SIGSEGV, SIGBUS, SIGFPE ...).

    Other languages are more effective filters, because they were written with that in mind. Java is a much more effective filter, eliminating many states, but not all error states. Java can't prevent you from having all your code being world writeable.

    I guess one thing I'm asking is what research is there in non-Von Neumann architectures? And since we're probably not going to a post Von Neumann world any time soon, what lessons can we take from these to help secure our machines? In a more and more connected world where my fridge will eventually tell me when I'm out of milk, what can we do?

    I also think tools suck. We still live in a C and C++ dominated source world. And while the tools to help reduce that complexity and unintended states have barely advanced (how many people think machine aided code analysis means to add -W -Wall to their compiles) the complexity (think how many more lines of code are in by default in your basic Qt app vs. hello world; how many more lines of code in your OS?) and threat (EVERYTHING is connected to the Internet, everything is under 24/7 threat from some bored kid in Mozambique). Where are the tools? Why doesn't splint do C++ code? Everyone and their mom has a combo IRC client/Text editor, but some of our basic infrastructure tools are aging very ungracefully.

    Hmm, rant mode off. =)

    1. Re:Random Musings by Anonymous Coward · · Score: 0

      >>under 24/7 threat from some bored kid in Mozambique

      Doubtful considering it is the poorest country in the world last I checked. That kid would probably be more concerned with where his next meal was coming from rather than being 'bored'.

      Boredom is something mostly found in affluent societies.

    2. Re:Random Musings by cant_get_a_good_nick · · Score: 1

      Doubtful considering it is the poorest country in the world last I checked. That kid would probably be more concerned with where his next meal was coming from rather than being 'bored'.

      I don't pretend to know Mozambique enough to say that there are zero people with net access, the inclination, the time, and the skillset to create malicious code. If not, then substitute some other location. Tuvalu may be better; it has some net uinfrastructure and some cash because of the selling of the .tv TLD.

      In actuality it doesn't quite matter if it's Mozambique, or Tuvalu, or Russia, or Israel, or anywhere for that matter. It doesn't take a team of people. Slammer killed off the Internet in South Korea and disabled ATMs and some emergency services, and it one damn 376 byte UDP packet. It just takes one individual with the the time and will and connection to do it, and it may come from anywhere.

      When I was taking my digital circuits class (basicially creating stuff with discrete logic gates; NAND, XOR, stuff like that) we were introduced to the concept of Don't Care states. Basically, there were certain states of the input that we assumed would never happen, and we could cluster the known states to be more efficient as far as the number of gates. The problem was, what happened if by some reason, we did end up in a bad, assumed it would never happen but here we are state? Unsure, you kind of hope that you eventually get pushed to a valid state. You hope, but you might get some new automata that will switch from the one unexpected state to the next. We then had an assignment to push those illegitimate states back to a valid state in your state machine.

      Buffer overflows and stack smashes (though not all errors) are these "assume we know the states going in, but look here we are" states. But I don't think we can use the solution from the above example. The "push all bad states back to the wanted automata" was an example with a small number of states. You can't really do this with a general computer program; you get a large number of states so it's difficult to account for all possible bad states, and the code to push the bad states to a valid state is going to be about as large as the original code with all the same possible bugs.

      But there are techniques you can do to help the state stuff. ElectricFence does some more manipulation of the MMU to prevent overwrites. Though used as a debugging tool, it may be useful as a security tool. ProPolice and StackGuard help stop the "new automata". OpenBSD now has W^X protection on architectures that support it. Since you now can't put shell code on the stack, you now need to find it in libraries, and OpenBSD helps there too by randomizing the locations of loaded shared libraries so you can't say, find the code for system() all that easily.

      But there still is weird stuff for a system that can be assumed to be under constant attack. Why is the return value for functions on the stack where it is vulnerable to be overwritten? Systems aren't designed for security, and it goes all the way to the chip level. Palladium, or whatever they're calling it these days won't help. It only ensures that code that's initially loaded by the OS is from a known source. It doesn't prevent the unwanted states. I'm sure the RPC code that caused Blaster would have been signed under Palladium.

    3. Re:Random Musings by TheLink · · Score: 1

      Here's one from my stream of consciousness:

      Don't drink too much beer before peeing in your stream of consciousness...

      As for the talking out of ass thing... Go figure ;)

      --
  46. No fifth type of programmer... by solprovider · · Score: 1, Insightful

    Your fifth type of programmer fits in either the third or fourth category.

    3. Those who write good code most of the time, but who don't fully realize their limitations
    If you write code that is difficult to maintain for the fun of having written it, you belong in the category of those who should be limited. Let another programmer review your code before it is committed. If any line takes more than a minute to understand, he either rewrites it or passes it back.

    4. Those who really understand the language, the machine architecture, software engineering, and the application area, and who can write textbook code on a regular basis.
    Part of software engineering is knowing that code will require maintenance someday. The code is easy to understand. The code itself code be complicated, but comments make certain the next programmer knows exactly what is happening.

    severely abuse short-circuit evaluation
    It is the difference between:

    for(i=1;((x=getEmployeeNumber(i))>0)||((y= getDaysSinceRaise(x))>0)||((z=calculateRaise(y))>0 ));i++) notifyManager(x,z);

    And

    //Give raises until someone does not deserve one or an error occurs
    for(record=1;
    ((empnum=getEmployeeNumber( record))>0) //get next employee
    ||((days=getDaysSinceRaise(empnum))>0) //get number of days, errors return 0
    ||((amount=calculateRaise(empnum, days))>0)); //get amount of raise, verify it is positive number
    record++) //Next record
    notifyManager(empnum, amount); //tell the managers so they can verify before telling the employee.

    This is the same code, but the latter is more understandable.
    It is not the code that matters, it is how you use it.

    --
    I spend my life entertaining my brain.
    1. Re:No fifth type of programmer... by Anonymous Coward · · Score: 0

      This is the same code, but the latter is more understandable.

      But it's still hideous, and apparently contains several fundamental bugs. :o)

    2. Re:No fifth type of programmer... by Anonymous Coward · · Score: 0

      you want &&'s there instead of ||'s i think?

    3. Re:No fifth type of programmer... by God!+Awful+2 · · Score: 1


      This is the same code, but the latter is more understandable.

      You have got to be kidding me!!! There are many good reasons to comment code and many bad reasons. Check out the book "Code Complete" if you want a good discussion of this. The *WORST* type of comment is the kind that mindlessly repeats what any fool can see that the code does. E.g.:

      x--; // decrement x
      if (x 0) // check if x is less than 0
      return 3; // return 3 if x is less than 0.

      That is pretty much exactly what your "good" version does. (Except that the comments arbitrarily make comments about each line that could apply equally well to any of the other lines.)

      Here are some fictitious examples of good comments: /* x should never go below 0 here, but if it does, return 3, since that allows us to fail gracefully. */
      x--;
      if (x 0)
      return 3; // Implement the sanity check from section 2.8 of the RFC.
      x--;
      if (x 0)
      return 3; /* This kludge allows us to be backwards compatible with v2.50, which had a bug where the index in the datafile is sometimes
      incorrect. */
      x--;
      if (x 0)
      return 3;

      -a

  47. No, brother of the NYR center by Anonymous Coward · · Score: 0

    Mark Messier. Only he has a bit more hair and is unlikely to be forced into retirement anytime soon (unlike Mark).

  48. Is the C and C++ code correct this time? by jdennett · · Score: 1

    I bought a copy of the Building Secure Software book, and it wasn't a bad read -- but the one flaw I did see was the code examples, which had too many correctness issues to be considered secure. The first rule of writing secure code in C or C++ is to avoid reliance on undocumented behaviour. "void main" is a nonstandard extension, casting from a char* to an int* without knowing if the alignment is suitable is undefined behaviour, and so on. Unfortunately I don't have my review notes from this book with me, so I can't give all of the specific defects I found in the code snippets.

    Could this code not be reviewed by a C or C++ "expert" before publication? At least someone who can spot things that could cause a compilation failure or a core dump?

    1. Re:Is the C and C++ code correct this time? by viega · · Score: 1

      Everything in the Secure Programming Cookbook compiled without warning under gcc -Wall and the Visual Studio compiler (where appropriate) and received a reasonable amount of functionality testing. We tried pretty hard to get people to do third-party testing, but it's very hard to get people to agree to test so much code. So it's very likely that there are some functionality bugs, but as they're found, we update things on the web site. This is why when using the code, you should get the newest code base from the website and do your own functionality testing. Let us know if you do find bugs, so that we can update things...

    2. Re:Is the C and C++ code correct this time? by jdennett · · Score: 1

      Thank you for taking the time to respond. Certainly building all of the code with multiple compilers is a good step -- and a recent gcc with -ansi -Wall is a sensible choice for one of those compilers.

      It's likely that I will do an extensive technical review of the Secure Programming Cookbook at some time, and have it posted to the ACCU website (http://www.accu.org/) as well as my own website (less publicized). I'll let you know of any bugs I find.

    3. Re:Is the C and C++ code correct this time? by viega · · Score: 1

      Cool. Hey, if you've got time to do extensive reviews like that, send me an email if you're interested in helping on future books!

  49. The argument I need to hear: by pyrrho · · Score: 1

    C and C++ inherently increase the risk of security problems because they don't check buffer bounds, so the program ends up with all of the security problems that would've existed in a buffer-safe langauge, plus buffer overflow vulnerabilities.

    I want to know why the language should check for buffer bounds. I think a class system should do this. I think a class system knows (or can know) what the memory is for, or at least the pattern of it's usage, and these are assumptions you do not want to make at the language level.

    Why is your argument to use a different language, when you could easily just adopt the policy of using a particular memory management strategy, in class you write or buy.

    As far as being happy they found a buffer overflow, imagine how happy I was to find a memory leak in a java program! well, not too happy actually.

    --

    -pyrrho

  50. Sorry for the bad code by solprovider · · Score: 1

    To the ACs who noticed that they should have been &&s, not ||s, you are correct.

    About the lousy comments, you are also correct. Some of my code does look like this, because I would start by writing an English version, comment it out, and then insert code. The redundant comments get removed as time passes and the code is revised. My comments tend to focus on the business reasons, with a few to explain more complicated code or to warn about possible failures. I agree that "Code Complete" is a good book for programmers who want to move to category 4.

    I wrote the example quickly to point out that using chained "||"s in an "if" were not necessarily bad, but if it made the code difficult to understand, then it was bad. So there was no fifth category of programmer, since someone who coded this way would still fit into the first 4 categories. (A case could be made that many who program this way would be category 1.)

    About the lousy code, sorry. My first example had functions with names like "action1()", and could have done anything. There were 4 examples of code, with the last one attempting to get cute by finding a possible business use for the code. I redid the other examples to match the last version, then deleted the middle ones to save space. I had not noticed that I needed to switch from ||s to &&s to make sense. I almost never code that way, since it does make the code less understandable. Try working on code you wrote 10 years ago. You will wish it was very easy to understand. Then imagine someone else trying to work on it. I do not want the negative karma from having that other programmer curse at me.

    --
    I spend my life entertaining my brain.
  51. Transport Triggered Architecture by dubstop · · Score: 1

    what research is there in non-Von Neumann architectures?

    Take a look at TTA. Probably the coolest computer architecture ever. Processors designed to be so simple that they don't even have an instruction set. I read about this concept years ago, in Byte, but the idea has never really made it out of academia.

    IIRC, it was originally intended for massively parallel computing (possibly as a backend for Lisp programs), which it was suitable for because it increases the granularity of operations.

  52. Donny Don't by sward · · Score: 1

    Someone should write a similar book, but with recipes for what *not* to do. "Don't Do What Donny Don't Does". :)

    Oh, wait. Just go buy any book from Microsoft Press ...

  53. when you grow up... by Anonymous Coward · · Score: 0

    ...you will realize that writing beautiful, readable code takes more prowess, discipline, and skill, than writing "cleverly convoluted" code.

  54. I think you should divide category 1 like this: by RogerWilco · · Score: 1

    1) Those that are to lazy to write good code
    2) Those that are truly incompetent for the code complexity they
    currently have to develop
    3) Those that think they are in category 4 instead of category 1.
    4) Those that would be in category 2 if given the proper coaching

    --
    RogerWilco the Adventurous Janitor