homepage
Open menu
Go one level top
  • Train and Certify
    Train and Certify

    Immediately apply the skills and techniques learned in SANS courses, ranges, and summits

    • Overview
    • Courses
      • Overview
      • Full Course List
      • By Focus Areas
        • Cloud Security
        • Cyber Defense
        • Cybersecurity and IT Essentials
        • DFIR
        • Industrial Control Systems
        • Offensive Operations
        • Management, Legal, and Audit
      • By Skill Levels
        • New to Cyber
        • Essentials
        • Advanced
        • Expert
      • Training Formats
        • OnDemand
        • In-Person
        • Live Online
      • Course Demos
    • Training Roadmaps
      • Skills Roadmap
      • Focus Area Job Roles
        • Cyber Defence Job Roles
        • Offensive Operations Job Roles
        • DFIR Job Roles
        • Cloud Job Roles
        • ICS Job Roles
        • Leadership Job Roles
      • NICE Framework
        • Security Provisionals
        • Operate and Maintain
        • Oversee and Govern
        • Protect and Defend
        • Analyze
        • Collect and Operate
        • Investigate
        • Industrial Control Systems
    • GIAC Certifications
    • Training Events & Summits
      • Events Overview
      • Event Locations
        • Asia
        • Australia & New Zealand
        • Latin America
        • Mainland Europe
        • Middle East & Africa
        • Scandinavia
        • United Kingdom & Ireland
        • United States & Canada
      • Summits
    • OnDemand
    • Get Started in Cyber
      • Overview
      • Degree and Certificate Programs
      • Scholarships
    • Cyber Ranges
  • Manage Your Team
    Manage Your Team

    Build a world-class cyber team with our workforce development programs

    • Overview
    • Why Work with SANS
    • Group Purchasing
    • Build Your Team
      • Team Development
      • Assessments
      • Private Training
      • Hire Cyber Professionals
      • By Industry
        • Health Care
        • Industrial Control Systems Security
        • Military
    • Leadership Training
  • Security Awareness
    Security Awareness

    Increase your staff’s cyber awareness, help them change their behaviors, and reduce your organizational risk

    • Overview
    • Products & Services
      • Security Awareness Training
        • EndUser Training
        • Phishing Platform
      • Specialized
        • Developer Training
        • ICS Engineer Training
        • NERC CIP Training
        • IT Administrator
      • Risk Assessments
        • Knowledge Assessment
        • Culture Assessment
        • Behavioral Risk Assessment
    • OUCH! Newsletter
    • Career Development
      • Overview
      • Training & Courses
      • Professional Credential
    • Blog
    • Partners
    • Reports & Case Studies
  • Resources
    Resources

    Enhance your skills with access to thousands of free resources, 150+ instructor-developed tools, and the latest cybersecurity news and analysis

    • Overview
    • Webcasts
    • Free Cybersecurity Events
      • Free Events Overview
      • Summits
      • Solutions Forums
      • Community Nights
    • Content
      • Newsletters
        • NewsBites
        • @RISK
        • OUCH! Newsletter
      • Blog
      • Podcasts
      • Summit Presentations
      • Posters & Cheat Sheets
    • Research
      • White Papers
      • Security Policies
    • Tools
    • Focus Areas
      • Cyber Defense
      • Cloud Security
      • Digital Forensics & Incident Response
      • Industrial Control Systems
      • Cyber Security Leadership
      • Offensive Operations
  • Get Involved
    Get Involved

    Help keep the cyber community one step ahead of threats. Join the SANS community or begin your journey of becoming a SANS Certified Instructor today.

    • Overview
    • Join the Community
    • Work Study
    • Teach for SANS
    • CISO Network
    • Partnerships
    • Sponsorship Opportunities
  • About
    About

    Learn more about how SANS empowers and educates current and future cybersecurity practitioners with knowledge and skills

    • SANS
      • Overview
      • Our Founder
      • Awards
    • Instructors
      • Our Instructors
      • Full Instructor List
    • Mission
      • Our Mission
      • Diversity
      • Scholarships
    • Contact
      • Contact Customer Service
      • Contact Sales
      • Press & Media Enquiries
    • Frequent Asked Questions
    • Customer Reviews
    • Press
    • Careers
  • Contact Sales
  • SANS Sites
    • GIAC Security Certifications
    • Internet Storm Center
    • SANS Technology Institute
    • Security Awareness Training
  • Search
  • Log In
  • Join
    • Account Dashboard
    • Log Out
  1. Home >
  2. Blog >
  3. PHP Weak Typing Woes #8212: With Some Pontification about Code and Pen Testing
370x370_Joshua-Wright.jpg
Joshua Wright

PHP Weak Typing Woes #8212: With Some Pontification about Code and Pen Testing

December 18, 2014

The other day I was reading Jos Wetzels' post on the Full Disclosure mailing list regarding a vulnerability in the open source social networking kit HumHub. One of the issues he pointed out was a PHP 'type juggling' attack where an attacker can force a password reset against HumHub for a user many times until a specific value is selected that reduces the password entropy (uniqueness), allowing her to access accounts without authorization.

I have not previously worked with HumHub, but the illustrative code Jos pointed out was intriguing (press CTRL+C to close the cat output after the closing PHP ?> tag):

$ cat >bahhumhubbug.php 
 <?php 
 if (md5('240610708') == md5('QNKCDZO')) {  print "Yes, these are the same values.\n"; 
} 
 ?> 
$ php bahhumhubbug.php 
Yes, these are the same values.

Huh? No, those are not the same values:

$ echo -n 240610708 | md5sum 
0e462097431906509019562988736854
$ echo -n QNKCDZO | md5sum 
0e830400451993494058024219903391

The issue here is related to how PHP performs type checking. Being the friendly language it is, PHP attempts to convert variables of different types in a way that makes comparison work as the programmer might expect*. For example, consider this "math":

$ cat >math.php
<?php print('5' + 8); ?>
$ php math.php
13

Here, PHP adds a string '5' to the integer 8. This is intuitive for a lot of people, since 5+8 is indeed 13. The magic of PHP is that these two values are of different types, but PHP accommodates the addition anyway. Contrast this with a strong typed language like Python:

$ python -c "print '5' + 8"
Traceback (most recent call last):
  File "<string>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects</module></string>

PHP is convenient in this way; if you accept a numeric input in a HTTP POST value, for example, you can treat it as an integer if it fits any of the loose typing rules PHP uses for integers. For beginning programmers, this allows them to sidestep any type conversion routines necessary to force data into a specific type.

This is all well and good... until it's not. Let's revisit Jos' code example from before. Why are the two MD5 output values equal to PHP? Because PHP thinks they are numbers:

$ echo -n 240610708 | md5sum
0e462097431906509019562988736854
$ echo -n QNKCDZO | md5sum
0e830400451993494058024219903391

PHP sees a number (0), followed by the letter "e", and it converts the MD5 string to exponential notation (e.g. 0462097431906509019562988736854). Because both MD5 hashes start with "0e", they both evaluate to 0, making them numerically equivalent.

In the case of HumHub, an attacker can force a password reset without authentication. HumHub selects a new password using a variety of techniques (which is also problematic, as pointed out by Jos) and MD5 hashes it. If the resulting password hash starts with one or more zeros, followed by "e" and the rest of the characters are numeric, then an attacker can login with the password "0". If the password hash does not match this criteria, the attacker resets it again and keeps trying until they can login.

I posted a note about this on Twitter the other day, and one response from @nicoduck reminding people to stop using MD5 was awesome:

Tweet_1

Since SHA1 hashes are longer than MD5 hashes, it is less likely that a randomly selected value will meet the 0 + e + digits rule for PHP to evaluate it as an exponential value. I left this Python code running on my Mac overnight to test SHA1 hashes for this pattern:

>>> import hashlib, string, itertools, re
>>> for word in itertools.imap(".join,
itertools.product(string.uppercase + string.lowercase +
string.digits, repeat=8)):
... if re.match(r'0+[eE]+\d+$',
hashlib.sha1(word).hexdigest()):
... print word
...

The itertools.imap() call returns a Python iterable object that consists of all the string combinations of upper and lowercase letters and numbers up to 8 characters in length. Each "word" is SHA1 hashed and compared to a regular expression to see if it meets the 0 + e + digits requirement. This routine is only single-threaded, but it was late at night and I was ready for bed.

