strtok() C++ wrapper

In this article, I share with you a simple C++ class that wraps the string tokenization function strtok(). The QuickTokenizer class makes it easy to tokenize and enumerate the tokens in a thread-safe manner.

The class code

//////////////////////////////////////////////////////////////////////////
class QuickTokenizer
{
private:
  char *buf;
  char *token;
  char *ctx;

  void FreeBuffers()
  {
    if (this->token != NULL)
    {
      free(this->token);
      this->token = NULL;
    }
    if (this->buf != NULL)
    {
      free(this->buf);
      this->buf = NULL;
    }
  }

public:
  QuickTokenizer() : buf(NULL), token(NULL)
  {

  }

  const char *Tokenize(
    const char *str,
    const char *tok)
  {

    this->buf = _strdup(str);
    this->token = _strdup(tok);

    return strtok_s(buf, token, &ctx);
  }

  const char *NextToken()
  {
    return strtok_s(NULL, token, &ctx);
  }

  ~QuickTokenizer()
  {
    FreeBuffers();
  }
};

Continue reading “strtok() C++ wrapper”

Detect executable format using Python

In this article, I am sharing with you a small Python script that lets you detect if a file is an executable file and what platform the executable is targeting.

The following formats for 32 bits and 64bits processors are supported:

  • Mach-O files: both regular and universal formats
  • Windows PE files
  • Linux ELF files

The script

#---------------------------------------------------------------------
EXEFLAG_NONE        = 0x0000
EXEFLAG_LINUX       = 0x0001
EXEFLAG_WINDOWS     = 0x0002
EXEFLAG_MACOS       = 0x0004
EXEFLAG_MACOS_FAT   = 0x0008
EXEFLAG_32BITS      = 0x0010
EXEFLAG_64BITS      = 0x0020

# Keep signatures sorted by size
_EXE_SIGNATURES = (
    ("\x4D\x5A", EXEFLAG_WINDOWS),
    ("\xCE\xFA\xED\xFE", EXEFLAG_MACOS | EXEFLAG_32BITS),
    ("\xCF\xFA\xED\xFE", EXEFLAG_MACOS | EXEFLAG_64BITS),
    ("\xBE\xBA\xFE\xCA", EXEFLAG_MACOS | EXEFLAG_32BITS | EXEFLAG_MACOS_FAT),
    ("\xBF\xBA\xFE\xCA", EXEFLAG_MACOS | EXEFLAG_64BITS | EXEFLAG_MACOS_FAT),
    ("\x7F\x45\x4C\x46\x01", EXEFLAG_LINUX | EXEFLAG_32BITS),
    ("\x7F\x45\x4C\x46\x02", EXEFLAG_LINUX | EXEFLAG_64BITS)
)

def get_exeflags(filepath):
    try:
        with open(filepath, "rb") as f:
            buf = ""
            buf_len = 0
            for sig, flags in _EXE_SIGNATURES:
                sig_len = len(sig)
                if buf_len < sig_len:
                    buf += f.read(sig_len - buf_len)
                    buf_len = sig_len

                if buf == sig:
                    return flags
    except:
        pass

    return EXEFLAG_NONE

Continue reading “Detect executable format using Python”

Gun with a tracking device from the “Dreamcatcher” movie

I watched the Dreamcatcher movie a while back. It is a nice movie involving young boys, now adults, who have been gifted psychic abilities by an alien. That alien, in the hiding, looks like a human being and waits for the right moment to defend the Earth from other hostile aliens.

In the movie we see a gun with a tracking device in it, I like the concept (not that this is something new). You would never suspect that your gun is traceable:

Speaking of dreamcatchers, I found this nice dreamcatcher on Amazon, check it out:

Dreamcatcher

You might also like:

Jokes for the month of June, 2017

No wonder

A policeman stops a reckless and speeding young driver. The policeman tells the driver: “Do you know that you were driving beyond the speed limit?”

The young, with a smile on his face, replies: “No wonder, this is the first time I drive”

I will be right back

The wife to the husband: “I will go to my neighbor and grab some salt, keep an eye on the food while I am gone. I will be back soon, it will be just 5 minutes at most”

