简体   繁体   中英

Defending classes with 'magic numbers'

A few months ago I read a book on security practices, and it suggested the following method for protecting our classes from overwriting with eg overflows etc.:

  • first define a magic number and a fixed-size array (can be a simple integer too)
  • use that array containing the magic number, and place one at the top, and one at the bottom of our class
  • a function compares these numbers, and if they are equal , and equal to the static variable, the class is ok , return true, else it is corrupt , and return false.
  • place this function at the start of every other class method, so this will check the validity of the class on function calls
  • it is important to place this array at the start and the end of the class

At least this is as I remember it. I'm coding a file encryptor for learning purposes , and I'm trying to make this code exception safe.

So, in which scenarios is it useful, and when should I use this method, or is this something totally useless to count on? Does it depend on the compiler or OS?

PS: I forgot the name of the book mentioned in this post, so I cannot check it again, if anyone of you know which one was it please tell me.

What you're describing sounds a Canary , but within your program, as opposed to the compiler. This is usually on by default when using gcc or g++ (plus a few other buffer overflow countermeasures).

If you're doing mutable operations on your class and you want to make sure you don't have side effects, I don't know if having a magic number is very useful. Why rely on a homebrew validity check when there are mothods out there that are more likely to be successful?

Checksums: I think it'd be more useful for you to hash the unencrypted text and add that to the end of the encrypted file. When decrypting, remove the hash and compare the hash(decrypted text) with what it should be.

I think most, if not all, widely used encryptors/decryptors store some sort of checksum in order to verify that the data has not changed.

This type of a canary will partially protect you against a very specific type of overflow attack. You can make it a little more robust by randomizing the canary value every time you run the program.

If you're worried about buffer overflow attacks (and you should be if you are ever parsing user input), then go ahead and do this. It probably doesn't cost too much in speed to check your canaries every time. There will always be other ways to attack your program, and there might even be careful buffer overflow attacks that get around your canary, but it's a cheap measure to take so it might be worth adding to your classes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM