Thursday, September 19, 2019

HTTP Request Security

Today I learned some very important security implications of how HTTP requests are formed, and how authentication data is handled.  It started with this article: https://thehackernews.com/2019/09/phpmyadmin-csrf-exploit.html


In a nutshell, phpMyAdmin, the primary management tool for MySQL and MariaDB databases, has a serious security flaw that allows attackers to delete entire DB servers with a trivial exploit.  It works like this: A webpage is setup with a link or even just a tag that attempts to load an external resource.  (The example in the article is an img tag.)  If a browser with an open phpMyAdmin session loads the page (in the case of automatically loading the resource) or someone using that browser clicks the link, a command will be sent to the DB to delete the server.  It's that simple.

This exploit relies on several vulnerabilities.  One vulnerability is that phpMyAdmin uses the same default URL on all systems, and almost no one changes it.  This allows an attacker to craft a URL that will work on nearly 100% of phpMyAdmin instances.  This is more a problem with the database administrators using phpMyAdmin than the software itself.

The second vulnerability is that phpMyAdmin does not check the referrer field of the HTTP request.  If it did that, it would be able to easily weed out HTTP requests that didn't come from the phpMyAdmin instance that is currently open.  This would make the exploit significantly more difficult, as spoofing the referrer is not something that can generally be done remotely.  The victim of the attack would have to instruct the browser to send inaccurate referrer information for this to be circumvented, though security flaws in browsers might still allow exceptions.  This is the obvious mitigation point, but it is not the end of the road.  There is an even more fundamental vulnerability here, which does not seem to be widely known, even in the security field.

The third vulnerability is the use of the GET method in handing the request to delete the server.  At this point, we actually need to look at the code used for this exploit.

http://server/phpmyadmin/setup/index.php?page=server&mode=remove&id=1
This is the URL used in the img tag, in the example from the article linked above.  If "server" is replaced with the appropriate domain name or IP address, and you have an open session of phpMyAdmin at that URL in your browser, clicking a link that points to that URL will delete the server.  The reason this works is that the session authentication data is stored in a cookie.  When the browser loads the above URL, that existing session cookie is sent with it, telling phpMyAdmin that it is a legitimate and authorized request.  There are two problems here.  The first is the use of a GET request to do something that changes data on the server.  Officially, the GET method is only for requests that get data, not for requests that send or change data.  The POST method is supposed to be used for requests that send data.  The PUT method is supposed to be used for requests that change data.  The DELETE method is supposed to be used for requests that delete data.  The default method is GET, and simple hyperlinks will always use the GET method.  Trivially loading external resources, like images and videos, will also always use the GET method.  To use any other method, one must either create a form, where the method used can be specified, or make an AJAX request using Javascript.  Injecting forms and Javascript is a lot more difficult than injecting a simple link or resource loading tag.  Plenty of web publication sites allow hyperlinks and external images, but they typically filter out Javascript, forms, and anything else that could interfere with the functioning of the website.  The problem with the GET method is that an attacker can include all of the command information in the URL itself, which is trivial.  In the URL above, we can see that the attacker was able to specify which phpMyAdmin page the request was coming from, the command from that page to execute, and the server id (which will default to 1).  If the context and the command were instead expected to be sent in a POST request, an attacker would have to either craft a form or an AJAX request to send the command.

It gets worse though.  Merely using a POST request instead of a GET request would make this attack much more difficult.  Many sites that allow the injection of GET requests will not allow the injection of any other kind of request, severely limiting an attacker's options.  But, given a site that allows this, an attacker could still do the work to implement the exploit, because the most fundamental problem here isn't even in the request type.  The request type merely guarantees the problem will exist.  The fundamental problem is actually using cookies to transmit the session data.

Cookies are very convenient for web developers, because they automate certain critical processes.  By default, HTTP is stateless.  This means the server does not know what page you are currently viewing nor what you have viewed in the past.  The solution to this is for the client to store the state data, and it does this using cookies.  Cookies can give the server some ability to track state as well, for example, whether or not a particular browser is logged into a website.  In fact, session management is the most common use of cookies.  There are two benefits to this.  One is that the server can easily put session authentication data in a cookie instead of having to embed it directly in the HTML.  The other is that the server can avoid sending session data multiple times.  In theory, this second benefit provides greater security, because it is sending sensitive data fewer times.  In practice though, it makes little difference, because the cookie will still be sent with every request.  Sending it half the times does not double security.  All it does is makes an attacker wait marginally longer to get the session data, a small fraction of the time.  In short, the only significant benefit is convenience.  The problem with cookies is this: They are sent automatically, regardless of where the request comes from.  For example, a POST request that relies on the cookie for authentication could still be used to attack phpMyAdmin, even if it did not allow GET requests to change the DB, because the cookie is sent automatically.  A POST request that relies on session data stored in the HTML of the page and sent in the POST data would not be vulnerable to this attack, because an attack coming from an outside web page wouldn't have the authentication data, nor would it have any way to obtain it.  This is true of any cookie based session management.  The browser automatically sends the cookie with any request to the site the cookie is associated with, which means that even a request to that site from an external site will be authenticated, if an open session exists on the browser being used.

How can this vulnerability be mitigated?  Surely you cannot be expected to abandon cookies and keep authentication data in the HTML.  Perhaps, but there is one more benefit of cookies.  If you open a new tab and navigate to a site where your browser has an open session, if it uses cookies, it will already be logged in.  If it uses HTML for storing session data though, you will not be logged in, in the new tab.  This can be a serious nuisance.  It would certainly avoid the problem we are trying to avoid, but the cost would be far too high to many users.  There are a few other potential solutions.  Perhaps the best one is to split the session data.  Put most of the session data in a cookie, but keep a little bit in the HTML, to be sent with form requests and such.  That little bit extra is what authorizes the server to make changes to data.  Without it, a request with the cookie will still have the page logged in, but if the request attempted to change something, the server will deny the request and a message will be included on the response page indicating that the requested operation failed because it did not appear to come from an authorized web page.  This seems to be the best solution to the problem of cookies, without causing users too much grief.

In short, there are several changes phpMyAdmin needs to be secure against attacks of this nature.  First, it needs to check the referrer and deny requests that do not come from its own pages.  Second, it needs to apply the HTTP methods correctly, using GET only for requesting data, and using POST and perhaps also PUT and DELETE for changing data.  Third, it needs to rely less on cookies for storing authentication data, requiring some kind of authentication embedded in the HTML of its own pages for any request that alters the data or the database.  All of these together would be pretty bulletproof, and it would avoid an security vulnerability inherent to using cookies to store session data.

Of course, these strategies should probably be applied to any website that stores sensitive data.   None of this is difficult, and none of it introduces much additional complexity.  The only potential issue is that it might be a little more difficult to include a special write session key to be sent with POST, PUT, and DELETE requests, if you are using certain frameworks designed to make this easier.  Even then though, it should still be possible, and the benefit is certainly worth the cost.

Sunday, July 21, 2019

Why Reusable Software is Bad

I don't actually think reusable software is bad, but I do think excessive reliance on it is bad.  Reusable software, in the form of libraries, frameworks, or even clips of code off Stack Overflow, is very useful but also very dangerous, and dependence on reusable code is downright harmful.

I've written about frameworks before.  I don't like them.  They encourage laziness, and they often fool developers into thinking they are saving time when in reality they are not.  They also impact design in ways that a well designed set of tools should never do.  A perfect tool is one that never gets a thought during design but can then be used to implement the design flawlessly, without any modifications to accommodate for the idiosyncrasies and limitations of the tool.  A framework is supposed to be a full toolkit, but why then do most modern websites include at least three frameworks?  And worse, why is it that most websites use exactly the same tools from each one, and neglect exactly the same tools from each one?

Reusable software is dangerous, because it breeds dependence and it enables incompetence.  In 2016, this was really brought home, when the creator of a NodeJS library removed his 11 lines of trivial code from NPM, and it broke thousands of websites.  All these lines of code did was to pad out the left side of a string with spaces or zeroes, a task so trivial it could be done in only 10 lines of code (the eleventh was merely bookkeeping code that would be unnecessary had users implemented it themselves).  In fact, a slight style change would have taken it down to 9 lines of code.  There was nothing novel about his implementation either.  Any competent developer could have written that code in less than a minute.  In fact, most applications could have used a sightly shorter version, with only 8 lines of code, provided they only needed space padding or '0' padding and not both.  Why didn't they then?  They had become so dependent on reusable code that they did not even consider that they could write it themselves.  They did not consider that it could one day disappear, because they did not write it and thus had no special right to continue using it indefinitely.  Some may even have lacked the competence to write it themselves, and the use of the library enabled them to remain incompetent.

The decision to use reusable software instead of writing it yourself should always be taken very seriously.  Why do you want to use reusable software?  Is it because you don't know how to do something yourself?  If that is the case, then maybe it would be better to look into it.  Not only might it be easier to do it yourself, you might find you can make it fit your needs better that way.  If you want to use it, because you think it will take longer to do it yourself, keep in mind that we tend to underestimate how long things will take, and that includes learning how to use someone else's code!  It is often faster to create your own implementation of a feature than it is to learn to use a framework or library containing that feature.  Unless you are going to use a lot of features of a framework or library, it might actually be faster to just implement what you need yourself.  And it is worth learning now: Popularity is never a reason to use a particular piece of reusable code.  In this field, things come and go very rapidly.  Things that get popular fast often disappear fast as well.  If you need to use reusable software, because you know it is too difficult or time consuming to do yourself (OpenGL, for example) or because you need to use a lot of the features it offers and it is a good fit for your application, then it might be worth using.  If you just want to learn something new, maybe it would be better to learn something with broader applications and better staying power.

Why I don't Like JSON

JSON is really popular for passing small to medium amounts of data around the web.  It is commonly used in AJAX applications for communication between the client and server.  JSON can be really handy, because it can represent objects in a human readable form.  This is great for debugging, and makes certain aspects of writing web applications a breeze.  Unfortunately, it is also terribly wasteful, and most of the time it is unnecessary.

JSON is not the only communication protocol that has problems.  In fact, most popular protocols designed to be human readable have serious problems.  The two most common ones are JSON and XML.  The primary problem in both of these is the passing of unnecessary metadata.  For example, most JSON applications pass data that has a well defined, static format.  Metadata does not need to be passed with this kind of data, because the metadata is implied.  Imagine passing a C struct or a Java object with metadata about the variable types and names.  Perhaps for regular JSON users this seems normal and reasonably, but it is not.  The metadata in C-like languages will take up several times the memory, bandwidth, and processing power of the data itself, and this is true even if making it all human readable is not a priority.  C structs are a really good example here, because they are one of the most well defined, statically formatted, composite data types one can use.  In all but the rarest cases, a struct can be passed across a network or some other interprocess communication media, and as long as the struct definition is identical on both sides, the end product will be identical, without the need for any metadata to consume bandwidth.  Adding metadata consumes more memory, and it does not just consume a little bit more memory.  A standard integer might be 4 to 8 bytes.  If human readability is not important, type metadata can use as little as 1 byte.  The attribute name could be anywhere between 4 bytes and 16 bytes, depending on coding style (yes, it could be 1 byte, but then your code is no longer human readable, and that is a serious problem).  The metadata will generally fall between two and four times the size of the data itself.  If the type metadata is human readable, it will likely be between 3 and 6 bytes, making the metadata between three and five times the size of the data itself.  JSON avoids sending much type data, because JavaScript is so loosely typed that the parser can just infer the type from the data, but it still has the attribute names, which are often several times the length of the data, even with the data being in human readable format (which is its own problem).  XML is far worse.  XML is designed to track metadata about metadata.  In fact, it is designed to be as deeply nestable as desired.  It can track metadata about metadata about metadata and so on as deeply as one may wish to plunge.  XML attributes also add yet another form of metadata on top of the hierarchical metadata.  It is so human readable that it is actually quite difficult to read without an editor that will collapse the hierarchy to avoid displaying all of the meaningless metadata all at once.  In the vast majority of applications, there is no need to pass metadata.  In many cases, having the metadata does not even improve convenience for the programmer.  The metadata can be useful for debugging, but well designed debugging and testing tools can abstract that need away quite easily.

The other major problem with JSON, XML, and other human readable protocols is general verbosity.  Technically this is also a metadata issue, but it exists at a higher level than attribute names.  Structural metadata includes braces, brackets, parenthesis, commas, quotation marks, colons, equal signs, and anything else defining the structure of the data or the relationship between data and metadata.  Unsurprisingly, this stuff also takes up a lot of memory, bandwidth, and processing power.  XML is the biggest offender here, by far, but JSON is not that far behind.  The minimal JSON example looks something like this:

{"var":12}
The data being passed is the number 12.  The attribute name is much smaller than typical, and the only structural metadata is the mandatory outer braces, the quotation mares, and the colon.  This is 10 bytes total.  To parse it, one must find the location of the two braces, find the colon, check for commas to see how many attributes the object has, find the location of the quotes between the opening brace and the colon, compare the characters of the text between the quotes with the desired attribute name, and then read the characters between the colon and the closing brace and convert it to a numerical value.  Yes, JavaScript and any JSON library will do this for you.  No, this does not made it free.  Parsing JSON consumes a lot of processor power.  The above process takes nine steps.  The steps for comparing the attribute name and parsing the value both take a number of steps equal to their length, and the conversion of the number to a numerical data type requires multiple steps per character.  Complex JSON with multiple attributes, arrays, and nested objects gets far more complex.  If the value will always be fairly small, this value could be send in a single byte.  The client knows what to expect, because it requested the data.  The metadata is unnecessarily, because the client already knows the metadata.  Wrapping it in a JSON object is wasteful.  Send as a single byte, no parsing is necessary.  A single byte uses a tenth of the bandwidth and memory.  Even if the client does not know exactly what to expect, in the vast majority of cases, a single byte is enough to tell it.  That's 256 possible things the client could expect, and few applications have more than that.  No, it is not as human readable, but ultimately what is the purpose of writing the application?  Is the goal maximum convenience for the developers or is it getting a decent quality product to the consumers?  Yes, there is some flexibility here, but using JSON in an application like this is absurd.  It is not even lazy, because writing the code to send and process the JSON is more work than sending and receiving one byte of data.  How does XML measure up?  Let's assume we are using raw XML that is non-compliant, so we can skip things like the doctype line, the xml version line, and such.  The above expression, in its simplest form, might be rendered this way:
<var>12</var>
Of course, compliant XML would include an xml version line and a doctype line, the above would be enclosed in a root tag of some sort, and the tags might have attributes.  Alternatively, the root tag could have an attribute named "var" set to 12.  Whatever the case, this non-compliant, simplest form is 13 bytes total, which is 3 bytes longer than the JSON version.  Parsing is also a problem, though perhaps simpler than the JSON.  First, the opening tag must be parsed, by finding the bracketing greater-than/less-than symbols.  The "var" text is then compared with the expected attribute name.  The parser must then search for the closing "var" tag.  If the parser is a full XML parser, it will also have to put some CPU time into making sure the closing tag belongs to the opening tag and another tag at a different nesting level.   If not, all it has to do is verify that the closing tag matches the opening tag.  At this point it will already know where the opening tag ends and closing tag begins, so reading the value and converting it to an integer is all that is left.  In the best case, we are looking at seven steps with a few sub-steps.  In this case, the non-compliant XML takes up 30% more memory and bandwidth than the JSON, but it costs around 20% less processing power to parse.  If we enforced standards compliance, the XML would be several times larger and it would take much more CPU time to parse as well.  Again, just passing the number 12 as a single byte would be far cheaper, eliminating the parsing and minimizing memory and bandwidth.  In terms of natural language, this is like the difference between the answer, "I saw twelve cars" and "Twelve" when someone asks how many cars you saw.  The first answer is more complete, but the second answer is entirely appropriate, because the metadata is already included in the context of the question.  Similarly, if a client asks the server for the value of a particular variable, it might be more complete to respond with an object containing the context, but doing so is unnecessarily verbose, because the context was already included in the request.

There are cases where passing large amounts of metadata may be appropriate.  Most reasons for using protocols like this, however, are actually just laziness.  For example, JSON and XML do not care much about order.  An object with multiple attributes can be passed with the attributes in any order.  This isn't a valid excuse though.  It's noting more than nesting a poorly defined protocol inside of another protocol that contains metadata, so you can avoid the consequences of lazy coding.  A well defined protocol would define length, order, type, and meaning of each piece of data being sent, eliminating the need to send any metadata.  In the case where length cannot be predefined or would be unacceptably inefficient to predefine, the protocol would provide a dedicated place to provide the length metadata, but it would not include any unnecessary metadata.  The only place where large amounts of metadata are necessary are places where it is impossible or infeasible to use a well defined protocol.  Several examples of this are found in web sites.  HTTP and HTML are weakly defined protocols.  HTTP has a few somewhat positional elements, but the rest is defined by data not by position or length.  HTTP headers must be parsed, they cannot be treated like well defined, statically formatted structs.  This is necessary though, because applications of HTTP vary so dramatically.  Every server cannot define its own unique protocol and expect every client to understand it, nor can every client define its own unique protocol and expect every server to understand it, and the W3C cannot be expected to create a separate standard for every single web site.  Some servers may need to communicate different information from others.  Some web sites may need to communicate different information from others.  Thus a flexible and dynamic approach is necessary.  The same is true of HTML at the presentation layer.  Every web pages doesn't need the same organization.  CSS must by dynamic, because every web page doesn't need the same style and layout.  But unless your web application is going to be communicating with a lot of different systems that might have a lot of different needs, there is no reason to use such a flexible and dynamic protocol.  Flexible and dynamic protocols are wasteful and inefficient, and they are far more prone to bugs than compact, well defined, statically formatted protocols.  Less well defined protocols are also prone to bloat, because they typically ignore extraneous white space.  For the applications where they are needed, this is a useful feature, but for well defined applications, this is wasteful and potentially harmful to clients.  Bandwidth, memory, and time are not free, after all.

JSON isn't a useless protocol.  Dynamic protocols like JSON and XML have their place.  That place, however, is not in applications with well defined communication needs.  When the need can be filled by designing a much simpler, much more elegant, and much more efficient protocol, then designing and using such a protocol should be the solution.  Only when a simple, elegant, static protocol is impossible or unfeasible should a stock dynamic protocol like JSON or XML be used.  And even in those cases, it may still be appropriate to use a simplified version, if the parser you are using can handle it.

The real reason I don't like JSON isn't that JSON is bad.  The real reason is that it is used as a default in applications where it really shouldn't be and where it actually wastes time instead of saving it.

Thursday, May 30, 2019

Why I Don't Teach Unity

I teach college level video game design.  Every semester some student asks about Unity.  Unity is a game development platform.  Essentially, it is a program that does a lot of the game development work for you.  Unity can do things like handling lighting and shadows in 3D graphics.  It can deal with animation for you.  It provides access to a decent collection of art assets.  In all, it can make video game development significantly easier.  In software development though, tools that make things easier always come with a price, and complex general purpose tools can come with a high price.

The first reason I don't teach Unity is that it would defeat the point of the class.  There are two parts to the course.  One is knowledge.  This focuses on design.  It covers things like how to design a game that keeps players engaged, and how to design games with specific goals in mind.  The other part is application.  This is about programming.  Students could learn the design knowledge and apply it to games in Unity, but the course would be more of an art course, not a computer science course if I did that.

The second reason I don't teach Unity is that big game companies (that might be interested in hiring my students) don't use it.  Yes, there are a few large game companies that have used Unity for maybe one fairly small game.  This is not typical though.  Large game companies write their games in languages like C++, mostly from scratch.  If a student applied for a job at a company like Blizzard and cited my game course as a qualification, if I taught Unity, that student would be treated like a second class applicant.  Blizzard is not looking for Unity developers.  Blizzard is looking for developers who can write games without the need for a crutch.  If I want my course to be a good selling point for getting a job in the game industry, I cannot take the lazy approach and teach students to use a game development platform that does all the heavy lifting for them.  They need real experience with real tools.

The third reason is teaching problem solving skills and providing practical experience.  While many of my students do have an interest in becoming game developers, most of them won't end up in that industry.  Learning to write games using Unity will be worthless to these students.  It does not carry over to other applications.  It also solves the hardest problems for them, denying them experience that will help build their problem solving skills.  Writing games from scratch does provide significant experience that will carry over to other applications, and it provides an excellent opportunity to build problem solving skills.

The fourth reason is that relying heavily on 3rd party tools carries a lot of risk and difficulty.  The main problem is that tools designed to be general purpose are rarely ideal for any given specific purpose.  Unity is designed to be suitable for a wide variety of games.  This means that it is tracking data and doing processing that is probably not necessary for any given game.  A game of one genre or style might require something that other games don't really need, but Unity has to provide it to accommodate any game someone might want to make.  If there are things Unity does not provide, that will make it harder or even impossible to make games that need to rely on those things.  This cuts into efficiency, which means that a game written in Unity will almost certainly perform worse than a game written in C++.  For small games, this may make no difference, but for big ones it can limit the market to only users with very high end computers.  This is one element of risk.  The other element of risk is failure.  If Unity has a bug that makes your game not work, you can't just fix it.  Even if you had access to Unity's code, it could take months to learn the code, find the bug, and then fix it.  This is rare, but it is worth considering, and big game companies do consider it, and they don't use 3rd party game development platforms for these reasons.


These are the top four reasons I don't teach Unity.  They do not cover everything though.  Unity is mostly used by small indie developers who are either not interested in hiring or who cannot afford to pay even the low wages of a CS graduate.  It is certainly a useful platform for hobby game makers who like to tinker.  It can even be a good gateway into game development for people without much programming experience.  It is not appropriate for a course in a college Computer Science department that wants to produce high quality graduates who have good programming skills, and it is certainly not appropriate for giving students knowledge and experience that might help them get a job in the video game industry.  This is an industry that gets a ton of applicants, and even a small edge is worth quite a lot.

Unity is not terribly hard to learn.  Like I said, it does all of the heavy lifting for you.  Real game programming requires decent math skills.  Unity does most of the hard math for you.  This makes it trivial to learn compared to real game development.  There are plenty of online tutorials and courses for learning to make games in Unity, which is why indie developers with little or no education in computer science can do it.  People that want to learn Unity have plenty of resources available to them.

I want to provide the best education I can to my students.  Teaching them something that is probably not going to be useful to them does not do that.  Teaching them something they can easily learn on their own with a little bit of study online does not do that.  Teaching them skills that are useful in a variety of places and knowledge that is difficult to find will provide them with the value they deserve.

Wednesday, May 29, 2019

Why I Hate Frameworks

While most of the software development world has been rushing headlong into mountains of awesome frameworks over the last decade-and-then-some, I have been quietly reinventing the wheel.  At least, that is how a lot of developers often see me.  I do not like frameworks.  I avoid using frameworks.  When I am forced to use frameworks, I do not enjoy it.  I find frameworks only cause me pain and suffering.

Reusable code is not a bad idea.  I am a big fan of well written libraries that save me significant time and energy.  That is not what frameworks are though.  I have seen well written frameworks, but the truth is, it tends to be a toss up.  Your odds of getting a well written framework are not better than your odds of getting a poorly written one.  While I have rarely had to peak into the guts of a framework (a distinct benefit of avoiding them), those that I have had to dive into have not been good.  On one occasion, a family member offered me a decent bounty to find and fix a bug in a popular framework.  I spent a few hours trying to get familiar with the code of the framework, but in the end, I realized that I would have to charge several times the bounty offered to make it worth my time.  Over the course of a few hours, I was unable to trace the path through the code that the program was taking.  It was not that the framework was particularly complex.  I can handle complex code.  It was just poorly written.  It might have looked like a nice framework for people who would not have understood what was under the hood regardless of quality, but for an experienced software developer, it was absolute garbage.  On another occasion, I was doing some QA work for a corporation, and I needed to get a little bit more information out of their automated testing system.  Of course, they were using a reasonably popular framework for the automated testing.  It took me days of combing through the framework to figure out where everything was happening, so I could add the critical code to provide the required data.  Again, it was not a matter of complexity.  The problem was that whoever wrote the code was doing things in the most roundabout way possible.  There was a massive amount of coupling.  Everything was touching everything else, and consequently, to understand one thing, I had to understand everything.  Other frameworks I have used are often buggy, and the generally poor design and code quality make it not worth the effort to try to fix the bugs myself.  I have also had a few occasions to look inside general purpose libraries, and I typically find them to be of much higher quality.  This is not always the case, but when I discover a bug in a library, I do not feel the same anxiety when considering whether to try to fix it myself or not.  So the problem is not that reusable code is just a lousy idea.  It is a great idea.  The problem is that frameworks specifically tend to be low quality.

There are a lot of reasons I avoid frameworks.  The worst is the fact that most frameworks require a lot of effort to do even the simplest things.  The theory is that frameworks make everything easier.  The reality is that they tend to make hard things significantly easier and easy things much harder.  For example, the straw that broke the camel's back (and pushed me over the edge, into writing this article) is the ESP-IDF framework for programming the ESP32 micro-controller.  I would not have used the framework voluntarily (I actually prefer manipulating the hardware directly), but it turns out enough of the ESP32 is proprietary, and the FreeRTOS real-time operating system only has the framework implementation available, so I have no other option.  The ESP32 is an excellent micro-controller, with built in wifi and a lot of other really nice features for its price.  The framework, however, is a disaster.  For a previous project, I used I2C on an Arduino, which I programmed entirely in C.  Because I did not want to write my own I2C driver, I took Arduino's driver and ported it to C.  This was mildly challenging, but despite excessive complexity, Arduino's code was written well enough that it was not too much of a chore.  Now I am writing the same program for the ESP32, and the ESP-IDF framework's I2C driver is a nightmare.  I do not even have to port it to C.  It is already in C.  Somehow though, it is actually more work to use than it was to port Arduino's driver to C and use that.  The fact is, I2C is trivial.  It is not a complicated protocol.  (It is not terribly well designed, but it is not complicated either.)  The most difficult part of porting the Arduino driver was eliminating all of the unnecessary object orientation.  ESP-IDF is written for C, so it does not even have object orientation, and yet it manages to be several times more complex.  The fact is, I2C is such a simple protocol that the most difficult part of using it should be setting up the pins on your chip and configuring the clock speed, if your chip has a built in I2C controller (the ESP32 does), but that is not how it works with ESP-IDF.  No, setting up the I2C device is fairly simple (though, the documentation does nothing to help, and the provided example code is stupidly complex).  The first step is setting up a struct to tell it which pins to use, how to initialize them, what mode to use, and what clock speed to use.  The second and third steps are a pair of function calls that really could have been rolled into a single function call.  One extra function call is not a disaster though, and maybe it is somewhat justified, if you need to enable and disable I2C frequently.  That is where the simplicity ends though.  With the ported Arduino I2C library, once you have the thing the initialized, you can call a single function to read and a single function to write.  You give the functions the address, the command, and a few other parameters, and you are good to go.  With ESP-IDF, I2C reads and writes are major productions.  First, you have to tell it that you are starting an I2C transaction.  Next you have to tell it to start accepting data for the transaction.  Then you have to do a pair of write function calls to tell it what you want to write (it may be possible to roll them into one, but all of the examples show it as two).  Then you tell it you are done giving it the transaction data.  Do not think it has actually sent the command though.  After that, you tell it to send the command.  Once that is done, you have to tell it to delete the transaction.  In Arduino, this is all a single function call.  In ESP-IDF, it is a disaster.  I2C is a simple protocol!  ESP-IDF manages to take something incredibly simple and turn it into something extremely complicated.  This is perhaps the biggest reason I hate frameworks.  This is not a one time thing either.  Even Arduino's I2C driver is overly complicated to use.  In the process of porting it, I eliminated a significant amount of setup cruft caused by using an object oriented approach where it is entirely unnecessary.  In my experience, every framework has places where it takes something almost trivial and makes it more complicated than it has to be.  Libraries sometimes do this too, for example, most high level languages built in libraries make pipes prohibitively hard to use (one of the few places Python really biffs it), but frameworks do this all over the place.  Threading libraries tend to do this as well.

