DANGEROUS C Functions gets & strcpy (PicoCTF 2022 #04 buffer-overflow0) (2023)

Introduction

Help the channel grow with a Like, Comment, & Subscribe!
❤️ Support ➡ j-h.io/patreonj-h.io/paypalj-h.io/buymeacoffee
Check out the affiliates below for more free or discounted learning!
🖥️ Zero-Point Security ➡ Certified Red Team Operator j-h.io/crto
💻Zero-Point Security ➡ C2 Development with C# j-h.io/c2dev
👨🏻‍💻7aSecurity ➡ Hacking Courses & Pentesting j-h.io/7asecurity
📗Humble Bundle ➡ j-h.io/humblebundle

🌎Follow me! ➡ j-h.io/discordj-h.io/twitterj-h.io/linkedinj-h.io/instagramj-h.io/tiktok

📧Contact me! (I may be very slow to respond or completely unable to)
🤝Sponsorship Inquiries ➡ j-h.io/sponsorship
🚩 CTF Hosting Requests ➡ j-h.io/ctf
🎤 Speaking Requests ➡ j-h.io/speaking
💥 Malware Submission ➡ j-h.io/malware
❓ Everything Else ➡ j-h.io/etc

Video

In this video, we are cruising through even more of pico ctf 2022 in the last video.

We wrapped up another cryptography challenge, super simple, kind of adapting our code from the previous previous episode video, showcasing, modular, arithmetic.

And some of those shenanigans in this video we're gonna keep cruising so let's dive in okay.

I am back on my terminal, uh, previously.

I was in that basic mod challenge, I'm gonna go ahead and actually move that to a basic mod complete again, just to tie up and close the loop on the things that I should have done in the previous video.

You guys know the drill.

This is the next challenge that we're working through buffer overflow zero.

It is in the binary exploitation category.

And it says, hey, smash.

The stack let's start off simple.

Can you overflow the correct buffer? The program is available here? You can view the source here and connect to it remotely with this command as follows so let's, go ahead and grab the links that we could download this here, I'll move into the binary.

Exploitation category make a directory for buffer overflow if I could type zero move into that directory and let's use wget to download this vuln program.

Now if you haven't done it before the file command will tell you a little bit about what a file is in linux, we can tell, oh, this is a 32-bit program, it's an elf binary or executable link format.

I might have that algorithm wrong acronym wrong goodness.

And it is just a program that we could go ahead and run and execute.

It is not marked as executable at the moment.

So if I try to dot slash vol, it won't, let me, but I could see h, mod, plus x and add literally add with a plus sign, an executable bit changing the modification values for the file, vol present there.

Now when I hit ls, you can see it is brought together in a green syntax highlighting.

And with that, I could dot slash vol.

This actually needs us to create a local flag.text copy, but we're going to end up using this on the remote system, which already has a flag for us.

Anyway, let's download the source again, right, clicking grabbing this link here.

W get to download.

You know, the drill let's open this one up in our text editor, sublime, okay.

So more c code, uh, calling back to maybe the first video in the series includes to grab more library stuff defining a constant for a flag size, maximum value character array with this actual size denoted the length of the flag.

And we have a couple handlers for seg faults.

This is actually a sig seg or maybe a signal when a signal was received for a segmentation fault.

Or when the program crashes or spits up breaks, vomits dies, whatever that is what's actually going to print out our flag.

So that is our win condition, that's how we know we can get the flag.

If we actually cause a segmentation fault crash, the program, okay.

And we have a vuln function that takes in some input.

This is a character array.

You can tell by the pointer or asterisk here and actually defines a buff variable with 16 bytes in length.

So we copy the input that's passed in into the buffer, knowing that it's a length of 16, maybe that's something we could just break here is the check inside of the main function.

Hey, if we open the flag.text file, we want to get the contents, but if we weren't able to open it, then we would get this message, kind of as we saw locally, please create your own flag.text.

Good enough.

Then we use f gets f gets to read the contents the flag.

And we supply the signal handler actually set up the plumbing for that.

If we receive a segmentation fault, it will execute this function, which is our handler, which will display the flag again, our win condition.

Now we go ahead and get an effective user id or effective group id, probably they're doing this.

So on the back end, it is able to read the flag, naturally on their server side, whatever.

And we retrieve an input, we flush standard output.

So it's all displayed something that you can work through.

So the remote service actually gives this message to you.

And we define a buffer one of a hundred characters in length 100 bytes, we use gets as the function to retrieve information from that.

And then we pass it to vuln.

Um gets is a bit interesting because uh gets is a dangerous function.

Now I don't know if folks are familiar with that, let me run man gets to check out the manual page for that.

Can I please goodness gracious I can't, what is it I'm? Just gonna brute force the numbers to try and get the like linux like it's? Just do I not have it downloaded is that my problem all right we'll go to the internet we'll, ask uncle, google let's go.

Look at the c, gets function.

I'll, grab the a man page, hopefully showcased, excuse me, it's, not going to give me a result for that man page the manual page there.

It is linux man page here.

We go get a string from standard input.

However, this function is deprecated.

It is old.

It is not recommended it is not one that you could use.

In fact, the description literally says never ever use.

This function gets will read a line from standard input.

You typing on your keyboard into the buffer pointed to by s, the string or the character buffer character array that is, uh passed in as an argument and it'll read it until either a terminating new line or an end of file.

Eof is replacing, uh with a null.

Byte newline or uf will be replaced with a null byte.

But it does not check if a buffer overrun or a buffer overflow is performed or in place.

It actually defines as hey, if you want to look at the bugs section down below, let me do that we'll scroll down.

This literally says, never ever use.

This gets function because it's impossible to tell without knowing the data in advance how many characters gets will read in, and because gets will continue to store characters past the end of the buffer it's extremely dangerous to use it's been used to break computer security use f gets instead, which fgets will allow you to pass in a known length, or what you can expect to retrieve from your input.

What is it for more information, check out use of inherently dangerous functions, that's, that's wild.

So we knew looking back at the source code, our original buffer that we read in sure it's a hundred bytes long.

And we can read in buff.

One of that with gets it's, not going to check the bounds.

If we actually entered a hundred bytes, it gets passed into volume, then which uses str copy.

And that might cram up 16 bytes.

So I'm interested and curious will both of these break let's.

Do it let's? Go ahead and go back to the picoctf challenge and let's, grab this remote connection string.

So I can just use netcat in my terminal.

It wants to know an input and I'll say, please subscribe.

How many characters is that we got what six here seven and then subscribe, how many did we count earlier? That's, nine, yeah, uh.

So 16 characters on the dot program will exit.

Now let's enter please subscribe with a couple exclamation points at the end.

All it needed was 16 bytes because str copy is another dangerous function.

And now let's dive into that.

One just as well, it gets, we knew was bad to begin with, uh, maybe it'll break even earlier.

If we just hit through the 100 bytes, but let's check out str copy, scr copy copies, a string.

And I tried to elude to this right? Sure, it'll return a character array buffer, but it has a destination and a source that are passed in scr copy function copies.

The string pointed to by the source, including the terminating nullibyte to the buffer pointed to by destination.

The strings may not overlap and the destination.

String must be large enough to receive the copy beware of buffer overruns or buffer overflows.

And this is where again, you can see bugs.

They denote here.

The str n copy function is similar, except that most n bytes of the source are copied.

This adds a limit that sets a maximum that says, hey, you cannot copy more than n.

Bytes, there's, a maximum length there.

If the length is less than n, sure strn copy will do it properly, um and there's, a fine implementation of that just as well, but scrolling down to again that bugs section if the destination string of str copy is not large enough.

Then anything could happen.

Overflowing fixed length.

String.

Buffers is a favorable.

Excuse me, favorite cracker technique for taking complete control of the machine.

This is old right, modern security mechanisms, hey, you'll know, when there's a stack smashing based off stack canaries, a little token or a little special string, that'll say, hey, if this value is overwritten or clobbered, we can tell that evil's going on not the case and how this binary was compiled how this was created.

I think that's what f no stack protector.

Let me show you that super quick.

Let me actually can I create I'll copy I'll move vuln to, oh, goodness, vol original and I'll gcc, our own vuln.c.

And this actually will display some straight up warnings.

Some of it's, hey, based on the group id or effective group id.

But the one down here it says, uh, even below our linker is telling us.

Look the gets function is dangerous and should not be used did it actually even compile it? It did okay.

Cool.

So a dot out I could run, and we need a flag.text.

Let me just echo flag, please subscribe and I'll redirect that out to our own local flag.text.

Now, when I run this program, hey, we have our input.

Hello program will exit.

Hello program will exit.

Did I have enough values there, I'm, not sure let's try and send some more shenanigans, and that will read our flag for us.

How did that compile did I do something stupid there, no elf, 64-bit, lsb position, independent executable, blah, blah, blah, what I'm a dumbo? I must be doing something all right? I must be misunderstanding something as I try to show you something worthwhile.

Come on it's, not going to give me the stack smashing detected.

I can't even check the message, whatever I'm just going to make a fool of myself.

Okay? Well, forgive me, maybe cali.

I don't even want to postulate.

I think I'm I'm.

Clearly a horrible teacher.

I clearly don't know what I'm doing.

I've always said, you know, what I'm a security charlatan, uh, regardless we have retrieved our flag.

We've retrieved the legitimate flag, uh, when I use netcat I'll use a control r in the terminal to be able to do a quick reverse search typed in nc or netcat and found the previous iteration.

If I just spammed it with, hey, a whole crapload of a's.

I get my legitimate flag, overflows, aren't that bad, um, yeah.

That's it.

Those are the dangerous functions that we've learned about str copy and gets, uh, we're still going to be end up breaking it.

Even if we are at 100 or not let me check out how much did I supply there I'm using python, super quick length of 43., all right, let's amp that up here's 129 as a string.

And of course, look we're gonna end up crashing the thing just as well, I'll use netcat.

Once again, slapping it.

In gets is gonna break any of these functions will break, but we have our flag.

And that is what we can go ahead and submit and call it a day for that challenge.

I don't know, if you learned something new or not, uh, again, hey, we're still kind of at the baby steps here, we're on our training wheels.

But now we're learning a little bit more about those dangerous functions and other things that you shouldn't use in c, low-level programming languages, hooray.

We've earned 100 points.

Hey, thank you so much for watching everybody.

I hope you enjoyed this video.

If you did, please do those youtube algorithm things, please like the video comment, subscribe, those are things that really really help the channel grow support share all things that I don't know help me motivated help me stay motivated to keep putting out stuff like this for you.

Thanks so much.

Everybody I'll see in the next video.

I love you take care with you.

FAQs

What are the unsafe functions for buffer overflow in C? ›

That is why the safest basic method in C is to avoid the following five unsafe functions that can lead to a buffer overflow vulnerability: printf , sprintf , strcat , strcpy , and gets . Unfortunately, the base C language provides only one safe alternative: fgets (to be used instead of gets ).

What are the dangerous functions in C? ›

C users must avoid using dangerous functions that do not check bounds unless they've ensured that the bounds will never get exceeded. Functions to avoid in most cases (or ensure protection) include the functions strcpy(3), strcat(3), sprintf(3) (with cousin vsprintf(3)), and gets(3).

What is a buffer overflow in C? ›

A buffer overflow is a type of runtime error that allows a program to write past the end of a buffer or array — hence the name overflow— and corrupt adjacent memory. Like most bugs, a buffer overflow doesn't manifest at every program execution.

Can strcpy cause buffer overflow? ›

The strcpy() function does not stop until it sees a zero (a number zero, '<0') in the source string. Since the source string is longer than 12 bytes, strcpy() will overwrite some portion of the stack above the buffer. This is called buffer overflow.

How do you fix a buffer overrun? ›

How to Fix Overrun of a Stack-Based Buffer Issue
  1. Scan Your Computer for Virus or Malware.
  2. Run SFC And DISM Command.
  3. Clean Boot the Computer.
  4. Perform System Restore.
  5. Try Startup Repair.
  6. Back up Data and Reinstall Your Windows.
Jun 28, 2022

Is C vulnerable to buffer overflow? ›

Key Concepts of Buffer Overflow

This error occurs when there is more data in a buffer than it can handle, causing data to overflow into adjacent storage. This vulnerability can cause a system crash or, worse, create an entry point for a cyberattack. C and C++ are more susceptible to buffer overflow.

What is unsafe in C? ›

The unsafe keyword denotes an unsafe context, which is required for any operation involving pointers. For more information, see Unsafe Code and Pointers. You can use the unsafe modifier in the declaration of a type or a member. The entire textual extent of the type or member is therefore considered an unsafe context.

What is a dangerous thing about programming in the C language? ›

What is a dangerous thing about programming in the C language? What's dangerous about C is that a beginner can make some big blunders. For example, a programmer can write to areas of memory that cause damage to the OS kernel or, even worse, write a program that allows a remote user to write to areas of memory.

What are the 4 types of functions in C? ›

There are four types of user-defined functions divided on the basis of arguments they accept and the value they return:
  • Function with no arguments and no return value.
  • Function with no arguments and a return value.
  • Function with arguments and no return value.
  • Function with arguments and with return value.
Jun 22, 2023

What is one way to prevent a buffer overflow? ›

A buffer overflow is one of the best known forms of software security vulnerability and is still a commonly used cyber attack. You can prevent a buffer overflow attack by auditing code, providing training, using compiler tools, using safe functions, patching web and application servers, and scanning applications.

What is an example of a buffer overflow vulnerability? ›

For example, an attacker may introduce extra code, sending new instructions to the application to gain access to IT systems. If attackers know the memory layout of a program, they can intentionally feed input that the buffer cannot store, and overwrite areas that hold executable code, replacing it with their own code.

What functions cause buffer overflow? ›

The following five common unsafe functions that can lead to a buffer overflow vulnerability: printf, sprintf, strcat, strcpy, and gets.

Why is strcpy unsafe in C? ›

strcpy has no way of knowing how large the destination buffer is (i.e. there is no length parameter) so sloppy programming using it can lead to overrunning the buffer and corrupting other memory. Such an overrun can lead to crashes, odd behaviour and may be exploitable by malware authors.

Is it safe to use strcpy? ›

Using strcpy() function to copy a large character array into a smaller one is dangerous, but if the string will fit, then it will not be worth the risk. If the destination string is not large enough to store the source string then the behavior of strcpy() is unspecified or undefined.

How to mitigate buffer overflow in C? ›

How to Mitigate Buffer Overflows. Use an interpreted language which isn't susceptible to these issues. Avoid using functions which don't perform buffer checks (for example, in C, instead of gets() use fgets()). Use compilers which can help identify unsafe functions or errors.

How to avoid stack overflow in C? ›

In order to prevent stack overflow bugs, you must have a base case where the function stops make new recursive calls. If there is no base case then the function calls will never stop and eventually a stack overflow will occur.

What happens if your buffer is too heavy? ›

With a heavier buffer weight, the BCG encounters more resistance rearwards. The entire action becomes smoother, especially the felt recoil. But an overly heavy buffer isn't good for a rifle, either. It will prevent the AR-15 from cycling, leading to improper extraction and ejection.

How do you clear a buffer? ›

Clearing input buffer in C/C++

The function fflush(stdin) is used to flush or clear the output buffer of the stream. When it is used after the scanf(), it flushes the input buffer also. It returns zero if successful, otherwise returns EOF and feof error indicator is set.

What are the most common buffer overflow attacks? ›

The most common are: Stack-based buffer overflows: This is the most common form of buffer overflow attack. The stack-based approach occurs when an attacker sends data containing malicious code to an application, which stores the data in a stack buffer.

Is buffer overflow a cyber threat? ›

A buffer overflow attack is a common cyberattack that deliberately exploits a buffer overflow vulnerability where user-controlled data is written to memory. By submitting more data than can fit in the allocated memory block, the attacker can overwrite data in other parts of memory.

Which action prevents buffer overflow attacks? ›

Several measures can be taken to prevent buffer overflows. These include address space layout randomization (ASLR), data execution prevention, and operating system runtime protections. ASLR is a technique that makes it harder for an attacker to predict where code will be executed in memory.

What makes a code unsafe? ›

Unsafe code in C# isn't necessarily dangerous; it's just code whose safety cannot be verified. Unsafe code has the following properties: Methods, types, and code blocks can be defined as unsafe. In some cases, unsafe code may increase an application's performance by removing array bounds checks.

What is an unsafe variable? ›

One source claims that an unsafe variable is a variable, which appears in the head of a rule but not in the body, which makes sense as the symbols :- denote a reverse implication.

What is type unsafe language? ›

A type safe language maintains data truthfulness from the cradle to the grave. This means it won't allow an int (or any other data type) to be inserted into a char at runtime. It'll usually throw some kind of class cast or out-of-memory exception.

Can C damage your computer? ›

Not if you're using a modern operating system; you can crash your own program as much as you like, but the OS will insulate everything else from it. This is called 'process isolation', and it's a very good thing.

Why do hackers use C language? ›

The C programming language is suitable for ethical hacking as it helps access memory and system processes. Ethical hackers use C to reverse engineer, simulate a cyberattack, then gain access as if a system breach occurred.

Why is C good for malware? ›

As one of the older programming languages, C is the most commonly used in creating malware. One of the reasons for this is that it has many windows-based libraries that efficiently control the computer's functionality. Also, Languages like C are more memory efficient than others.

What are the 5 function in C? ›

Types of Functions

Library Functions: are the functions which are declared in the C header files such as scanf(), printf(), gets(), puts(), ceil(), floor() etc.

How many C functions are there? ›

There are two types of function in C programming: Standard library functions.

What is C type function? ›

The ctype. h header file of the C Standard Library declares several functions that are useful for testing and mapping characters. All the functions accepts int as a parameter, whose value must be EOF or representable as an unsigned char.

What programming languages are vulnerable to buffer overflow attacks? ›

Programming languages commonly associated with buffer overflows include C and C++, which provide no built-in protection against accessing or overwriting data in any part of memory and do not automatically check that data written to an array (the built-in buffer type) is within the boundaries of that array.

What is the simplest buffer overflow? ›

The simplest and most common buffer overflow is one where the buffer is on the stack.

How do you detect a buffer overflow? ›

Buffer overflow detection dynamically analyzes the behavior of programs running on the system in order to detect when an attempt is made to exploit a running process using buffer overflow techniques.

Which tools can be used to detect buffer overflow attacks? ›

How to Detect Buffer Overflow Vulnerability and a Buffer Overflow Attack. The best way to detect this type of vulnerability is to use a static code analyzer, such as Klocwork. Klocwork has an extensive set of software security checkers to help ensure that security vulnerabilities cannot be exploited.

What is a real life example of a buffer overflow? ›

Buffer overflow attacks have been responsible for some of the biggest data breaches in history. Some notable examples include: Morris Worm: The Morris worm of 1988 was one of the first internet-distributed computer worms, and the first to gain significant mainstream media attention.

What are two types of buffer overflow attacks? ›

There are two types of buffer overflows: stack-based and heap-based.

How many primary ways are there for detecting buffer overflow? ›

How many primary ways are there for detecting buffer-overflow? Explanation: There are two ways to detect buffer-overflow in an application.

Is strcpy function banned? ›

The following C functions are banned in CS3214: strcpy. strcat. strncpy.

What is the safe version of the strcpy () function in C? ›

You should know that the new C11 update to the C programming language provides for a replacement “safe” version of this function, which is named strcpy_s(). The parameter lists and return types differ: char *strcpy(char *strDestination, const char *strSource);

What is strcpy in cyber security? ›

strcpy is a C standard library function that copies a string from one location to another. It is defined in the string. h header file. The function takes two arguments: a destination buffer where the copied string will be stored, and a source string that will be copied.

Why do we use strcpy? ›

The strcpy function in C++ is used to copy the content of the source string to the destination string without changing the source string. It returns a pointer to the destination string after copying its content.

Why do you have to use strcpy? ›

It is used to copy the character array pointed by the source to the location pointed by the destination. Or in easy terms, it copies the source string(character array) to the destination string(character array).

What is the main function of strcpy? ›

The strcpy() function copies the string pointed by source (including the null character) to the destination. The strcpy() function also returns the copied string.

Which C code is vulnerable to buffer overflow? ›

That is why the safest basic method in C is to avoid the following five unsafe functions that can lead to a buffer overflow vulnerability: printf , sprintf , strcat , strcpy , and gets . Unfortunately, the base C language provides only one safe alternative: fgets (to be used instead of gets ).

What is the most common cause of buffer overflow in software today? ›

The combination of memory manipulation and mistaken assumptions about the size or makeup of a piece of data is the root cause of most buffer overflows. Buffer overflow vulnerabilities typically occur in code that: Relies on external data to control its behavior.

Which functions are vulnerable to buffer overflow? ›

The following five common unsafe functions that can lead to a buffer overflow vulnerability: printf, sprintf, strcat, strcpy, and gets.

Which programs are vulnerable to buffer overflow? ›

A buffer overflow program in Assembly, C, C++ or Fortran is also particularly vulnerable and more likely to enable attackers to compromise a system. However, applications written in JavaScript or Perl are typically less vulnerable to buffer overflow attacks.

What are vulnerabilities to buffer overflow? ›

Buffer overflow vulnerabilities typically occur in code that: Relies on external data to control its behavior. Depends upon properties of the data that are enforced outside of the immediate scope of the code. Is so complex that a programmer cannot accurately predict its behavior.

What are bad characters for buffer overflow? ›

Characters such as \r , \n , / and ? can cause the line that's being parsed to truncate prematurely and fail to overflow the buffer, or lead to a 404 error instead of calling the vulnerable function. Characters being converted between upper and lower case is another example that will mess with shell code.

Which type of buffer overflows are common among attackers? ›

Stack-based buffer overflows, which are more common among attackers, exploit applications and programs by using what is known as a stack, the memory space used to store user input.

What causes a buffer overflow quizlet? ›

A stack buffer overflow occurs when the targeted buffer is located on the stack, usually as a local variable in a function's stack frame.

Is a buffer overflow a memory leak? ›

Answer : Memory leaks means incomplete deallocation - are bugs that happen very often. Buffer overflow means data sent as input to the server that overflows the boundaries of the input area, thus causing the server to misbehave. Buffer overflows can be used.

Is buffer overflow memory corruption? ›

Buffer overflow attacks can cause memory corruption with unintentional memory modification, which the hacker can use to inject code. Looking at the overall application, there are more security threats that exist at the infrastructure layer, network layer, and data layer.

Top Articles
Latest Posts
Article information

Author: Amb. Frankie Simonis

Last Updated: 21/07/2023

Views: 5577

Rating: 4.6 / 5 (56 voted)

Reviews: 95% of readers found this page helpful

Author information

Name: Amb. Frankie Simonis

Birthday: 1998-02-19

Address: 64841 Delmar Isle, North Wiley, OR 74073

Phone: +17844167847676

Job: Forward IT Agent

Hobby: LARPing, Kitesurfing, Sewing, Digital arts, Sand art, Gardening, Dance

Introduction: My name is Amb. Frankie Simonis, I am a hilarious, enchanting, energetic, cooperative, innocent, cute, joyous person who loves writing and wants to share my knowledge and understanding with you.