In the morning, I awoke to this output:

AAJd1x3j
AAPkbYlH
AAZlIwOZ

Sure enough, all these strings SHA1 hash to what PHP would consider exponential numbers:

$ echo -n AAPkbYlH | sha1sum 
0e51223820731210116366152413868569204545  -
$ echo -n AAJd1x3j | sha1sum 
00e6811279456694288001763399976992804485  -
$ echo -n AAZlIwOZ | sha1sum 
0e13965443605273185827757762777509208778  -
$ cat p.php 
<?php var_dump((sha1('AAPkbYlH') == sha1('AAJd1x3j')) ==
sha1('AAZlIwOZ')); ?>
$ php p.php 
bool(true)

The Fix

My good friend Tom Hessman pointed out that this problem is not inherent in the PHP "===" operator:

$ sed -i php 's/==/===/' bahhumhubbug.php 
$ cat bahhumhubbug.php 
<?php
if (md5('240610708') === md5('QNKCDZO')) {
     print "Yes, these are the same values.\n";
}
?>
$ php bahhumhubbug.php 
$

The "===" operator returns true only when the values are equivalent and are of the same type. That said, I'd be willing to bet that other PHP projects are vulnerable to similar types of bugs, judging from the popular use of "==" in PHP projects.

As an instructor, I know a lot of pen testers out there get to a point in their careers where they are great at using tools, but lack coding skills. Coding isn't for everyone**, but if you want to be a great penetration tester, you need to be able to read code from time to time. I'm not recommending you print out the source code to a popular web app and sit down with a good cup of coffee and read it end-to-end. However, you should be able to make judicious use of grep (or findstr.exe, I won't judge) and search through source to find interesting bits of information that is worth a second look. Understanding tidbits about the language you are looking at (like the difference between "==" and "===" in PHP) can be extremely useful:

$ egrep -R "md5|sha" * | grep '=='
helpdesk/helpdesk-admin/login.php:
     if(sha1($_POST['password']) == $admin_password) {

Uh-oh.

-Joshua Wright
@joshwr1ght

*As "some programmers" might expect. This programmer finds this weak typing thing bizarre.
**Coding isn't for everyone, unless you sign up for Mark Baggett's SANS SEC573: Python for Penetration Testers class. You'd be amazed at how much you can get done with a little Python!

Share:
TwitterLinkedInFacebook
Copy url Url was copied to clipboard
Subscribe to SANS Newsletters
Receive curated news, vulnerabilities, & security awareness tips
United States
Canada
United Kingdom
Spain
Belgium
Denmark
Norway
Netherlands
Australia
India
Japan
Singapore
Afghanistan
Aland Islands
Albania
Algeria
American Samoa
Andorra
Angola
Anguilla
Antarctica
Antigua and Barbuda
Argentina
Armenia
Aruba
Austria
Azerbaijan
Bahamas
Bahrain
Bangladesh
Barbados
Belarus
Belize
Benin
Bermuda
Bhutan
Bolivia
Bonaire, Sint Eustatius, and Saba
Bosnia And Herzegovina
Botswana
Bouvet Island
Brazil
British Indian Ocean Territory
Brunei Darussalam
Bulgaria
Burkina Faso
Burundi
Cambodia
Cameroon
Cape Verde
Cayman Islands
Central African Republic
Chad
Chile
China
Christmas Island
Cocos (Keeling) Islands
Colombia
Comoros
Cook Islands
Costa Rica
Croatia (Local Name: Hrvatska)
Curacao
Cyprus
Czech Republic
Democratic Republic of the Congo
Djibouti
Dominica
Dominican Republic
East Timor
East Timor
Ecuador
Egypt
El Salvador
Equatorial Guinea
Eritrea
Estonia
Ethiopia
Falkland Islands (Malvinas)
Faroe Islands
Fiji
Finland
France
French Guiana
French Polynesia
French Southern Territories
Gabon
Gambia
Georgia
Germany
Ghana
Gibraltar
Greece
Greenland
Grenada
Guadeloupe
Guam
Guatemala
Guernsey
Guinea
Guinea-Bissau
Guyana
Haiti
Heard And McDonald Islands
Honduras
Hong Kong
Hungary
Iceland
Indonesia
Iraq
Ireland
Isle of Man
Israel
Italy
Jamaica
Jersey
Jordan
Kazakhstan
Kenya
Kiribati
Korea, Republic Of
Kosovo
Kuwait
Kyrgyzstan
Lao People's Democratic Republic
Latvia
Lebanon
Lesotho
Liberia
Liechtenstein
Lithuania
Luxembourg
Macau
Macedonia
Madagascar
Malawi
Malaysia
Maldives
Mali
Malta
Marshall Islands
Martinique
Mauritania
Mauritius
Mayotte
Mexico
Micronesia, Federated States Of
Moldova, Republic Of
Monaco
Mongolia
Montenegro
Montserrat
Morocco
Mozambique
Myanmar
Namibia
Nauru
Nepal
Netherlands Antilles
New Caledonia
New Zealand
Nicaragua
Niger
Nigeria
Niue
Norfolk Island
Northern Mariana Islands
Oman
Pakistan
Palau
Palestine
Panama
Papua New Guinea
Paraguay
Peru
Philippines
Pitcairn
Poland
Portugal
Puerto Rico
Qatar
Reunion
Romania
Russian Federation
Rwanda
Saint Bartholemy
Saint Kitts And Nevis
Saint Lucia
Saint Martin
Saint Vincent And The Grenadines
Samoa
San Marino
Sao Tome And Principe
Saudi Arabia
Senegal
Serbia
Seychelles
Sierra Leone
Sint Maarten
Slovakia
Slovenia
Solomon Islands
South Africa
South Georgia and the South Sandwich Islands
South Sudan
Sri Lanka
St. Helena
St. Pierre And Miquelon
Suriname
Svalbard And Jan Mayen Islands
Swaziland
Sweden
Switzerland
Taiwan
Tajikistan
Tanzania
Thailand
Togo
Tokelau
Tonga
Trinidad And Tobago
Tunisia
Turkey
Turkmenistan
Turks And Caicos Islands
Tuvalu
Uganda
Ukraine
United Arab Emirates
United States Minor Outlying Islands
Uruguay
Uzbekistan
Vanuatu
Vatican City
Venezuela
Vietnam
Virgin Islands (British)
Virgin Islands (U.S.)
Wallis And Futuna Islands
Western Sahara
Yemen
Yugoslavia
Zambia
Zimbabwe

By providing this information, you agree to the processing of your personal data by SANS as described in our Privacy Policy.

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

Tags:
  • Penetration Testing and Red Teaming

Related Content

Blog
Penetration Testing and Red Teaming, Cybersecurity and IT Essentials
January 4, 2023
Cloud Scanning for Vulnerability Discovery
In this article we'll look at the step-by-step process of scanning a cloud provider's network for target enumeration.
370x370_Joshua-Wright.jpg
Joshua Wright
read more
Blog
powershell_option_340x340.jpg
Cyber Defense, Penetration Testing and Red Teaming
July 1, 2022
Month of PowerShell: 5 Tips for Getting Started with PowerShell
In this article I'll talk about the 5 tips that helped me get started with PowerShell. I encourage you to follow along!
370x370_Joshua-Wright.jpg
Joshua Wright
read more
Blog
Untitled_design-43.png
Digital Forensics and Incident Response, Cybersecurity and IT Essentials, Industrial Control Systems Security, Purple Team, Open-Source Intelligence (OSINT), Penetration Testing and Red Teaming, Cyber Defense, Cloud Security, Security Management, Legal, and Audit
December 8, 2021
Good News: SANS Virtual Summits Will Remain FREE for the Community in 2022
They’re virtual. They’re global. They’re free.
370x370-person-placeholder.png
Emily Blades
read more
  • Register to Learn
  • Courses
  • Certifications
  • Degree Programs
  • Cyber Ranges
  • Job Tools
  • Security Policy Project
  • Posters & Cheat Sheets
  • White Papers
  • Focus Areas
  • Cyber Defense
  • Cloud Security
  • Cybersecurity Leadership
  • Digital Forensics
  • Industrial Control Systems
  • Offensive Operations
Subscribe to SANS Newsletters
Receive curated news, vulnerabilities, & security awareness tips
United States
Canada
United Kingdom
Spain
Belgium
Denmark
Norway
Netherlands
Australia
India
Japan
Singapore
Afghanistan
Aland Islands
Albania
Algeria
American Samoa
Andorra
Angola
Anguilla
Antarctica
Antigua and Barbuda
Argentina
Armenia
Aruba
Austria
Azerbaijan
Bahamas
Bahrain
Bangladesh
Barbados
Belarus
Belize
Benin
Bermuda
Bhutan
Bolivia
Bonaire, Sint Eustatius, and Saba
Bosnia And Herzegovina
Botswana
Bouvet Island
Brazil
British Indian Ocean Territory
Brunei Darussalam
Bulgaria
Burkina Faso
Burundi
Cambodia
Cameroon
Cape Verde
Cayman Islands
Central African Republic
Chad
Chile
China
Christmas Island
Cocos (Keeling) Islands
Colombia
Comoros
Cook Islands
Costa Rica
Croatia (Local Name: Hrvatska)
Curacao
Cyprus
Czech Republic
Democratic Republic of the Congo
Djibouti
Dominica
Dominican Republic
East Timor
East Timor
Ecuador
Egypt
El Salvador
Equatorial Guinea
Eritrea
Estonia
Ethiopia
Falkland Islands (Malvinas)
Faroe Islands
Fiji
Finland
France
French Guiana
French Polynesia
French Southern Territories
Gabon
Gambia
Georgia
Germany
Ghana
Gibraltar
Greece
Greenland
Grenada
Guadeloupe
Guam
Guatemala
Guernsey
Guinea
Guinea-Bissau
Guyana
Haiti
Heard And McDonald Islands
Honduras
Hong Kong
Hungary
Iceland
Indonesia
Iraq
Ireland
Isle of Man
Israel
Italy
Jamaica
Jersey
Jordan
Kazakhstan
Kenya
Kiribati
Korea, Republic Of
Kosovo
Kuwait
Kyrgyzstan
Lao People's Democratic Republic
Latvia
Lebanon
Lesotho
Liberia
Liechtenstein
Lithuania
Luxembourg
Macau
Macedonia
Madagascar
Malawi
Malaysia
Maldives
Mali
Malta
Marshall Islands
Martinique
Mauritania
Mauritius
Mayotte
Mexico
Micronesia, Federated States Of
Moldova, Republic Of
Monaco
Mongolia
Montenegro
Montserrat
Morocco
Mozambique
Myanmar
Namibia
Nauru
Nepal
Netherlands Antilles
New Caledonia
New Zealand
Nicaragua
Niger
Nigeria
Niue
Norfolk Island
Northern Mariana Islands
Oman
Pakistan
Palau
Palestine
Panama
Papua New Guinea
Paraguay
Peru
Philippines
Pitcairn
Poland
Portugal
Puerto Rico
Qatar
Reunion
Romania
Russian Federation
Rwanda
Saint Bartholemy
Saint Kitts And Nevis
Saint Lucia
Saint Martin
Saint Vincent And The Grenadines
Samoa
San Marino
Sao Tome And Principe
Saudi Arabia
Senegal
Serbia
Seychelles
Sierra Leone
Sint Maarten
Slovakia
Slovenia
Solomon Islands
South Africa
South Georgia and the South Sandwich Islands
South Sudan
Sri Lanka
St. Helena
St. Pierre And Miquelon
Suriname
Svalbard And Jan Mayen Islands
Swaziland
Sweden
Switzerland
Taiwan
Tajikistan
Tanzania
Thailand
Togo
Tokelau
Tonga
Trinidad And Tobago
Tunisia
Turkey
Turkmenistan
Turks And Caicos Islands
Tuvalu
Uganda
Ukraine
United Arab Emirates
United States Minor Outlying Islands
Uruguay
Uzbekistan
Vanuatu
Vatican City
Venezuela
Vietnam
Virgin Islands (British)
Virgin Islands (U.S.)
Wallis And Futuna Islands
Western Sahara
Yemen
Yugoslavia
Zambia
Zimbabwe

By providing this information, you agree to the processing of your personal data by SANS as described in our Privacy Policy.

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.
  • © 2023 SANS™ Institute
  • Privacy Policy
  • Contact
  • Careers
  • Twitter
  • Facebook
  • Youtube
  • LinkedIn