10027 items (0 unread) in 75 feeds
Security
We released an advisory today to Bugtraq regarding a DOM-Based XSS bug I found in the Dojo Toolkit SDK 1.4.1 and earlier versions. The Dojo team was informed on February 19, 2010 and released the fix today along with some other security bugs. If you want some more information on this bug as well as the other bugs that were fixed, see their security bulletin.
The files identified with the XSS issues are primarily designed for testing; however a quick Google search will identify numerous sites that have deployed these files along with the core framework components. Unfortunately, this is evidence of a much larger issue. All too often, test code gets deployed to production and ultimately leads to a security exposure. This is clearly a recipe for disaster!!! Folks, please clean up your web root. You clean up your house when relatives come by, right? You wouldn’t want them tripping over your GI Joe’s and breaking their leg! It’s the same thing, more or less : )
Overview
The Dojo Toolkit is an open source modular JavaScript library/toolkit designed to ease the rapid development of cross platform, JavaScript/Ajax based applications and web sites. Multiple instances of DOM-based Cross Site Scripting (XSS) vulnerabilities were found in the _testCommon.js and runner.html files within the SDK. The XSS vulnerabilities appear to affect all websites that deploy any of the affected SDK files.
More information on DOM-based XSS can be found at OWASP’s site.
Technical Details
File: dojo-release-1.4.1-srcdojo-release-1.4.1-srcdijittests_testCommon.js
1) Data enters via “theme” URL parameter through the window.location.href property.
Line 25:
var str = window.location.href.substr(window.location.href.indexOf("?")+1).split(/#/);
..snip..
2) The “theme” variable with user-controllable input is then passed into “themeCss” and “themeCssRtl” which is then passed to document.write().
Writing the un-validated data to HTML creates the XSS exposure.
Line 54:
..snip..
var themeCss = d.moduleUrl("dijit.themes",theme+"/"+theme+".css");
var themeCssRtl = d.moduleUrl("dijit.themes",theme+"/"+theme+"_rtl.css");
document.write('<link rel="stylesheet" type="text/css" href="'+themeCss+'">');
document.write('<link rel="stylesheet" type="text/css" href="'+themeCssRtl+'">');
==================================================
File: dojo-release-1.4.1-srcdojo-release-1.4.1-srcutildohrunner.html
1) Data enters via “dojoUrl” or “testUrl” URL parameters through the window.location.search property.
Line 40:
var qstr = window.location.search.substr(1);
..snip..
2) The “dojoUrl” and “testUrl” variables with user-controllable input are passed to document.write(). Writing the un-validated data to HTML creates the XSS exposure.
Line 64:
document.write("<scr"+"ipt type='text/javascript' djConfig='isDebug: true' src='"+dojoUrl+"'></scr"+"ipt>");
..snip..
document.write("<scr"+"ipt type='text/javascript' src='"+testUrl+".js'></scr"+"ipt>");
Proof-of-Concept Exploit
This vulnerability can be exploited against websites that have deployed any of the 145 SDK files which reference _testCommon.js.
Reproduction Request:
http://WebApp/dijit/tests/form/test_Button.html?theme=”/><script>alert(/xss/)</script>
(Note: test_Button.html is one of the SDK files that includes the _testCommon.js file)
==================================================
This vulnerability can be exploited against any website that has deployed the runner.html file.
Reproduction Request:
http://WebApp/util/doh/runner.html?dojoUrl=’/>foo</script><’”<script>alert(/xss/)</script>
Recommendation
Update to Dojo Toolkit SDK 1.4.2
Jim Manico has produced another great addition to his OWASP podcast canon, the latest discussion is with Richard Bejtlich. Jim is very good as an interviewer which means the questions are all meat and potatoes on in the trenches issues.
One of the main points that Richard makes that is lost on many security programs is how to take information security concerns and then communicate them to the business. How do you talk about security to people (i.e. business) that could care less about SQL injection. As James McGovern says, the business doesn't want a maturity model, they want working software.
Richard talks about extending the communication through using threats, and that this is a way to put a face on the problem. I have no doubt that this works well. The BBC show "Spooks" (called MI-5 in the US) is a pretty detailed (for a TV show) look at counter terrorism in the UK, they get into a lot of hidden assumptions we have about the intersection of security and privacy. One of the criticisms of the show is that it looks like all the problems are solved in one hour by the same three people. And this is one issue I have with using threats as the primary means for communicating security concerns to the business. I have no doubt its effective, and its for sure an important part of telling the story, but I think some aspects are not addressed if there's an overfocus on threats. Threats must be assumed but its resilience and survivability that matter in the end and that goes back to your company's mission.
I came up originally looking at security as something that we solve through equal parts access control, defensive coding, and crypto. Those are still the basic workhorses of most software security regimes, but there is a missing piece. For me, Richard's work going back Tao of Security Monitoring is the best distillation that made me realize that all of the above areas must be backstopped by a robust detection and response lifecycle, or what Richard calls "Building Visibility In"
So in terms of building visibility in, every process that we design/code for should have a "monitor first" mandate. We saw the lack of this just recently with the Chip and PIN fiasco. There are real challenges to getting the right amount of visibility in the app. Where you put the detection determines what you see. On the presentation layer it looks like raw HTTP, at the middle tier it looks more transaction-like and at the DAO layer you can observe the data operations. In the secure audit logging class I teach we go through each of these areas and its very interesting to see what you can see from these different angles, just like turning a Rubiks cube.
Jim and Richard explore a couple of other areas - issues around incidents/compliance for funding (for which I propose the need for a flat tax). Jim asks about how attackers have advantage, and Richard responds with his black hat budget, in other words what can the bad guys do with a fraction of your assets.
Jim asked Richard a question I sent in - "The trustworthiness of a digital asset is limited by the owner's capability to detect incidents compromising the integrity of that asset." Given that we don't have any high integrity database, identities or application servers - how do you detect a breach of integrity when there is no verifiable integrity in the system in the first place?"
Richard's response is that trustworthiness impossible inside an asset itself (agree)- for an asset to defend itself look outside of the asset. The network is a cheap way to watch. That logic makes perfect sense to me, but it still makes sense to push for more and better data out of the apps. There is a lot of context there about transactions, data, identity and so on that can be harvested.
I quite liked the final challenge that Richard threw down - enterprises need to focus on getting real data. How many of us have an accurate scoreboard based on real data?
Bill Gross is the manger of the world's largest bond fund, his quarterly letters contain many insights on the economy as a whole. This one is no exception, and it contains a typically witty yet telling story, about how much people at cocktail parties care about what you are saying as opposed to themselves.
In his last letter in January, Gross took the UK to task for being among the high risk members of the dubious Debt Ring of Fire club:During that unbearable minute-and-a-half, however, you’re likely to have covered some of the following topics:
1. Where are you from? (If it’s not a place where I’ve been or have a distant second cousin – don’t care.)
2. How’s the family? (If Johnnie is in advanced placement courses and my kids aren’t – don’t care. Don’t care about your kids’ soccer games either or that upcoming wedding.)
3. Medical problems. (Unless you’re dying from cancer – don’t care. Your artificial hip and kidney stone stories are important only to let me tell you about mine.)
4. How’s work? (Forgot where you work, but it’s a good lead in. Don’t really care though unless you can direct some business my way.)
5. Can you believe Tiger? (Now there’s something I care about, but the wife is only five feet away.)
Like high ranking central bankers everywhere, Bank of England Governor Mervyn King has been reassuring the financial world that their investments in the UK are safe. Gross has an interesting take on this:the U.K. is a must to avoid. Its Gilts are resting on a bed of nitroglycerine. High debt with the potential to devalue its currency present high risks for bond investors. In addition, its interest rates are already artificially influenced by accounting standards that at one point last year produced long-term real interest rates of 1/2 % and lower.
Don't care is a particularly useful precept for security architects to keep in mind. You are assessing a company's product and they have a slide on their security that features a large number of security protocols. Don't care. Need to lift the hood. You are using Chip *and* PIN so your authentication is stronger? Don't care. Let's look at the tokens used for authorization, the authorization, audit logging, and so on.Just last week Bank of England Governor Mervyn King said that it would be difficult to cut government spending quickly, but that there needs to be a clear plan for doing so. Not good enough, Mr. King. Don’t care. Show investors the money, not vice-versa. An investor’s motto should be, “Don’t trust any government and verify before you invest.”
You are sending my Web services requests via XML message data to my service's application methods and you are using SSL to secure the channel, so you think that should suffice for security?
Don't care. Make sure the message has integrity, give me a security token, a way to authenticate the request, authorize and audit it. Why should I trust the data and the method request simply because they were sent over SSL? If someone sent you a message over SSL and told you to jump off a bridge would you do it?So the mantra isn't "Trust but Verify", its "Don't Trust and Verify."
Verification along the lines of static analysis, fuzzing, and other means is still required. Verification is done because of complexity and to ensure linkage between design time intent and run time reality. But verification is not an adequate substitute for trust.
Security budgets are often based on combination of last year's spending, this year's threat du jour(s), and "best" practices, i.e. what everyone else is doing. None of these help to address the main goal of information security which is to protect the assets of the business. The normal security budgeting process results in overspending (as a percentage) on network security, because that's how the budget grew organically starting from the 90s.
A simple three step process to achieving a Security Budget that maps to business reality rather than security silver bullet fantasies is as follows:
Step 1. Gather the relevant data for where the enterprise is investing its dollars in IT. Let's assume our company is Jones Widgets.
Step 2. Apply a "flat tax" for security budgeting, for this example let's say 7%, so if Jones Widgets invests $5M in its Customer relationship systems, $2M in Order Management, and $1M in ERP, this is the starting point for assigning priorities on security budgets. This is the part that security people miss, you don't need to do asset valuation - there is a whole group of people in the business that have already done that for you. Your job is to enable the intent that they have already clearly communicated in budget decisions.
So applying the flat tax, our Jones Widget's budget look like this
| IT System | IT Budget | Initial InfoSec Budget |
| Customer Systems | $5M | $350k |
| Order management | $2M | $140k |
| ERP | $1M | $70k |
Notice that the starting point in this step is aligning the budget with overall Enterprise IT spending. Its not based on whatever area that infosec happened to invest in last year, or what someone at a conference said, its about starting by aligning with what your business values. Its not about security foo-fa-ra, its about Jones Widgets.
Step 3. Efficacy. Let's assume that the Customer Management and ERP systems are behemoth packages that are purchased third party apps, and the Order management system is built in house so you have the source code. The way that you choose to deliver security to third party purchased systems versus the ones where you design, build, and deploy the code will vary. So the next step after initially rationalizing the budget is to assess what's the most effective security I can get for each area.
Its not that the business budget should trump the infosec budget, but its a very useful starting point. Moving off of those priorities should require a statement of efficacy that some security dollars are better spent in say the Order Management system, because the company controls the code. So if Jones Widgets' Order Management system is built in house, and the business relies on that to process orders, if that Order Management asset is compromised then its not like Jones Widgets can go and buy another Order system off the shelf from a vendor. Its their core business, their DNA.
So let's assume that Jones Widgets wants to scan its code, invest time in threat modeling and so on for its core business asset. This results in pulling 20% in from the ERP and Customer systems
| IT System | IT Budget | Updated InfoSec Budget |
| Customer Systems | $5M | $280k |
| Order management | $2M | $224k |
| ERP | $1M | $56k |
There's no need to get wrapped around the axle on asset valuation, the business gives you a starting point, use it. Then only move away from that when you can make a concrete case on improving efficacy by altering priorities. Or put another way - its your job. Do it.
Just wanted to let everyone know that if you are headed to Blackhat USA 2010 this summer in
Las Vegas, we have just added a 1-day workshop on the day before the Briefings start -
http://www.blackhat.com/html/bh-us-10/training/bh-us-10-training_RB-WAFVirtPatch.html
In the workshop, we will be mainly discussing the "Virtual Patching" concept of using a
WAF (ModSecurity in this case) and we will use the OWASP WebGoat app as the target. In
the workshop, we will talk virtual patching theory and then have hands-on labs where we
will show how to use Mod to virtually patch the various WebGoat lessons. As a side note -
we will also have a section on the new CRS v2.0 when discussing negative security models.
So, if you want to come and dive into the deep-end of the pool and have fun using some of
ModSecurity's advanced features (such as Lua and Content Injection) then sign-up now!
Brian Rectanus and I hope to see you all in Vegas!!! :)
Learning about security means understanding types of risk, and investors, specifically value investors, have a long demonstrated track record of framing ways to think about asset protection and making it actionable. Recently I've been reading James Montier, very impressed with his approach which is based on a pretty rigid process and objective checklists, here is an excerpt from a recent interview:
In the infosec world the "seductive details" are threats, hollywood movie plots and the like that infosec people use to get funding. Meanwhile the real structural problems of the core assets (apps, data, identity) remain unaddressed whilst the security world chases the taillights of the latest threat du jour.Miguel: Let’s talk about the concept of seductive details…can you give us an example of how investors are trapped by irrelevant information?
James Montier: The sheer amount of irrelevant information faced by investors is truly staggering. Today we find ourselves captives of the information age, anything you could possibly need to know seems to appear at the touch of keypad. However, rarely, if ever, do we stop and ask ourselves exactly what we need to know in order to make a good decision.
Seductive details are the kind of information that seems important, but really isn’t. Let me give you an example. Today investors are surrounded by analysts who are experts in their fields. I once worked with an IT analyst who could take a PC apart in front of you, and tell you what every little bit did, fascinating stuff to be sure, but did it help make better investment decisions, clearly not. Did the analyst know anything at all about valuing a company or a stock, I’m afraid not. Yet he was immensely popular because he provided seductive details.
The airbag that's guaranteed to work unless you get in accident is of course the network firewall, which "protects" your system until someone tries to attack it.Miguel: Interestingly you connect the dangers of irrelevant information to modern risk management. I’m referring to your comments on Value at Risk – “VAR is fundamentally flawed after all it cuts off the very it of the distribution that we are interested in: the tails! This is akin to buying a car with an airbag that is guaranteed to work unless you have a crash…” Can you tell us more?
James Montier: Sure. Modern risk management is a farce; it is pseudoscience of the worst kind. The idea that the risk of an investment, or indeed, a portfolio of investments can be reduced to a single number is utter madness. In essence, the problem with risk management is that is assumes that volatility equals risk. Nothing could be further from the truth. Volatility creates opportunity. For instance, was the stock market more risky in 2007 or 2009? According to views of risk managers, 2007 was the less risky year, it had low volatility, which they happily fed into their risk models and concluded (falsely) that the world was a safe place to take risk. In contrast, these very same risk managers were staying that the world was exceptionally risky in 2009, and that one should be cutting back on risk. This is, of course, the complete opposite to what one should have been doing. In 2007, the evidence of a housing/credit bubble was plain to see, this suggested risk, valuations were high, it was time to scale back exposure. In 2009, bargains abounded, this was the perfect time to take ‘risk’ on, not to run away. Risk managers are the sorts of fellows that lend out umbrellas on fine days, and ask for them back when it starts to rain.
For some strange reason, infosec is far removed from business realities. The layers of seductive details about threats create an artificial separation between what infosec spends its money and time on versus what the business invests its money and time in.
By itself this misalignment would be a medium sized problem (there's plenty of wasteful IT spending, and infosec's penchant for overallocating on network toys is just another example). But what makes this a much larger problem is the lack efficacy of protection and detection mechanisms that only work so long as they are not attacked. The reason for this is that security architecture is removed from the core business assets (apps, data, identity) they are supposed to be protecting. Instead the protection and detection mechanisms must form fit to that which they are supposed to be protecting. The reasons air bags work is that they are very close to the asset they are protecting.
At RSA conference this week, I gave two talks on building a margin of safety into your software. In various conversations during the week at least 25 different people brought up to me (unprompted) that they "just used SSL for security on their web services". Chris Walsh immediately picked up on the preposition that says it all - "security on your web services" instead of course security in your web services. Of the legions of vendors on display, I could count on one hand the ones that help you get security in web services or anything else for that matter.
The other matter of course is the notion that the defender gets to choose the security model and define its efficacy. I find this notion a network security centric view at best; its quaint yet dangerous out moded thinking.
Web services are the primary way to integrate whether its web server to ESB or mobile device to web server. The attack surface is typically comprised of the HTTP channel, some application methods like HTTP verbs URLs, URIs, and the data like XML.
If you put SSL on your web service, then what confidence, if any, should the recipient have in the Data and Method? Where did it originate? What is protecting it? Has it been tampered with? and so on. These are all open, unaddressed questions, and the real problem is that blithely stating "we use SSL on our web services" is at best an opening in the security chess match, its not the end game, its the beginning of the game and the attacker has the next move. If your only web service security is on the channel, then there are vast spaces for the attacker to operate in.
As the Cole Porter song goes -
Putting SSL on your web service and calling it good leaves acres of space for attackers to roam How does this all end? I think we know. In the 90s people wrote web apps with similarly naive network centric trust models, and then they started to discover that their opening move of SSL and firewalls did zippo to defend against XSS, SQL Injection and friends. The defender's opening move does not decide the game, particularly when its weakly mapped to only one part of the attack surface (the communication channel). It took a few years for attackers to find all those holes left open in the web apps, and web services have been the dominant integration technology for mobile and other areas for a few year now, its just a matter of time til the naive trust on SSL network security breaks down. If you want to get busy on solving problems now, consider getting down to the message level as quickly as possible,Give me land lots of land, under starry skies above
Don't fence me in
Let me ride through the wide open country that I love
Don't fence me in
Together with the release of PHP 5.3.2 by the PHP team I have released Suhosin-Patch 0.9.9.1 which comes with bugfixes and new features. The changes are:
While going through the HTTP_REFERER log of the Month of PHP Security website I realised that there are more incoming refers from various blog posts about it than there are submissions to drawing@php-security.org. Like I previously announced we will honor 10 blog postings with 25 EUR amazon coupons. The winners will be selected by random, however only among those we will select that announce their blogpost to us via the email address provided above.
The reasons for this rule is very simple. Without the announcement we would have to look at every new HTTP_REFERER and manually check if it is just spam, an old link to the Month of PHP Bugs, someone who just copied the blog of another person or other nonsense. In addition to that we have to find a contact address of the person who originally has written the entry and ask him/her if he/she wants to take part in the drawing. This would be too much work. Therefore announce your blog posting to drawing@php-security.org or you have no chance of winning one of the coupons.
There's a lot of room for innovation as companies move from RBAC to Claims Based access control“This is a two day XACML introduction course, including hands-on training. It will be provided by leading XACML experts with in-depth experience from some of the world’s largest XACML deployment projects. Based on their attendee experience, there will be a mix between high-level aspects and technical details. We cover best practices and discuss how you avoid common pitfalls in the deployment of an Attribute Based Access Control (ABAC) solution. However, we also ensure you get a thorough understanding of the XACML request/response and policy languages. You will create and debug your own XACML policies and run access requests against them to verify that you get the response you expect.”
BSIMM2 is the 30 firm version of BSIMM. I wrote up an article with Brian Chess and Sammy Migues (my BSIMM co-creators) called “Software [In]security: What Works in Software Security — Fifteen Common Activities from BSIMM2.” In addition to highlighting the fifteen most common BSIMM activities, the article also provides the 30 firm data for all 110 activities in public for the first time.
We’re unveiling some statistical results at RSA this week that will enhance and expand the dataset published in the article. We’ll do an official BSIMM2 launch within the next couple of months.
The MSRC Engineering team has been investigating reports of a vulnerability involving the use of VBScript and Windows Help files.
What is the impact and affected platforms?
Our investigation has determined that Windows 7, Windows Server 2008, and Windows Vista are not impacted. Only Windows 2000 and Windows XP are impacted by default. Windows 2003 Server is also impacted, but the issue is mitigated in the default configuration due to the presence of the Internet Explorer Enhanced Security Configuration. With this issue, it is possible for a malicious web page to display a dialog box which will trigger the execution of arbitrary code when the user presses the F1 key. The prompt can appear repeatedly when dismissed, nagging the user to press the F1 key. Platforms are affected regardless of the Internet Explorer version installed.
How would a malicious user leverage this vulnerability?
Windows Help files are an inherently unsafe file format. That means these files can run arbitrary code, thus the browser must prevent remote Windows Help files from executing automatically.
VBScript functionality available from within Internet Explorer exposes the MsgBox function, allowing script on a web page to display a message to the user. The parameters supplied to the MsgBox function may reference an associated Window Help file, though this functionality is limited when VBScript is used within the browser. Though user interaction is required the F1 keyboard shortcut does enable an attack scenario. In the exploit, a file path enables a .HLP file to be loaded from the local filesystem, SMB, or WebDav.
Workarounds
As an interim workaround, users are advised to avoid pressing F1 on dialogs presented from web pages or other Internet content. If a dialog box appears repeatedly in an attempt to convince the user to press F1, users may log off the system or use Task Manager to kill the Internet Explorer process.
It is also possible to use the following command line to lock down the legacy Windows Help system, preventing it from loading:
cacls "%windir%winhlp32.exe" /E /P everyone:N
Command line to roll back this change:
cacls "%windir%winhlp32.exe" /E /R everyone
As this vulnerability is driven by scripting, the following standard workarounds apply as well:
|
The Group Policy setting to “Turn off displaying the Internet Explorer Help Menu” under the Category Path “Computer ConfigurationAdministrative TemplateWindows ComponentsInternet Explorer” is not a sufficient mitigation for this issue.
Acknowledgements
Thanks to Robert Hensing for his work on the issue.
-David Ross, MSRC Engineering
A very interesting and meritorious effort on stock spam from the folks at Motley Fool.
First off a little background, the Fool has a game called CAPS, you can think of this like fantasy baseball, but its for picking stocks. So you pick a stock like say MMM and you enter whether or not you think it will out perform or under perform the S&P index over some period of time. Then you get points if you are right and by how much it over performs or under performs. There are over 69,000 players. (*)
So its a pretty straightforward concept, you get points for picking the right stocks. Now with that background, here is the part of interest to security. You know the gajillion stock spam messages you get typically around small cap penny stocks that you've never heard of (and wish you never had)? Well, two Fools set up an account TMFStockSpam, they take the penny stock fraud/spam messages, enter them into the CAPS engine as picks that they shorting (meaning they predict they'll go down - "red thumbing" in CAPS parlance).
TMFStockSpam has 20 picks since 12/15/09, they have shorted them all. 80% of these have underpeformed the S&P. Four of the 20 have actually generated positive returns (+2, +2, +14, 27%)
The other 16 have generated negative returns with the worst being BRGO.OB -89.5%, a recent pick from 2/23 (RCYT.OB) has lost -44.8% from 2/23-2/26.
Anyway, its interesting data on stock spam, and they are also asking for people to send them any stock offers that you receive so they can track them
Oh one more thing the TMFStockSpam CAPS player is ranked 5,368 out of 69,524 players
* note that the CAPS community as a whole has outperformed the S&P index over its life, something the various misguided MBA programs that drunk the efficient Market Hypothesis kool aid by the gallon would say is impossible, but which does explain why fully 80% of mutual funds (run by these same MBA grads) under perform the S&P *before* fees
Interesting annual shareholder letter from Eddie Lampert at Sears Holdings:
Making Sense of Business and Policy
I just finished Thomas Sowell’s most recent book, Intellectuals and Society. For those not familiar with his writings, Thomas Sowell is one of the clearest and most insightful writers of our era. I look forward to every book and column he publishes. In this book, he discusses the “vision of the anointed” and how their views shape society regardless of their merit. He describes how often these views conflict with reality without altering these views and, paradoxically, sometimes strengthening them. I couldn’t help noticing the parallels between his comments and the “vision of the anointed” in the financial and business world over the past few years.
Business leaders, regulators, public officials, and journalists have become an echo chamber of self-support and self-congratulation, whether on TV, in print or at numerous conferences. Their words and their actions are often self-serving (whether right or wrong), and they are typically regarded and reported on as if they were obvious and selfless. They get repeated as if there were no alternative views or possibility of error in their thinking. Dominant narratives develop and get defended primarily by repetition and secondarily by attacks on those who disagree with those narratives. When these favored people and views become endorsed in laws and regulations, some may benefit, but many get harmed.
Two days ago I installed a mail client on my reinstalled desktop system that was not doing anything for 2 month and checked mails of the hardened-php account that were not checked for 2 months. Usually noone uses this email account to contact me, but the Suhosin bug reports sometimes end up there. While killing thousands of SPAM messages I also found a message from the Debian PHP maintainers, dating back to the 10th February 2010, telling me about a crash problem inside the Suhosin patch. The email also contained their solution to the problem: a patch for the suhosin patch. You can view this patch here. However you should not commit this patch to your PHP because it does not solve the problem correctly.
I previously blogged about one of the new features in Suhosin Patch for PHP 5.3.x. It is now possible to adjust several internal features by setting certain environment variables on startup. This includes the memory manager canary protection, the sanitization of free memory blocks, the protection of linked lists and hashtables. When a Suhosin patched PHP starts the environment variables are evaluated and the suhosin config is written into a variable called suhosin_config.
It should be obvious that this kind of feature comes with a little problem. Certain bytes in memory now control if Suhosin’s internal memory protections are activated or not. This means that a memory corruption vulnerability in PHP could be used by an attacker to overwrite the config variable and disable the security. Because of this Suhosin Patch tries to align the suhosin_config variable to a page boundary and then set it to read only.
/* hack that needs to be fixed */
#ifndef PAGE_SIZE
#define PAGE_SIZE 4096
#endif
#ifdef ZEND_WIN32
__declspec(align(PAGE_SIZE))
#endif
char suhosin_config[PAGE_SIZE]
#if defined(__GNUC__)
__attribute__ ((aligned(PAGE_SIZE)))
#endif
;
static void suhosin_write_protect_configuration()
{
#if defined(__GNUC__)
mprotect(suhosin_config, PAGE_SIZE, PROT_READ);
#endif
}
The implementation has some problems. First of all it only works in case of a GNU C compiler. The second and more serious problem is that it assumes that the PAGE_SIZE is smaller than or equal to 4096. Otherwise mprotect() will not correctly work. On systems where the PAGE_SIZE is bigger than 4096 the mprotect() will either fail or set too many bytes to read only. In case of a write access after the suhosin_config variable this can lead to a crash.
The Debian people saw this crash on some architectures and reacted with a patch. However they did misunderstand the security idea behind it and therefore their patch looks like this.
char *suhosin_config = NULL;
static void suhosin_write_protect_configuration()
{
#if defined(__GNUC__)
mprotect(suhosin_config, sysconf(_SC_PAGESIZE), PROT_READ);
#endif
}
...
if (!suhosin_config) {
suhosin_config = mmap(NULL, sysconf(_SC_PAGESIZE), PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
if (suhosin_config == MAP_FAILED) {
perror("suhosin");
_exit(1);
}
}
The Debian maintainers tried to fix the problem by replacing the aligned suhosin_config variable with a pointer. They then allocate a single memory mapped page and set it to read only. While this fixes the possible crash it shows that the Debian PHP maintainers did not fully understand the idea behind that code. The patch ensures that the suhosin configuration is set to read only, but now a memory corruption exploit can just overwrite the suhosin_config pointer and let it point to a memory area that contains a new configuration.
A correct fix would be to check if the dynamic page size is indeed bigger than 4096 and in this case just warn the user that he should recompile PHP with a bigger PAGE_SIZE definition and do not set the variable to read only in this case. But this might arise the next problem that the PAGE_SIZE might exceed the maximum alignment that the compiler supports.
UPDATE: I rewrote several parts of this blog entry to make it less critic and sound less aggressive. I spent the day discussing possible fixes and other problems with the current solution. The current solution is also not safe in all cases (all OS/architectures/compilers) because of intermediate pointers introduced by the compiler that are invisible at the C level. The solution to this is that the runtime configurability of Suhosin will become optional and can be selected at compile time. If the runtime configurability is selected the sysconf() method will be used to determine the correct page size. The pointer however will be protected by pointer obfuscation/encryption and maybe checksums.