Compared to this, most of my other issues with frameworks are trivial.  The worst one is that when a framework has a bug, it is a lot harder to fix than a bug in code you wrote yourself, even if the framework is well written, because you are not familiar with the framework's code.  I have legitimately abandoned frameworks because they had one critical bug that would have taken me more time to fix than just writing the code myself, from scratch.  Now days, I generally just skip the part where I use a framework in the first place.  Another is that, in my experience, frameworks often take more time to use than writing code from scratch anyway, because learning a framework takes time.  Unless I am going to use most of the features offered by the framework, it is not worth my time to learn it.  I have written AJAX functions from scratch many times instead of using JQuery, because it is actually faster to do that than it is to setup JQuery on my web site and look up how to use its (admittedly high quality) AJAX stuff.  Frameworks also consume unnecessary space, leading to memory bloat, performance costs, and unnecessary bandwidth costs, unless you are using almost 100% of the features provided.  These things may seem trivial, but when you consider the scale on the server side instead of at the individual client, it adds up surprisingly fast.  Frameworks also tend to come and go, especially in web development.  This means that the framework you are learning today probably will not be worth much to you in a couple of years.  It might help you advance in your current company, but most promotion in the software industry is not internal, and that other company you really want to work for probably does not use the framework you are learning for your current job.  This is further aggravated by the fact that there are so many frameworks out there that there really is no point learning one that you do not have an immediate application for.  Lastly, and this is really more important than the last few issues, frameworks are almost never as general purpose as libraries.  Nearly all frameworks are designed with a fairly narrow set of use cases in mind, but then they are advertised with a focus on one design element that is not closely related to those use cases.  For example, responsiveness is a popular feature of web frameworks that dynamically load data.  Most such frameworks are designed for point-of-sale and inventory management, and they tend to be janky or even downright lousy for anything else.  They do not tell you that you should not use them to make a site that needs good quality real-time interaction though.  They do not tell you that the responsiveness comes at a heavy performance cost.  So you decide to use a framework like AngularJS, because "responsive" sounds like exactly what you want for your browser game, but halfway through, after you have spent many hours learning the framework, you discover that while it might work well for business applications (if you are willing to tolerate the making-easy-things-excessively-complicated problem that it also has), it is a horrible choice for games, because what they mean by "responsive" is not the same as what you thought it meant.  (No, I did not actually try to use AngularJS for a browser game.  I did use it for an inventory management system though, where it worked fairly well but where the performance costs occasionally reared their ugly heads in ways that do not matter to an inventory management system but that would make a game unplayable.)

There are a lot of problems with frameworks.  Their popularity makes it clear that a lot of people are willing to put up with those problems, for the perceived benefits, but in my experience, most of those benefits are ethereal.  Recent research suggests that system and development architectures make a much bigger difference in success rates than development stacks anyway.  This means that any benefits gained from using a particular framework will almost certainly be dwarfed by improving team communication and spending more time on quality design work.  My personal experience supports this conclusion.

What it all comes down to is that if you really want to use a framework, pick one with features you are going to use, and know what you are getting yourself into.  Personally, I find it easier and faster to code the features I want myself, and I find that the time spent finding and learning a suitable framework ultimately costs me more than just writing the code myself.  You might say I am reinventing the wheel, but the fact is, when there are a million different kinds of track, you need a million different kinds of wheel if you want all of your trains to run smoothly.

Tuesday, November 13, 2018

Comprehensive Password Security

We are doing passwords all wrong.  Requiring excessively complex passwords that are impossible to remember is absurd, especially given how much easier it is to ensure password security through other means.  Requiring numbers or special characters is far less effective than requiring a few additional characters.  Users are far more likely to write down passwords that are difficult to remember in places that are easy to find.  When users forget passwords frequently, and they have to be reset, it sets a precedent that makes it easier for someone else to fraudulently reset the password.  In general, our current guidelines for password security are a disaster.

I am going to give you a warning now: This post is going to be math heavy.  I am not going to try to explain how all of the math works, but I will try to explain what numbers mean, to make comparisons more meaningful.

To start with, you should really read this comic: https://xkcd.com/936/  According to some sources, some of the math in there is wrong, but one thing is definitely right: The second password, composed of four common English words, is more secure than the first one, which uses a bunch of numbers and special characters that make it harder to remember.

The calculations used in the above comic measure password security by calculating how much entropy the password has.  The entropy represents the number of possible passwords that could exist of that length with the combination of character classes used.  Common character classes used in passwords include letters (these can be separated into an uppercase and lowercase class), numbers, and "special characters" which is anything that can be typed on a keyboard that is not in the other two classes.  Space tends to be ignored, but it could be grouped into special characters.  To convert the entropy value into the actual number of possible combinations, you raise 2 to the power of the entropy.  So, if the entropy of a password is 28, you can calculate the number of possible combinations with 2^28 = ~268m.  On average, a brute force hacking algorithm should be able to figure out your password with only having to try around half of the possible combinations, in this case 134 million, which a modern computer can easily do fairly quickly.  We won't bother looking at actual numbers of combinations from here on out, but keep in mind that adding one bit of entropy doubles the difficulty of cracking a password.

Most accounts require a password at least 8 characters long, with letters, numbers, and special characters.  Assuming the password is just a randomly selected combination of all characters that appear on a typical keyboard, that is 95 possible characters, which has an entropy of about 6.6 per character or 52.4.  So let's use 52 as a minimum acceptable security level, since that is approximately what most web sites require.

The xkcd comic suggests that a password of four common words, in all lower case, has an entropy of 44.  When something like known words are used in a password, we cannot just calculate entropy per character.  First, each word must be treated as a whole entity itself, because a word has different entropy (typically less) than the same number of characters.  If a hacking algorithm tests common words before going to brute force (most do now days), it will break your password faster than a pure brute force algorithm.  English has around 3,000 common words.  That's close to 11.5 bits of entropy per word (verified by calculating 2^11.5).  Four words thus will have about 46 bits of entropy (which makes xkcd's estimate right on, if he rounded down to 11 bits per word).  The average English word is about 5 characters long, so a four word password is around 20 characters long.  That might seem like a lot, but memorizing a password of four common words is a lot easier than memorizing eight random characters.  An entropy of 46 bits, however, is well under 52 bits, which is our minimum reasonable limit (a 6 bit difference means the 46 bit password is 64 times less secure).  Four common English words is not enough for good security.

The Second Edition of the Oxford English Dictionary contains around 180,000 words that are still in use (as well as 47,000 obsolete words, which I will leave out for convenience, but which might actually be good to use, since a dictionary attack is unlikely to include them).  That is around 17.5 bits of entropy per word.  A password composed of four randomly selected words from the 180k words that are still in use listed in this dictionary would have a total entropy of 70.  That's 18 more bits (2^18 = 262k times more secure) than our baseline of 52.  It will probably be a little bit harder to memorize than the common words, but it should still be pretty easy, and it is still only around 20 characters.  Without capital letters, numbers, or special characters, this password is five orders of magnitude more secure than the baseline.

We can do better though.  There are a few reasons words are so good for passwords.  They are all based on the fact that words are easier to remember than random character strings.  First, pronounceable words will be easier to remember, and second, the meanings of words make them easier to remember.  These happen in different parts of the brain.  Pronunciation of a word will be stored in areas of the brain associated with decoding the meaning of language heard, as well as areas associated with speaking.  Meaning will be stored in regions associated with abstract thought.  These will form connections that make the password much easier to remember.  If we make up pronounceable words and then give them meanings though, we eliminate the possibility of a dictionary attack, falling back to brute force, where we add up the entropy of each bit.  Now it depends on the length of the password again, and we don't have this issue where a long word has no more entropy than a short one.

