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
      • European Skills Framework
    • 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. Go To The Head Of The Class: LD_PRELOAD For The Win
370x370_Jeff-McJunkin.jpg
Jeff McJunkin

Go To The Head Of The Class: LD_PRELOAD For The Win

December 6, 2017

go-to-the-head-of-the-class

Imagine a Linux binary compiled from the following source:

#include <stdio.h>
#include <unistd.h>

int main(){
  int duration = 15 * 1000 * 1000; /* microseconds are hard */

  printf("Starting, please wait...");
  usleep(duration);

printf(" Done!\nThe program started up or whatever.\n");
return 0;
}

Now, dear readers, what if we wanted the program to start up immediately? We could wait 15 seconds, but nobody's got time for that. Plus, it could just as easily be a longer wait.

If we have access to the source, we could certainly just remove the usleep() calls and recompile the program. But what if we don't have the source to the program? We'd need an easy way to change runtime behavior, and we'd need to discover which function calls are being made in the first place.

Luckily, today we'll discuss using a cool trick to steal time back. We will make our own usleep function and make the Linux loader call on it first — hence the title of this blog post.

First, if we're curious as to what function calls a binary is making (when we don't have the source), we can use the ltrace utility to see, as shown here:

$ ltrace ./delayed 
__libc_start_main(0x4005b6, 1, 0x7fff764a7958, 0x4005f0 
printf("Starting, please wait...")                               = 24
usleep(15000000)                                                 = <void>
puts(" Done!\nThe program started up or"...Starting, please wait... Done!
The program started up or whatever.
)                             = 43
+++ exited (status 0) +++</void>

The ltrace utility shows regular library calls. It's similar to strace, which shows system calls made by a program, but it's more useful for our purpose here.

Now that we can see those usleep() calls, we can make our own version of that function, then replace the normal version with ours at runtime.

$ cat hacking_time.c
#include <stdio.h>

unsigned int usleep(unsigned int microseconds) {
printf("Hijacked usleep!\n");
return 0;
}
$ gcc hacking_time.c -o hacking_time -shared -fPIC</stdio.h>

Using gcc we've specified the normal input file (hacking_time.c) and output file (-o hacking_time),but we've also specified two additional options: -shared to make a library and -fPIC to specify Position Independent Code, which is necessary for making a shared library.

Now that we've built hacking_time as a shared library, here's the basic usage:

$ LD_PRELOAD="$PWD/hacking_time" ./delayed
Starting, please wait...Hijacked usleep!
Done!
The program started up or whatever.

Great! Instead of calling the normal usleep, we've told the Linux library loader to use our own version instead.

There are a few gotchas here. Note that C functions have input variable types and output variable types. We can look up those expected values after finding the functions shown in the ltrace output though by querying the corresponding manual page:

$ man 3 usleep # also visible online at http://man7.org/linux/man-pages/man3/usleep.3.html
[...skipping a few lines at the beginning...]
SYNOPSIS
       #include 
       int usleep(useconds_t usec);

int usleep tells us that usleep() will return an integer. usleep(useconds_t usec) tells us it expects to be sent something of the type useconds_t. Scrolling down a little further in that same man page we see that useconds_t is also an integer type:

NOTES
The type useconds_t is an unsigned integer type capable of holding integers in the range [0,1000000]


When we build hacking_time.c (or any other code meant for hijacking library calls) we'll need to be sure to have the same inputs (parameters) and output types.

Okay, now that we've examined the happy path to hacking time itself, let's look at some of the common issues when hijacking functions:

Common Issues

Compiling without -fPIC:

Running a shared library for use with LD_PRELOAD without -fPIC looks like the following:

$ gcc hacking_time.c -shared -o hacking_time
/usr/bin/ld: /tmp/ccZKQYM8.o: relocation R_X86_64_32 against `.rodata' can not be used when making 
a shared object; recompile with -fPIC
/tmp/ccZKQYM8.o: error adding symbols: Bad value
collect2: error: ld returned 1 exit status

Make sure you specify the -fPIC argument when compiling an library for a LD_PRELOAD attack.

Compiling without -shared:
$ gcc hacking_time.c -o hacking_time
/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/crt1.o: In function `_start':
(.text+0x20): undefined reference to `main'
collect2: error: ld returned 1 exit status

Since we don't define main(), gcc doesn't know how to build this as a standalone binary. Make sure you specify the -shared argument when building a library for an LD_PRELOAD attack.

Wrong input type to a hijacked function
$ cat hacking_time_wrong_input.c
#include <tstdio.h>

unsigned int usleep(void) {
printf("Hijacked usleep!\n");
return 0;
}
$ gcc hacking_time_wrong_input.c -o hacking_time -shared -fPIC
$ LD_PRELOAD="$PWD/hacking_time" ./delayed
Starting, please wait...Hijacked usleep!
Done!
The program started up or whatever.

Note that I defined usleep as accepting no parameters / inputs with usleep(void). I think we're clearly into undefined behavior here, but I was surprised to see that this actually worked for me.

Wrong return type from a hijacked function
$ cat hacking_time_wrong_return.c
#include <tstdio.h>

void usleep(unsigned int microseconds) {
  printf("Hijacked usleep!\n");
  return;
}
$ gcc hacking_time_wrong_return.c -o hacking_time -shared -fPIC
$ LD_PRELOAD="$PWD/hacking_time" ./delayed 
Starting, please wait...Hijacked usleep!
 Done!
The program started up or whatever.

Here I defined usleep as not returning any data with void usleep. This worked but isn't reliable, since the Linux loader expects the library to comply with the system function declaration.

More resources

If you want to go further into LD_LIBRARY tricks, there are a few resources I'd like to point you to:

  • preeny has a number of pre-built replacement functions available
  • libfaketime can fake calls to see the system time, which is interestingly used to make more deterministic (bit-for-bit identical) software builds in projects like Reproducible Builds by Debian
  • retrace to flexibly track and alter library calls using config files

Thanks for reading! I hope you enjoy the challenge of hacking time — and other libraries — this holiday season.

- Jeff McJunkin
@jeffmcjunkin

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
N2C_Blog_Image.png
Penetration Testing and Red Teaming, Cyber Defense, Cybersecurity and IT Essentials, Open-Source Intelligence (OSINT), Red Team Operations, Incident Response & Threat Hunting, Operating System & Device In-Depth, Community, Digital Forensics and Incident Response, Job Hunting, Mentorship, NetWars, Imposter Syndrome, Offensive Operations
March 14, 2023
A Visual Summary of SANS New2Cyber Summit 2023
Check out these graphic recordings created in real-time throughout the event for SANS New2Cyber Summit 2023
370x370-person-placeholder.png
Alison Kim
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
Blog
Penetration Testing and Red Teaming
January 17, 2018
SANS Poster - White Board of Awesome Command Line Kung Fu (PDF Download)
Imagine you are sitting at your desk and come across a great command line tip that will assist you in your career as an information security professional, so you jot the tip down on a note, post-it, or scrap sheet of paper and tape it to your white board... now imagine you do this all the time...
SANS Pen Test
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