C programming byte data type - c

I am doing a ctf and I have reversed and elf file and found the function that encodes the flag and i have made a decoder but because it is in c i cant use the byte data type. Is there any library that i can add and if not how did this code use the byte data type. I alredy did some challanges by this author and i solved the by deocidng the in c, and i think that this is something called dynamic string traformation.
// the original encoder
undefined8 main(void)
{
int iVar1;
ssize_t sVar2;
long in_FS_OFFSET;
int local_40;
byte local_38 [40];
long local_10;
local_10 = *(long *)(in_FS_OFFSET + 0x28);
initialize_flag();
puts("Give me your password: ");
sVar2 = read(0,local_38,0x1f);
local_38[(int)sVar2 + -1] = 0;
local_40 = 0x28;
while (local_40 < (int)sVar2 + -1) {
local_38[local_40] = local_38[local_40] ^ (char)local_40 + 10U;
local_38[local_40] = local_38[local_40] - 2;
local_40 = local_40 + 1;
}
iVar1 = strcmp((char *)local_38,"lp`7a<qLw\x1ekHopt(f-f*,o}V\x0f\x15J");
if (iVar1 == 0) {
puts("Thats the right password!");
printf("Flag: %s",flagBuffer);
}
else {
puts("Thats not the password!");
}
if (local_10 != *(long *)(in_FS_OFFSET + 0x28)) {
/* WARNING: Subroutine does not return */
__stack_chk_fail();
}
return 0;
}
Here is my encoder:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main()
{
ssize_t sVar2;
int local_40;
byte local_38 [40];
sVar2 = read(0,local_38,0x1f);
local_38[(int)sVar2 + -1] = 0;
local_40 = 27;// the flag lenght is 27
while (local_40 > 0) {
//this is the reverse of the og encoding
local_40 = local_40 - 1;
local_38[local_40] = local_38[local_40] - 2;
local_38[local_40] = (local_38[local_40] ^ (char)local_40) - 10U;
}
puts(local_38);
return 0;
}
//lp`7a<qLw\x1ekHopt(f-f*,o}V\x0f\x15J this is the encoded flag
// s after the original encoding should be w

The comments already have gotten you two great answers(Using stdint.h or chars), but otherwise...
If you do not have access to the stdint header and do not want to use chars, libraries such as Boost can provide you the uint8_t datatype, too.
In C++, you have std::byte accessible(Not sure you, specifically, will be helped by that, but others maybe)
If you wish to make sure a char is 8-bits of lenght, you can check the CHAR_BIT value defined in .
So your options(Ranking from best to worse) are:
(If you can use cpp) Using std::byte
Using the uint8_t datatype defined in <stdint.h>
Using a char/unsigned char
Using an external library
Note it's probably overkill using an external library for such a trivial task unless you already have that said library.
Hope this helps.

your decoder seems to have some errors like: local_38[local_40] = local_38[local_40] - 2;
It should be like this: local_38[local_40] = local_38[local_40] + 2;
I have written a decoder for above question in python
key="lp`7a<qLw\x1ekHopt(f-f*,o}V\x0f\x15J"
check=list(key)
string=str()
string=''
for i in range(26,-1,-1):
j=i+10
k=(ord(check[i])+2)
string=(chr(k^j)+string)
print(string)
Hope this will help

Related

Can Ghidra re-compile and run a short function?