Before we do this, we should look at the entropy for various sets of character classes.  The letter class (uppercase and lowercase) has 52 possibilities, for 5.7 bits of entropy.  Letters and numbers has about 5.9 bits of entropy.  Letters, numbers, and special characters (everything that is on a modern keyboard) has about 6.6 bits of entropy.  Notice that adding numbers only increases the entropy by 0.2 bits per character (a 14% increase in possibilities).  Adding special characters only increases entropy by 0.7 bits per character (a 62% increase in possibilities).  For an 8 character password, adding numbers increases entropy by a total of 1.6 bits, and adding special characters only increases entropy by a total of 5.6 bits.  Adding a single character increases overall security by more than adding either of these.  Adding numbers and special characters to an 8 character password increases overall entropy by 7.2, which is better than adding a single character but far worse than adding two.  In short, adding length to a password makes a far bigger difference than requiring more character classes.  Requiring numbers and special characters makes only a very small difference.  The primary value in this is making it harder for users to make terribly insecure passwords, by discouraging the use of single common words.  The key for getting secure passwords is all about length, not character classes.  For an additional character class to add even 1 bit of entropy per character, it has to double the total number of possible characters.  Adding length, on the other hand, increases security exponentially.

Now, let's say you make a password of four made up words, all lowercase, without spaces, where the length comes out to 20 characters.  Because the words are made up, a dictionary search won't work, so we have to use brute force.  Each character adds 4.7 bits of entropy.  (All lower case gives 26 possibilities per character.)  This password has a total of 94 bits of entropy.  That is extremely secure compared to the baseline of 52.  Because these words are pronounceable, they are easy to remember.  If you give them meanings, that will make them even easier to remember.  Because there are so many characters, despite its minimal effect, throwing in a number will increase the entropy by 4 (16 times harder to break, which is honestly not as impressive as it sounds), giving you 98 bits of entropy.  Throwing in a special character or two will increase the entropy by 14 bits (which is a little bit more impressive but still pretty low compared to initial 20).  Together, you get a total entropy of 112 bits, at the cost of having a couple of characters that make it harder to memorize.  (Honestly, I am still questioning the value of adding the numbers and special characters, because that's only a total 16% increase in security, at the cost of being harder to memorize...  Adding only 4 additional characters would have a bigger effect.)  The biggest effect you can get is by capitalizing the first character of each word, which doubles the number of possibilities per character, increasing the entropy by 1 per character.  That gives you a total entropy of 114 bits, without adding numbers or special characters.

Good password security is not about using numbers and special characters in your passwords.  It is purely about length.  If you avoid using combinations of characters that are coherent in any common language (ie, don't use words that exist in common languages), you can still create easily memorable passwords that are long enough to be extremely secure.  Just 20 lowercase characters has an entropy of 94, which is 42 bits stronger or 2^42 =  4.4 trillion times more secure than the minimum security required by most sites.  The only problem you may run into is some sites using poor security practices themselves limit password length to 16 characters (75.2 bits for all lowercase made up words and 92.1 bits if you include some uppercase letters).  Even with this limitation, using made up words is massively superior to short passwords that are too random to be easy to memorize.  In fact, with only lowercase letters, you only need 12 characters of made up words to have a password of equivalent strength to an 8 character password including lower case, upper case, numbers, and special characters, and with both lower and upper case, you only need 10 characters to beat it.

The takeaway here is that the best passwords are made of multiple made up words that are pronounceable and have meanings.  Passwords like this, with at least 16 characters, will be significantly stronger than the weakest password most sites allow, and on top of that they will even be easy to memorize, and all of this is true even if you use only lowercase English letters.

Thursday, October 11, 2018

Minecraft Mod Economics

I have been playing Minecraft with mods off and on for a few years now.  Instead of installing huge mod packs, I generally prefer to play only a few at a time, and I typically play just one major mod with a handful of support mods.  When I play with multiple major mods, I generally find myself focusing on only one of them but rarely more.  I recently analyzed this behavior, and I found that the reason is economics.

Vanilla Minecraft has a pretty good economic balance.  I have a few complaints, but they are mostly the consequences of my play style, not any clear flaw in the game.  I generally prefer to focus on exploring, gathering, and building.  I don't spend a lot of time on combat, and I never go out of my way to find and fight bosses.  I prefer to make mob farms to get drops rather than fight them on even footing.  This means I don't get a lot of Ender pearls, I have never obtained a Nether Star, and I have not even gone to the End, let alone defeated the dragon.  This works well though, because Ender pearls are mostly used for finding the End, which I have little desire to do, Nether Stars are good for building beacons, which mostly boost combat stats which I don't care about, and all the Ender Dragon provides is a trophy and experience (which can be obtained from a good mob farm).  In short, the economics of vanilla Minecraft work fairly well, even for different play styles.  Perhaps the only real complaint I have had is that rails cost a lot of iron and gold for any significant distance, and getting the materials is incredibly time consuming.  As a result, I don't use rails much anymore, which is a shame, but the game is still fun even without them.  For the most part though, the economy of the game is well balanced, allowing resources to be obtained as they become needed without costing more time than they are worth.

Mods, on the other hand, often fail at economic balance.  The least susceptible mods to poor economics is mods that add their own resources to the game and use built-in resources minimally.  They are successful, because it is easy to balance your mod with new resources that are not used for anything outside of your mod.  Most mods don't do this though, and even many very popular mods fail in economics.  Recently, I have played using BuildCraft, MystCraft, Immersive Engineering, Thaumcraft, Twilight Forest, and Botania.  These are all fairly popular mods.  They are all very well made.  But most of them have at least a few economic balance issues, and some have pretty serious issues.  The biggest problem with economics is using built-in resources in ways that cause competition with the vanilla content or with other mods.  For example, Botania and Thaumcraft have a fair amount of content that uses Ender pearls, gold, and diamonds.  Most major mods have some economic flaw like this.

Botania really fails hard with terrasteel, where one bar of terrasteel costs an iron bar, an Ender pearl, and a diamond.  The iron is not a terrible problem, especially given that the equipment made from terrasteel replaces your iron or diamond equipment.  The Ender pearl is a very high cost though, given that Endermen are generally rare, and they are notoriously hard to farm.  The diamonds are a less dramatic cost, because the terrasteel is taking the place of diamond or lower tier equipment, but now we are competing with vanilla on two equipment materials that are fairly limited.  This makes getting terrasteel very frustrating, because first you are spending a lot of time mining when you really want to be doing other things, and second, the mining itself is consuming some of the materials you are trying to collect.  It's true, the terrasteel tools have some pretty awesome time saving features, but by the time you finally have all of the materials to make them, you have already spent so much time getting the materials that the time saved does not feel like it will ever make up for it.  It also does not help that after spending so many hours mining, you just don't feel like mining ever again, making the nice tools a lot less motivating to use.  Ender pearls are also a problem when it comes to making the elf portal.  This portal basically opens up the second half of the content in Botania.  Unfortunately, you have to craft a set of equipment that is fairly heavy in Ender pearl cost to make the portal work.  I spent tens of hours during one game trying to find Endermen to kill for Ender pearls.  I had the portal completely constructed, and I only needed a couple more Ender pearls to power and open it.  After days of spending a few hours a day hanging outside at night looking for Endermen to kill, I gave up.  I got one spawn, and it did not even drop a pearl.  It was beyond frustrating, and now when I even think about opening a portal, it feels like an insurmountable task.  Botania also has a few items that cost a lot of gold.  If you want to automate anything in Botania, you need hovering hourglasses as redstone timers.  Unfortunately, each one costs four gold bars, which is quite a lot.  Yes, you can make gold and iron farms, and once you get to the End, Ender pearls are really easy to come by, but all of these things take a lot of time and planning.  I'll come back to this later, but part of the issue when it comes to stuff like this is that I have done it so many times already that it feels incredibly tedious when all I want to do is experience the content of the mod.  Where Botania does really well is in the resource it adds.  Botania adds mana to the game.  Early on, it is hard to generate mana in large quantities, but by the time you need it in large quantities, it is easy to generate in large quantities.  Mana production relies mostly on renewable resources.  Some methods can generate manage by consuming non-renewable resources, but most have renewable options.  For example, mana can be generated using food or charcoal as fuel.  Automating food production is easy even in vanilla Minecraft, such that there does not need to be any competition between vanilla and the mod.  Botania makes automating food production even easier, with the hovering hourglass taking over the role of a larger and more elaborate redstone clock (though at a high cost in gold).  Automating charcoal production is much more difficult before the elf portal is opened, but charcoal is generally not terribly difficult to manually produce in significant quantities.  In general, Botania's economic balance when it comes to its own resources is quite good, but it does a poor job of economic balance when it comes to its use of vanilla resources.

Thaumcraft has similar issues to Botania, though perhaps not as severe.  Part of the issue with Thaumcraft is timing related though.  Early Thaumcraft has really poor balance when it comes to iron and gold.  Thaumcraft especially competes very strongly with vanilla uses of iron.  The last time I played Thaumcraft (a month or two ago). I found myself spending around 20+ minutes underground mining for iron for every minute I spent above ground doing anything with Thaumcraft.  I burned through iron so fast, and I frequently found my Thaumcraft progress stalled by lack of iron.  For a significant period of the early game I did not even have iron armor, because all of my iron was going to Thaumcraft stuff.  Eventually I did start accumulating significant amounts of iron, but right around that time, I started hitting the same problem with gold.  It was less severe, but I was still spending more than half my time mining for gold for a while.  Thaumcraft does have an ore doubling mechanic, but early in the game it is too expensive (and environmentally harmful) to use a lot.  The most frustrating thing, however, was (again) Ender pearls.  There is one type of resource in the mod that has no other source except Ender pearls, and Ender pearls only provide a very small amount of that resource.  Thaumcraft is not as bad on this as Botania, using this resource only in limited amounts for some pretty late game stuff.  Unfortunately, that late game stuff is pretty trivial to unlock somewhere around mid-game.  Worse, the mod does nothing to clarify the fact that this is late game stuff, so when you unlock it, it feels like you should be able to (and maybe need to) use it right away, when in reality, the only way to use it effectively is to farm Endermen in the End.  For a majority of its resources, Thaumcraft is actually very well balanced.  Nearly all of its resources are produced from vanilla content.  Half of those that are not displace vanilla resources, but they displace resources that are plentiful and farmable (trees, mostly).  Thaumcraft does add some resources, but a vast majority of its resources are derived from vanilla resources.  For a most of those resources, it does an exceptional job of balancing.  In part, this is because nearly everything in vanilla can be turned into Thaumcraft resources.  Thaumcraft does not rely as heavily on scarcity for resource control as it does side effects.  You can easily obtain enormous amounts of most of the resource types quickly and easily, but the consequence is that your land becomes diseased and extremely inhospitable.  The motivation to only produce what you really need is pretty strong.  The places where Thaumcraft fails is where it relies on the scarcity of certain vanilla materials to control the availability of some very valuable resources, because in those places it ends up competing with vanilla features for resources.

Immersive Engineering also does a lot of things right but a few things wrong.  It adds some resources to the game, and where it does this, it does extremely well.  It adds uranium for power generation, and its rarity is perfectly balanced with its value.  It has been a while since I played this mod, so forgive me if I get the occasional detail wrong, but I do recall some struggles.  I seem to recall this mod having a serious problem with iron.  Most of the machinery uses a ton of iron. The Crusher does double the ore obtained from ore blocks, but this only mitigates the issue, and the Crusher is not available till mid game anyhow (not to mention has an absolutely _massive_ iron cost, which won't be doubled, because you don't have the Crusher yet).  Ore doubling is actually a common method for reducing resource competition between vanilla and mods, but there is only so much it can do, especially when it is a mid game tech.  Immersive engineering also adds a power resource, Redstone Flux (RF), which is reasonably well balanced but not, perhaps ideal.  There are three different kinds of wire, which can carry different amounts of current and different voltages.  They are made from different materials as well, and this adds some challenges of its own.  Some of the larger equipment in the mod has extremely high power consumption, and the result is that it costs a lot of resources (including a lot of vanilla) to power them.  This is not actually as bad as it sounds though, because most of this is really late game stuff that is not easily accessible earlier.  It largely just ends up being very time consuming.  It does compete somewhat heavily with some vanilla resources, but the pacing of the mod makes it so that you are pretty likely to already have most of what you need by the time you have the mod progressed up to that point.  The Immersive Engineering Excavator is especially useful in keeping up on resources, but it is pretty late game, which means a lot of its benefit comes too late to help a lot.  It also costs enough iron to be a serious project to build even late game, when you think you already have a ton of iron.  The last time I played this mod, most of the struggle was early on, and I spent a lot less time trying to keep up with vanilla and Immersive Engineering than with other mods.  Part of this is that Immersive Engineering heavily supplements vanilla resources with its own, limiting competition.  It also adds more automation stuff earlier on than other mods, reducing the burden in the early and mid-game.  I found this mod less frustrating than some others, though it is still not perfect.

BuildCraft has some resource competition issues in the early game as well.  It does not compete as heavily as some other mods, because it largely limits competition to resources that are less rare, but there are some points where excessive time has to be spent gathering resources.  BuildCraft does manage to keep these pretty minimal though.  It does this by tiering a lot of its content based on vanilla resources.  For example, pipes can be made from a lot of materials, where higher tier materials give them better properties.  This makes a lot of BuildCraft content available quite early on.  There is a period between high iron competition and highly automated mining where things tend to drag on a bit, but it is actually pretty fast to get through this compared to other mods.  The biggest difficulty with BuildCraft is probably the time spent on the liquid fuels required to automate at high speeds.  These are made from BuildCraft oil, which either must be carried (in buckets or similar container) or piped to where it is to be refined.  The refinery equipment is expensive enough that it is often more economical to just move it from one oil spring to another, but this is pretty tedious.  Piping is another solution, but for any real distance, it gets expensive very fast (and then you run into chunk loading issues...).  Unfortunately, this is not a completely automatable task either, because oil springs eventually run out.  Once you have a good system, it is worth the effort, but early on it is very tedious.  Overall, BuildCraft does a fairly decent job with game economy.  It has a few points where things are difficult for a bit, but it does pay that back fairly quickly once you get automated mining going.  Once you reach this point, BuildCraft can even produce enough mineable resources to support a couple additional mods.  BuildCraft's massively advanced automation control stuff also really helps reduce drudgery in the late game, but progressing to it involves a lot of drudgery.  I have only gotten a little way into the circuitry and such, mostly because the more valuable chipsets are so expensive (using iron, gold, diamonds, and Ender pearls).  But, these are not critical to solid automation in the mod.  The more expensive stuff is more about convenience than anything, so doing without them is not a huge burden.  Overall, BuildCraft's economy is pretty solid.  There are a few hiccups, and there are some failures in the very late game stuff, but none of this is anything terribly critical.  My biggest frustrations with BuildCraft come from inventory management when there are such huge quantities of resources coming in, but this is better than not enough, and there are good support mods specifically for dealing with this problem.

Mystcraft only produces one serious challenge when it comes to economics.  This is leather, and it brings up another issue some of the above mods occasionally have.  The problem is that sometimes, there will not be any cows near spawn.  When I say "near", I mean, on two occasions in the recent past (out of the 5 or 6 worlds I have created recently, which means about 1/3 of the time), I have landed half a day's (MC time) boat ride from the nearest cows or more.  In at least one, I never did find cows.  Luckily, that time I was using a mod that made it pretty easy to make leather from rotten flesh, without first needing leather to start the mod off.  (The other time, I was playing Thaumcraft, and I am not even sure how far I ended up going from spawn to find a cow just so I could craft the mod documentation/progress book.  I think I ended up holing up for at least one night during the journey.)  Mystcraft requires a lot of leather if you are doing it right, and when you cannot find any cows, the mod is straight up impossible to do anything with.  Now, I cannot blame the mod entirely for this, however, mod makers should be aware of cases where a critical material for the mod may be rare enough to seriously hold up the mod progression.  For leather, a simple solution would be to just add a recipe for crafting rotten flesh to leather.  It does not have to be one for one, and it can even be more expensive than just the rotten flesh, though if leather is a major resource for the mod (Mystcraft, for example), the cost should be quite low.  Two good options I have seen are four rotten flesh crafted in a square to get one leather, and cooking a piece of rotten flesh in a furnace turns it into leather.  One costs four for one, and the other costs fuel on top of the main ingredient.  Neither is terribly overpowered either.  The point is, mods should be aware how scarcity of resources used in the mod can vary.  In the current game I am playing with Botania, I have not found a biome with emeralds yet.  If I needed emeralds for some critical, early part of the mod, this could be a serious problem.  (As it is, I have found a village, so for the mid to late game, I do have access to emeralds.)  Overall, Mystcraft is a very well balanced mod, when it comes to economy, but it does occasionally have issues, because it fails to account for a scenario that is not terribly uncommon.

The last mod I want to discuss is Twilight Forest.  I have far less experience with this mod than the rest.  (In fact, I am currently playing it for the first time.)  From what I have seen so far, it is very well economically balanced, mostly because it primarily focuses on non-resource content.  The only resource (vanilla or otherwise) I have spent on it is a single diamond, to open the portal to the forest dimension.  While diamonds are legitimately very rare, a one time cost of a single diamond for the mod only barely competes with vanilla.  One diamond ever is not a significant burden.  In the worst case, it could be a cost of 30 minutes to an hour of mining, in exchange for a ton of additional content.  By focusing on content that has no resource economy, Twilight Forest has managed to almost entirely avoid the economic issues common in other mods.

It should be pretty easy to see, at this point, how some mods harm the economy of the game by adding resource competition without sufficiently improving access to those resources.  When mods are combined though, resource issues can be further amplified.  Thaumcraft and Botania both expect a certain level of access to Ender pearls, and neither provides a decent means of increasing production.  This means that now the mods are competing with each other in addition to the game.  Similarly, Thaumcraft and Immersive Engineering both do ore doubling, but when you play them together, now you need three times the ore but neither can do more than double ores.  Mod authors should also consider how competition with other mods is going to affect their mod economies.  When you have multiple mods and the vanilla game all competing for the same resource, players are not going to enjoy the game as much.  Generally this will result in players picking one or two mods to focus on, and in big mod packs, odds are your mod won't be one of them.  This can be mitigated by adding support for other mods to your own or by using standard resources that can be shared between mods without too much competition, for example, a significant number of mods use the Redstone Flux energy that Immersive Engineering uses, allowing players to use the same power generator for multiple mods, instead of having to construct a different generator for every mod.  It is important for mod makers to at least consider how their mod will play with others, and that includes their impact on resource economy.

The last thing to keep in mind about resource economies in mods is that most people playing with mods have a fair amount of experience under their belts.  To be clear, they have already experimented with automation, they have already played through the early game many times, and they are not playing your mod because they want to spend hours upon hours of more time mindlessly mining.  They probably won't mind spending the same amount of time in early game that they would in vanilla, but they don't want to spend a ton of extra time in the early game, because your mod is competing for resources.  If your mod is going to compete for resources in the early game, make sure there is a fairly immediate benefit that makes up for it.  Things like more effective mining tools are more appropriate early on than later, once the player has already spent far too much time mining.  Providing the player with quality of life improvements early on is far more valuable than later.  Instead of making the enhanced tools purely late game items (like both Botania and Thaumcraft do), offer mildly enhanced tools early game and push back some of the more impressive content till a little later.  A pickaxe that can mine a 3x3 area that is easily accessible between the iron and diamond tiers is not game breaking at an expense slightly higher than iron, and players will appreciate it far more than many things mods offer at that point that are often more valuable later on.  Experienced players neither need nor want the long slow early game, and they certainly don't want it dragged out longer by your mods.  So instead of purely trying to add end-game content, also add some early game content that will make it a little easier and faster for seasoned players to get to your awesome late-game content.

Balancing game economies is tough by itself, but it is really easy to break a well designed game economy by throwing in new content without fully considering how it is going to affect the existing economy.  And this includes time as well as resources.  If you are making or considering making a mod, please keep in mind that every unit of a resource your mod uses is a unit of resource that cannot be used for anything else.  If your mod is going to compete with vanilla or another mod for resources, make sure your mod provides something to mitigate that, otherwise your players will be spending a lot more time doing things that are boring and grindy, instead of having fun with your mod.  And likewise, keep in mind that mod players are generally experienced.  They don't want to spent a ton of time in the early game because of your mod.  Throw them a bone.  It's not terribly difficult to speed up the early game a little bit without going too far.  Again, keep in mind that the sooner the player is able to really use your mod content, the more they will enjoy your mod.  The last thing you want is for players to spend so much time and energy on other mods that they do not have time to enjoy yours.  Instead, make your's the mod that gives them the time to play all of them.  Maintaining balance is tough when making games and when modding games, but if you make sure to pay attention where resources are coming from and how much time is required to obtain them, it is not terribly difficult to avoid seriously upsetting the balance.  We have a lot of very good mods out there, but with a little tweaking on economic balance, they could be absolutely epic.