The husband: “How should I keep an eye on the food? What should I do?”
The wife: “It is not much, really! Just stir the pot every half an hour”

The Three Musketeers

Two friends were chatting.
The first one said: “My wife was reading the three musketeers and she gave birth to a triplet. Can you imagine that?!”

His friend replied back in amazement: “God forbids! I actually left my wife when she started reading Ali Baba and the 40 thieves”

True to her word

Man: My wife is one of the few women who stick to their words
The other man: How come?
Man: We have been married since 50 years already and every time I ask her how old is she, she answers 30 years old.

The inventor

The friend: “So tell me, what is the profession of the new tenant you have living in your apartment?”
The landlord: “Oh, an inventor”
The friend: “Really?! What does he invent?”
The landlord: “He keeps inventing excuses so he does not pay the rent!”
You might also like:

Introducing Ganxo v0.1 – An open source API hooking framework

Hello,

Today I release the first Alpha version of Ganxo (pronounced as “Gun Show” or “Gan Chou”), an open source API hooking framework. In Catalan, Ganxo means “hook”, thus the framework’s name.

Writing an API hooking framework was always on my to do list. I started developing Ganxo back in April 2016 and after two weeks of development during my free time, I got busy with other things and abandoned my efforts.

My initial goals were to accomplish the following before going public with it:

  • Support x86 and x64 hooking
  • Write a more extensive test suite
  • Fully document it

This past weekend, I decided to release Ganxo even though I have not met all my goals. As of today, Ganxo works on MS Windows and supports x86 API hooking. The groundwork is laid down and it should be easy to add x64 bits hooking support on Windows or even just port it to other operating systems.

Feel free to clone the code from here and start using it today.

Stay tuned, I plan more features in the coming future!

flower separator
batchography-good-resDo you want to master Batch Files programming? Look no further, the Batchography is the right book for you.

Available in print or e-book editions from Amazon.
flower separator

You might also like:

Wandering towards the sunset: My second painting

I am no artist but this is my second painting.
I enjoyed painting this one on 06/10/2017 at Pinot’s Palette

You might also like:

Are you a fan of The Reverse-Flash character? I am!

Ever since I watched “The Flash” series on Netflix, I fell in love with the Reverse-Flash character. Why not love the regular The Flash character you ask?

Well because, unlike The Flash who got his powers by accident, the Reverse-Flash used knowledge to acquire his powers and go back in time. Another simpler answer: I just love the yellow on red color! 🙂

I bought the Reverse-Flash T-shirt from Amazon. It looks good and has very good quality:

I also got the action figure:

You might also like:

Takeaways from the “California Driver Handbook 2017”

In this article, I share with you my notes from the “California Driver Handbook 2017“. Perhaps it will come in handy when you are preparing for the driving test in California:

Notes:

  • Speed limit
    • The maximum speed limit on most California highways is 65 mph. You may drive 70 mph where posted. Unless otherwise posted, the maximum speed limit is 55 mph on a two-lane undivided highway and for vehicles towing trailers.
    • California has a “Basic Speed Law.” This law means that you may never drive faster than is safe for current conditions. For example, if you are driving 45 mph in a 55 mph speed zone during a dense fog, you may be cited for driving “too fast for conditions.”
    • The speed limit in any alley is 15 mph.
    • Business or Residential Districts: The speed limit is 25 mph, unless otherwise posted.
  • Stopping and safe distance
    • At 55mph, it takes about 400 feet to react and bring the vehicle to a complete stop, and at 35mph, it takes about 210 feet.
  • Pedestrians, bicyclists
    • Pedestrians, bicyclists, or other vehicles alongside you may experience sudden strong winds when passing or being passed. Slow down and pass safely, and pass only at a safe distance (typically 3 feet or more for bicyclists).
  • Blind Intersections
      The speed limit for a blind intersection is 15 mph. An intersection is considered “blind” if there are no stop signs at any corner and you cannot see for 100 feet in either direction during the last 100 feet before crossing.
  • Near animals
    • If you see a stray animal in your path, slow down or stop if it’s safe. Do not swerve as you may lose control of your vehicle and cause an accident.

Continue reading “Takeaways from the “California Driver Handbook 2017””

Batchography: Batch files and Unicode

