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.

11 of 159 comments (clear)

  1. 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
  2. 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).

  3. 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;}
  4. 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.

  5. 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.

  6. 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".
  7. 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...

  8. 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.
  9. 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?!

  10. 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.
  11. 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%.