I've picked out a short and "self-contained" function from the Ghidra decompiler. Can Ghidra itself compile the function again so I can try to run it for a couple different values, or would I need to compile it myself with e.g. gcc?
Attaching the function for context:
undefined8 FUN_140041010(char *param_1,longlong param_2,uint param_3)
{
char *pcVar1;
uint uVar2;
ulonglong uVar3;
uVar3 = 0;
if (param_3 != 0) {
pcVar1 = param_1;
do {
if (pcVar1[param_2 - (longlong)param_1] == '\0') {
if ((uint)uVar3 < param_3) {
param_1[uVar3] = '\0';
return 0;
}
break;
}
*pcVar1 = pcVar1[param_2 - (longlong)param_1];
uVar2 = (uint)uVar3 + 1;
uVar3 = (ulonglong)uVar2;
pcVar1 = pcVar1 + 1;
} while (uVar2 < param_3);
}
param_1[param_3 - 1] = '\0';
return 0;
}
Can Ghidra itself compile the function again so I can try to run it for a couple different values
The P-Code emulator of Ghidra is intended for this kind of scenario.
If it is just a short function and doesn't use other libraries, syscalls, etc like your example then the emulator can easily handle this without further effort on your side to emulate library functions. Ghidra knows the semantics of each instruction and converts them to the standardized P-Code format for e.g. decompilation, but this can also be combined with a "P-Code virtual machine".
It will most likely still involve a bit of scripting, though there exist plugins like TheRomanXpl0it/ghidra-emu-fun to make this easier. There are also more general tutorials if you want to understand the basic idea and usage of the Emulator API (which is not exposed in the GUI in any way)
If you run into issues while scripting the emulator I would recommend asking specific questions about the emulator API at the dedicated Reverse Engineering Stack Exchange
You can, but you'll have to change some of the types to be standard C, or just add typedefs like so:
#include <stdint.h>
typedef uint8_t undefined8;
typedef long long int longlong;
typedef unsigned long long int ulonglong;
typedef unsigned int uint;
undefined8 FUN_140041010(char *param_1,longlong param_2,uint param_3)
{
char *pcVar1;
uint uVar2;
ulonglong uVar3;
uVar3 = 0;
if (param_3 != 0) {
pcVar1 = param_1;
do {
if (pcVar1[param_2 - (longlong)param_1] == '\0') {
if ((uint)uVar3 < param_3) {
param_1[uVar3] = '\0';
return 0;
}
break;
}
*pcVar1 = pcVar1[param_2 - (longlong)param_1];
uVar2 = (uint)uVar3 + 1;
uVar3 = (ulonglong)uVar2;
pcVar1 = pcVar1 + 1;
} while (uVar2 < param_3);
}
param_1[param_3 - 1] = '\0';
return 0;
}
Then you can call it like any function:
int main(int argc, char const* argv[])
{
char* mystr = "hello";
printf("%hhu\n", FUN_140041010(mystr, /* not sure about this arg */ 0, strlen(mystr));
return 0;
}

How to generate Universally Unique IDentifier, UUID from LoadRunner independent of the OS

I have experienced the need of generating UUID in LoadRunner several times while scripting but there is no in-build function to do so. I am using both linux and windows load generators.
Thanks to Scott Moore for writing the below code which uses windows in-build CoCreateGuid function (dependent on ole32.dll) to generate required UUID. However that code is completely dependent on windows platform and doesn't work in Linux platform.
How can we generate UUID from Loadrunner independent of OS?
#include "lrun.h"
#include "web_api.h"
#include "lrw_custom_body.h"
#include "stdlib.h"
#include "stdio.h"
#include "string.h"
int lr_guid_gen()
{
typedef struct _GUID
{
unsigned long Data1;
unsigned short Data2;
unsigned short Data3;
unsigned char Data4[8];
} GUID;
GUID m_guid;
char buf[50];
lr_load_dll ("ole32.dll");
CoCreateGuid(&m_guid);
sprintf (buf, "%08lx-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
m_guid.Data1, m_guid.Data2, m_guid.Data3,
m_guid.Data4[0], m_guid.Data4[1], m_guid.Data4[2], m_guid.Data4[3],
m_guid.Data4[4], m_guid.Data4[5], m_guid.Data4[6], m_guid.Data4[7]);
lr_save_string(buf, "PAR_GUID");
return 0;
}
You can use the following trick which doesn't require any code.
Define a hex parameter as follows:
Then use it with this code:
lr_eval_string("{MyHex}{MyHex}-{MyHex}-{MyHex}-{MyHex}-{MyHex}{MyHex}{MyHex}")
I have come up with the below mentioned solution
int lr_guid_gen()
{
char GUID[40];
int t = 0;
char *szTemp = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";
char *szHex = "0123456789abcdef-";
int nLen = strlen (szTemp);
for (t=0; t<nLen+1; t++)
{
int r = rand () % 16;
char c = ' ';
switch (szTemp[t])
{
case 'x' : { c = szHex [r]; } break;
case 'y' : { c = szHex [r & 0x03 | 0x08]; } break;
case '-' : { c = '-'; } break;
case '4' : { c = '4'; } break;
}
GUID[t] = ( t < nLen ) ? c : 0x00;
}
lr_save_string(GUID,"PAR_GUID");
return 0;
}

How mbtowc uses locale?

I have hard time using mbtowc, which keeps returning wrong results. It also puzzles me why the function even uses locale? Multibyte unicode chars points are locale independent. I implemented custom conversion function that convert it well, see the code below.
I use GCC 4.8.1 on Windows (where sizeof wchar_t is 2), using Czech locale (cs_CZ). The OEM codepage is windows-1250, console by default uses CP852. These are my results so far:
#include <stdio.h>
#include <stdlib.h>
// my custom conversion function
int u8toint(const char* str) {
if(!(*str&128)) return *str;
unsigned char c = *str, bytes = 0;
while((c<<=1)&128) ++bytes;
int result = 0;
for(int i=bytes; i>0; --i) result|= (*(str+i)&127)<<(6*(bytes-i));
int mask = 1;
for(int i=bytes; i<6; ++i) mask<<= 1, mask|= 1;
result|= (*str&mask)<<(6*bytes);
return result;
}
// data inspecting type for the tests in main()
union data {
wchar_t w;
struct {
unsigned char b1, b2;
} bytes;
} a,b,c;
int main() {
// I tried setlocale here
mbtowc(NULL, 0, 0); // reset internal mb_state
mbtowc(&(a.w),"ř",6); // apply mbtowc
b.w = u8toint("ř"); // apply custom function
c.w = L'ř'; // compare to wchar
printf("\na = %hhx%hhx", a.bytes.b2, a.bytes.b1); // a = 0c5 wrong
printf("\nb = %hhx%hhx", b.bytes.b2, b.bytes.b1); // b = 159 right
printf("\nc = %hhx%hhx", c.bytes.b2, c.bytes.b1); // c = 159 right
getchar();
}
Here are setlocale settings and the results for a:
setlocale(LC_CTYPE,"Czech_Czech Republic.1250"); // a = 139 wrong
setlocale(LC_CTYPE,"Czech_Czech Republic.852"); // a = 253c wrong
Why mbtowc doesn't give 0x159 - the unicode number of ř?

UTF-8 to unicode converter for embeded system display

I have an embedded system that gets UTF-8 encoded data to display via UPNP. The display device has the ability to display characters. I need a way to convert the UTF-8 data I recieve via UPNP to unicode. The display is on a PIC, and it is sent data via a UPNP bridge running linux. Is there a simple way to do the conversion before I send it to the display board in linux?
If you have a real operating system and hosted C environment at your disposal, the best approach would be to simply ensure that your program runs in a locale that uses UTF-8 as its encoding and use mbrtowc or mbtowc to convert UTF-8 sequences to Unicode codepoint values (wchar_t is a Unicode codepoint number on Linux and any C implementation that defines __STDC_ISO_10646__).
If you do want to skip the system library routines and do UTF-8 decoding yourself, be careful. I once did a casual survey using Google code search and found that somewhere between 1/3 and 2/3 of the UTF-8 code out in the wild was dangerously wrong. Here is a fully correct, fast, and simple implementation I would highly recommend:
http://bjoern.hoehrmann.de/utf-8/decoder/dfa/
My implementation in musl is somewhat smaller in binary size and seems to be faster, but it's also a bit harder to understand.
To convert an array of bytes encoded as UFT-8 into an array of Unicode code points:
The trick is to detect various encoding mistakes.
#include <limits.h>
#include <stdio.h>
#include <stdbool.h>
#include <stdint.h>
typedef struct {
uint32_t UnicodePoint; // Accumulated code point
uint32_t Min; // Minimum acceptable codepoint
int i; // Index of char/wchar_t remaining
bool e; // Error flag
} UTF_T;
static bool IsSurrogate(unsigned c) {
return (c >= 0xD800) && (c <= 0xDFFF);
}
// Return true if more bytes needed to complete codepoint
static bool Put8(UTF_T *U, unsigned ch) {
ch &= 0xFF;
if (U->i == 0) {
if (ch <= 0x7F) {
U->UnicodePoint = ch;
return false; /* No more needed */
} else if (ch <= 0xBF) {
goto fail;
} else if (ch <= 0xDF) {
U->Min = 0x80;
U->UnicodePoint = ch & 0x1F;
U->i = 1;
} else if (ch <= 0xEF) {
U->Min = 0x800;
U->UnicodePoint = ch & 0x0F;
U->i = 2;
} else if (ch <= 0xF7) {
U->Min = 0x10000;
U->UnicodePoint = ch & 0x07;
U->i = 3;
} else {
goto fail;
}
return true; /* More needed */
}
// If expected continuation character missing ...
if ((ch & (~0x3F)) != 0x80) {
goto fail;
}
U->UnicodePoint <<= 6;
U->UnicodePoint |= (ch & 0x3F);
// If last continuation character ...
if (--(U->i) == 0) {
// If codepoint out of range ...
if ((U->UnicodePoint < U->Min) || (U->UnicodePoint > 0x10FFFF)
|| IsSurrogate(U->UnicodePoint)) {
goto fail;
}
return false /* No more needed */;
}
return true; /* More needed */
fail:
U->UnicodePoint = -1;
U->i = 0;
U->e = true;
return false /* No more needed */;
}
/* return 0:OK, else error */
bool ConvertUTF8toUnicodeCodepoints(const char *UTF8, size_t Length,
uint32_t *CodePoints, size_t *OutLen) {
UTF_T U = { 0 };
*OutLen = 0;
for (size_t i = 0; i < Length;) {
while (Put8(&U, UTF8[i++])) {
// Needed bytes not available?
if (i >= Length) {
return true;
}
}
if (U.e) break;
CodePoints[(*OutLen)++] = U.UnicodePoint;
}
return U.e;
}
This is based on some old code, please advise as it may not be up to current standards.
Not the prettiest with goto and magic numbers.
What is nice about this approach is rather than CodePoints[(*OutLen)++] = U.UnicodePoint for consuming the codepoint, if one wanted to extract UTF16 (BE or LE), one could easily write consumer code for the UTF_T block and not need to change to the UTF8 -> codepoint part.
I would use the Unicode manipulation functions of GLib, a LGPL-licensed utility library. It sounds like g_utf8_to_ucs4() is what you are looking for.

Another C question

I have a piece of code shown below
#include <stdio.h>
#include <stdlib.h>
void Advance_String(char [2],int );
int Atoi_val;
int Count_22;
int Is_Milestone(char [2],int P2);
char String[2] = "0";
main()
{
while(1)
{
if(Is_Milestone(String,21)==1)
{
if(atoi(String)==22)
{
Count_22 = Count_22 + 1;
}
}
Atoi_val = atoi(String);
Advance_String(S,Atoi_val);
}
}
int Is_Milestone(char P1[2],int P2)
{
int BoolInit;
char *Ptr = P1;
int value = atoi(Ptr);
BoolInit = (value > P2);
return BoolInit;
}
void Advance_String(char P1[2],int Value)
{
if(Value!=7)
{
P1[1] = P1[1]+1;
}
else
{
P1[1] = '0';
P1[0] = P1[0]+1 ;
}
}
Now my problem is Count_22 never increments as the char increments never achieves the value 21 or above.Could anyone please tell me the reason for this unexpected behaviour?My question here is to find the value of Count_22.Is there any problem with the code?
Thanks and regards,
Maddy
Your code is probably one of the worst pieces of C code i've ever seen (no offense, everybody has to learn sometime).
It has syntax errors (maybe copy/paste problem), logical problems, meaningless obfuscation, bad practices (globals), buffer overflow (atoi used on a char where there is no place to store the terminating zero byte), uninitialized values (Count_22), surprising naming convention (mixed CamelCase and underscore, variables and functions beginning with capital letter), infinite loop, no header and I forget some.
More, if you want anyone to help you debug this code, you should at list say what it is supposed to do...
To answer to the original question: why Count_22 is never incremented ?
Because Is_Milestone is always false (with or without #Jay change). Is_Milestone intend seems to be to compare the decimal value of the string "22" with the integer 21 (or 1, boolean result of 21 == 1) depending on the version).
It's logical because of Advance_String behavior. both because String has bad initial value (should probably be char String[3] = "00";) and because of the Value != 7 test. I guess what you wanted was comparing the digit with 7, but atoi works with a full string. Another minor change to achieve that Atoi_val = atoi(String+1); in the body of your loop. Then again you won't see much as the loop never stop and never print anything.
If it is a first attempt at an exercice given by some teacher (something like "programming a two digit counter in base 7" or similar). You should consider not using atoi at all and converting characters digit to value using something like:
digit_value = char_value - '0';
example:
char seven_as_char = '7';
int seven_as_int = seven_as_char - '0';
If you can explain what you are really trying to do, we may be able to show you some simple sample code, instead of the horror you are trying to debug.
EDIT
It is really more simple with original code...
After reading the Ada source, I can confirm it is indeed an Ascii based octal counter. The original code is allready of poor quality, and that explains part of the bad quality of the resulting C code.
A possible direct port could be as following (but still need a serious cleanup to look like native C code... and is quite dumb anyway as it prints a constant):
#include <stdio.h>
#include <stdlib.h>
void Advance_String(char * P1)
{
if((P1[1]-'0') != 7){
P1[1]++;
}
else{
P1[1] = '0';
P1[0]++ ;
}
}
int Is_Milestone(char * P1, int P2)
{
return (atoi(P1) > P2);
}
main()
{
int Count_11 = 0;
int Count_22 = 0;
int Count_33 = 0;
int Count_44 = 0;
char S[3] = "00";
int cont = 1;
while(cont)
{
if(Is_Milestone(S, 10)){
if(atoi(S) == 11){
Count_11 = Count_11 + 1;
}
if(Is_Milestone(S, 21)){
if(atoi(S) == 22){
Count_22 = Count_22 + 1;
}
if(Is_Milestone(S, 32)){
if(atoi(S) == 33){
Count_33 = Count_33 + 1;
}
if(Is_Milestone(S, 43)){
if(atoi(S) == 44){
Count_44 = Count_44 + 1;
}
if (atoi(S) == 77){
cont = 0;
}
}
}
}
}
Advance_String(S);
}
printf("result = %d\n", Count_11 + Count_22 + Count_33 + Count_44);
}
This statement
if(Is_Milestone(S,21==1) // Braces are not matching. If statement is not having the closing brace. Compilation error should be given.
should be
if(Is_Milestone(S,21)==1)
I guess.
Also, the code you have posted doesn't seem to be correct. It will surely give compilation errors. You have declared Count22, but are using Count_22.
Please check.

Resources