Recently, I had to update my popular utility that resets NTFS files permission to support Unicode paths. I had to investigate how to add Unicode support in Batch scripts. It seems that this was a topic I forgot to add into my comprehensive Batch files programming book.

This article is the result of my investigation, in which I am going to show you how to add Unicode support to your Batch file scripts in 3 easy steps.

Continue reading “Batchography: Batch files and Unicode”

Infamous quotes about women

Some infamous sayings about women:

  • A woman is like a bee, she feeds the man honey for a month just to punish him and sting him all his life
  • The devil is the teacher of man, but he is the disciple of the woman
  • The devil needs 10 hours to trick a man, but a woman needs no more than one hour to trick ten devils
  • The best weapon for a man against a woman is another woman
  • A woman is not bothered if she owns less than others until she discovers another woman owning more than her
  • The tears of a woman are but a ruse to attack and control the man
  • The more freedom a woman acquires the shorter her skirt becomes
  • There’s one reason for a man to make a purchase, but for a woman she has one of many:
    • Because her husband told her: “Do not buy it”
    • Because the product makes her feel slimmer
    • Because it is fancy and made in Paris
    • Because her neighbor cannot buy the same item
    • Because no other woman she knows has this item
    • Because all other women have the item
    • Because the item makes her look unique
    • Because…

  • “Epicurus, how often should one man have sex with a woman?”, Epicurus answered: “Whenever he wants to be weaker than himself”
  • Behind each man a great woman. Behind each successful woman, a failed love story.
  • The woman is a devil that let’s you into hell through the doors of heaven
  • Gold is tested with fire, but a woman is tested with gold
  • A woman loves that her husband remembers her birth day as long as he forgets her age
  • If you find friendship between two women, it is a matter of time before it turns into an alliance against a third woman
  • A successful man, is the man who can make more money than his wife can spend. A successful woman is the one who can find such man.
  • The treasures of the whole world are not worth a single righteous woman
  • The jealousy of a woman is the key to her divorce
  • An ugly woman hates the mirror

 

Note: This article will be kept up to date with latest quotes.

 

You might also like:

Batchography: Embedding Python scripts in your Batch file script

I keep writing about Batch programming, so it is obvious by now that Batch files programming has become one of my favorite activities. Every time I have to write a quick script to automate a task, I go first for the Batch files programming language. If that does not do the job, I use the Python programming language and if that fails, I go for C/C++ before deciding to writing using the assembly language.

Now, what about combining the two languages to achieve what you want?

That’s today’s topic. It is an excerpt from Chapter 4 in the Batchography book. Continue reading “Batchography: Embedding Python scripts in your Batch file script”

How many faces you see?

One of my readers (thank you very much) left a comment saying that the people in this picture represent the faces of Indian freedom fighter and politicians:

  • Mahatma Gandhi
  • Rabindranath Tagore
  • Bala Gangadhara Tilak
  • Bhagat Singh
  • Jawahara Lal Nehru
  • Lal Bhadur Shastri
  • Subhash Chandra Bose
  • Indira Gandhi
  • Rajiv Gandhi

You might also like:

Using C/C++ TLS callbacks in Visual Studio with your 32 or 64bits programs

In the following article, I share with you how to use TLS callbacks in your C/C++ program compiled with Visual Studio.

Background

TLS (thread local storage) callbacks are a mechanism provided by the Windows loader to give your program a chance to do initialization/deinitialization tasks when the process starts, terminates, a thread is created or terminated.

A TLS callback has the following prototype:

typedef VOID (NTAPI *PIMAGE_TLS_CALLBACK) (
    PVOID DllHandle,
    DWORD Reason,
    PVOID Reserved);

The Reason argument can be any of the following constants:

  • DLL_PROCESS_ATTACH   = 1
  • DLL_PROCESS_DETACH  = 0
  • DLL_THREAD_ATTACH  = 2
  • DLL_THREAD_DETACH  = 3

The TLS callbacks are encoded inside the compiled program’s TLS data directory(IMAGE_DIRECTORY_ENTRY_TLS). Please refer to the PE file structure. Continue reading “Using C/C++ TLS callbacks in Visual Studio with your 32 or 64bits programs”