Starting with PSP homebrew!

Result of 24 first hours with psp toolchain.

Just yesterday, I cloned psptoolchain from Github and built it:
And I’m just fluttered to do some programming on it.
Compiled some of shipped samples and tried it on PPSSPP emulator, also cloned & built Minecraft-PSP:

Had some problems though, i.e samples that were shipped needed a flag to be set in their makefile in order to work properly:


Which I took from one of their issues page:

And in the Minecraft-PSP, I needed to remove linkage with MMIO, since there was no such library provided, and comment out a few functions (which utilized MMIO, but were not called anyway). Here it is:


And the reflections sample:



My 35C3 CTF writeup IV – stringmaster2


Stringmaster2 is a continuation of the previous task, stringmaster1 which I covered here:
I recommend you read it, since I’ll reffer to it in this writeup.

What we find in the distrib folder this time is:


You may wonder why would they include the libc (against which stringmaster2 is linked), but we’ll come to this soon.
Now, to see what changed in the source from stringmaster1:


There are two differences:

  1. Code – There’s no spawn_shell function provided this time – we can’t dump its address and overwrite return pointer from the play function with it.
  2. Security measures – Binary is compiled with PIE and stack protector enabled.

PIE stands for Position Independent Executable – which relates to PIC – Position Independent Code, since PIE’s are entirely made from PIC.
On how does it work, you may check on Wikipedia, but what does it change in the context of solving this CTF is:

  • Even if we had the spawn_shell function ready in the binary, this time we couldn’t use its absolute address dumped from the binary like in 1996 task.
  • We can’t just breakpoint at arbitrarily given address using gdb – though we could fix it by recompiling our local stringmaster2 binary if we really wanted to do some inspection.

If stack protector is enabled, on stack frame, before return address and (optionally) frame pointer, there will be placed another value called stack canary. Since buffer overflow attack to redirect code execution, like in the 1996’s writeup, causes overwriting bytes starting at some variable’s address on the stack to the return pointer, values in between will be overwritten, and thus stack canary will change its value.
Compiler will inject code that checks if that value changed, and if so, it will close program to prevent exploiting.
You can read more on that on the Wikipedia:

But the good news is – those make no obstacles, since like in stringmaster1, we can overwrite arbitrary bytes on the stack frame, so the canary value won’t be overwritten untill we specifically do it, and for the PIC problem – we don’t have the spawn_shell function in the binary anyway, thus we’ll need to return somewhere else – but where will we?

Return to libc

Return to libc (r2libc) technique bases on replacing return pointer’s value with an address from the C library – it may be execve function, the same which was called in spawn_shell in stringmaster1, it may be any other function or even a specific line of code within those functions!
Calling execve this way would involve overwriting:


  1. Return pointer, previously storing an address of a line in main function, to which call from play will return.
    It would be overwritten with an address of execve function (8 bytes).
  2. Address after that, would need to point to a literal with “/bin/bash” (where would we find it – later) – 8 bytes.
  3. Again, pointer to a literal with “/bin/bash” – 8 bytes.
  4. Pointer to NULL, which would be 8 zeroed bytes.
  5. Again, pointer to NULL – 8 zeroed bytes.

Where can we find execv address?


Where can we wind the “/bin/bash” literal I mentioned?

st rings

It’s in the libc, just like the execv, but how would it manage to get there?

Let’s download libc sources and find out.
I got mine (version 2.27) from

libc_sourcegrep -rni . -e “/bin/sh” causes recursive searching of “/bin/sh” in current path.

As you see, there are some execve calls involving const char literals “/bin/sh” passed as an argument, which means, that those literals will be eventually stored in the .data section of libc .so file, with pointers to them pushed on the stack when one of those specific call happens.
Now, as we know how to manually craft function call to execve with “/bin/bash” as an argument – I will tell you why we won’t do it in this case – though what we’ve learned will come handy, since what we’ll really do is very similar.

See, when last time we did stringmaster1, swapping bytes to make return pointer store value to spawn_shell was very unstable – program crashed at random, and we only tried to swap 8 bytes!
Swapping all bytes from our manually crafted call stack would involve swapping 40 bytes, not mentioning, we would need to have those 40, mostly different values, somewhere on the leaked stack (and that involves a lot of luck).
What if there would be a way to jump directly to the place where execve(“/bin/bash”) is called in the libc (already with the argument on the stack!) just as we’ve seen in libc sources, without planting function arguments?

Return Oriented Progamming

ROP is the technique I’ve just suggested. Find some place in the existing code that you want to execute, get its address and jump to it. Those places that can be jumped to are called ROP gadgets.

We won’t waste time on finding it manually since there is already a tool specifically for finding execve gadget (though, I’ll make another post about this later), it’s called one_gadget and can be downloaded here:

After installation, we’ll call one_gadget with path to our libc as an argument:


That’s it, we’ve been provided with 3 variants, where registers have different values when calling. We’ll use the first once, but it makes us no difference which one we call.

Return to the plan

So we could use the same python exploit we used before, but with another value of return pointer to substitute (this time the gadget instead of spawn_shell), could we?
Er, no. There’s one last thing I didn’t mention – ASLR, which stands for Address Space Layout Randomization.

The gadget’s address we just took from the libc is an absolute address. It’s an address that takes into account only distance from the beginning of the .so file.
It would be valid only if we added the base libc address to it (the address under which libc is loaded in the system), and the base address changes due to ASLR every time we run the application!
See how the base address changes (ldd runs the program and prints addresses in which libraries are loaded):


As an experiment, let’s temporarily disable ASLR and invoke ldd once again:


As you can see, this time addresses don’t change – how easy it would be to exploit without ASLR! We could just take this permanent base libc address, add absolute address of our gadget and run python script that would change return pointer value.

So in what manner do we defeat ASLR?

Let’s have a detailed look on what’s on stack of a very simple program:


I’ve printed first 20 addresses on the stack when I was breakpointed in the main function. As you see, we have plenty of addresses that reffer to the C library!

First one, __libc_csu_init is the frame pointer in our stack frame, second one, <__libc_start_main+231> is the return pointer – the 231 part means that it points to 231-st byte after the beginning of this function. So we return into a libc function, that called our main before, when bootstrapping the process!
If you want some details on why those addresses are here (not of much relevance for further solving of this task), you can see the answer I gave on Stack Overflow:

Same thing happens in stringmaster2 case, we return to the <__libc_start_main+231> too, and what’s nice is this symbol is also leaked in stringmaster2.

Now it’s time to add facts:

  • We need libc base address (to which we’ll add absolute address of our gadget)
  • We have absolute (from gdb) and [base + absolute] address of <__libc_start_main+231> (from leak)
  • We can calculate base address!

Our addresses:

__libc_start_main = 0x21AB0
__libc_start_main + 231 = 0x21B97

At which position will we find  <__libc_start_main+231> in stringmaster2’s leak?
At the same we used before, 18-th octet of leaked data is the return pointer, and program tries to return to the <__libc_start_main+231>.

The final algorithm is the same as in stringmaster1, but adding a step before replacing return pointer, because we need to calculate the value with which we will replace:

  1. Get integer value from 8 bytes starting at (17 * 8) index of leaked bytes array
  2. Substract 0x21B97 from that value and assign it to libc_base
  3. Bytes for further replacing are [libc_base + gadget_addr]

That’s how ASLR can be defeated – by leaking some address from libc that we know what it points to (<__libc_start_main+231> in this case).

Final attack

This time I moved the part which sends commands to Client class, but in its essence, code is almost like stringmaster1, besides calculating libc-base.


So far, it was the most complex task, since it involved:

  • Knowing how libc bootstraps processes – that their flow starts not in your main function, but in _libc_start_main, then it redirects flow to your main, and finally returns to <__libc_start_main+231> in the end, when your main return.
    You can read more on that on this excellent blog:
  • Knowing, that because of ASLR, you can’t just use some address extracted from libc, without knowing the base at which libc is loaded at this current process instance.
  • Knowing about ROP gadgets, since crafting a call stack for execve by yourself is too unstable to work with given commands (swapping/replacing bytes on stack).


If you’re curious how it is, that one process can use libc at different address every instance, but its code itself does not change – read about Global Offset Table and Procedure Linkage Table:

Also, I’ll have a look at this:
since it looks popular and it’ll probably ease solving CTF’s.


My 35C3 CTF writeup III – stringmaster1


As this task is one category higher than the last one (very easy -> easy), I wrote a separate blog post about std::string, as some knowledge about it would be required for this task and I assume you’ve already read it.

After cd-ing to this task’s distrib directory we’ll see a binary and cpp source code, from which we know, that this binary already provides spawn_shell function, though does not call it anywhere, and consists of 2 other functions – play() and main():


As play function contains much boilerplate, I’ll omit the noise and post only the most important code from which we’ll deduce a vector of attack:


Before I tell you how to exploit a vulnerability that is visible on this picture, let’s first run the binary to show what it prints:


As you see, it’s a simple game of making two strings equal by gradually replacing/swapping characters.
Now, going back to the code from the image before – you may have already noticed, that the “replace” command does not provide any sanitization of returned index! If you input a character that does not exist in the string the program searches, it’s going to return std::string::npos, which is 8 bytes, 0xFFFFFFFFFFFFFFFF.

That means, that if we try to access
[string’s data pointer address] + [0xFFFFFFFFFFFFFFFF]
we’re going to end up with…
[string’s data pointer address] – minus one byte!
If you don’t get it, I explained pointer overflow in the post linked above.
As a consequence, we’re going to end up writing in string’s length field’s last byte. That will make string’s length to hold ridiculously high value, and allow us to print more information with “print” command:

You may wonder – what use do I have from this seemingly random data?

Vector of attack – return pointer overflow

This data provides us 2 important facts:

  • position of return pointer from play function;
    we’ll inject address of spawn_shell there.
  • position and value of a set of bytes that we could use with “swap” command;
    we’ll use them to swap bytes of play’s return pointer

Of course, we won’t do this manually as it’s too cumbersome. We’ll write a python script for that, but before, we’ll need 2 another facts that gdb’s going to provide:

  • spawn_shell address
  • address of instruction that comes just after call to play function in main function; it’s going to be the value of return pointer in play function – from that fact we’ll know which bytes to swap to make it return to spawn_shell instead

First one is a simple matter of:


spawn_shell’s address is 0x00000000004011a7 (left padded to 16 bytes since it’s x86_64 platform I’m working on).
In the second one, we’ve got to disassemble main and find the call to the play function:


As you see, return pointer value’s going to be 0x000000000040246d.

Now we have all the information we need; it’s time for the python script.
I won’t comment about it much since it’s self-commenting, but the algorithm is:

  1. Connect to program (it’s running on a Docker image on port 22224)
  2. Wait untill it sends the command prompt text (and do it every sending of some command)
  3. Send ‘replace X a’ – X since there are no upper case characters in those strings so it’s always safe to pick one of those – ‘a’ since the program seemingly doesn’t crush that much with replacing with a’s – but it’s only arbitrary taken character, any other will do.
  4. Send ‘print’ request to get info of what is after string’s local data pointer
  5. Find index of return pointer (0x40246d) in what ‘print’ returned – I found it manually by printing hex of returned data to console before writing the rest of the script and just hardcoded it, but one can easily code searching for.
  6. Find indexes of 0x40, 0x11, 0xa7 bytes. There’s a chance they will be somewhere in program’s memory, there’s a chance they won’t. If not, just restart the exploit, since the stringmaster1 binary is re-spawned every connection.
  7. Replace return pointer bytes with bytes from indexes we’ve found in the last step
  8. Print ‘exit’ to make it return to spawn_shell
  9. Send ‘ls’
  10. Send ‘cat flag.txt’
  11. Pwned

Final attack

screenshot from 2019-01-27 17-11-19


Docker was convenient, but I’ll try to implement hacking the binary without docker; hooking python script to stdout, without sockets, just for further experiments.
Also, my python skills need some improvement.


I started to make my writeup on 35C3-CTF’s task stringmaster1, but as I progressed I realized I’ll need another blog post to cover nuances of std::string without overstretching amount of input for a potential reader. Here we go, std::string byte-after-byte.

std::string in gdb

Imagine such a program:


Being compiled in given manner:


Let’s start it in gdb and decompile main function:


I highlighted 3 addresses: where do they point to?

As you probably know (and if you don’t, here’s a link to the Wikipedia):

The .data segment contains any global or static variables which have a pre-defined value and can be modified. That is any variables that are not defined within a function (and thus can be accessed from anywhere) or are defined in a function but are defined as static so they retain their address across subsequent calls.

Strings’ values that we hardcoded must be provided from somewhere, and addresses that disassembled code utilizes seems to point into .data segment. We can verify it by executing info variables in gdb, and scrolling to surroundings of this address:


As you see, this address is above the __data_start symbol (it has lower address), so it must be declared in the .data section.
Figuring it out would be easier by calling nm string_example, out of gdb (gdb prints much more than we need).
But I am driving off topic, let’s focus on the strings themself.

Let’s breakpoint at some address at the end of the program, after we initialized all three of strings with given values and printed strings’ addresses:


So strings’ addresses are:

s1 - 0x7fffffffda90
s2 - 0x7fffffffda70
s3 - 0x7fffffffda50

std::string takes 32 bytes on my x86_64 computer – one can verify that by running a program that prints sizeof std::string.
Since the strings are declared one after another, by printing 3 * 32 bytes after the address of first string, we’ll see all 3 of them:

x/24x 0x7fffffffda90 means: print next 24 [4 byte chunks] after 0x7fffffffda90 address.
You can simply calculate it by [bytes you want to be printed, [32*3] in our case / 4].

Here’s where the action starts.
Since we know that each std::string occupies 32 bytes, I’ll colorize them by different colors and label by variable name:

addresses_2 fixed.png

We know lengths of our strings, which are:

s1 - "123" - 3 - 0x3
s2 - "123456789" - 9 - 0x9
s3 - "1234567890abcdefgh!@#" - 21 - 0x15

Can we identify such bytes on the image? Yes. That’s the 4’th column on the image above:


From looking at the sources (we’ll cover them later) I know, that length should be 64 bit value, so length takes 2 columns (2 x 4 bytes = 64 bits).

What else can be identified?
Individual characters we put into the strings.

Look at the first and second column – 0x34333231 and then 0x38373635, and then 0x39, when converted from ascii values present what that string contain:


Marking our finding on the image with ‘d’ character, as an abbreviation from ‘data’:


But wait, look at the s3, the longest one – where’s the data we supplied? It doesn’t appear in the same manner as on the other strings… We’ll come to this in a second.
In the meantime – look at the first 4 bytes of our strings, on the second column.
In s2 and s1 it appears, that this value points (stores an address of) to the ‘d’ section.
So this value must be the pointer to the string’s data!
Again, mark our finding to the image with ‘p’, as from ‘pointer’:


And that answers the question stated just before – s3‘s data is stored away from the actual string, under 0x00614c20. Printing it reveals the string that we put into s3 before:


Which make:


That makes a question: why are some strings stored locally, and some externally, on the heap?*
And a question that watchful reader would state – what’s stored on the column we didn’t mark, between 4th and 8th bytes of std::string?

*We know, that address 0x00614c20 is on the heap, since we can check heap start/end addresses via info proc mappings in gdb:
info proc ma.png

0x00614c20 is bigger than 0x603000, but smaller than 0x635000.


std::string in sources

Answer to those questions lies in std::string’s sources.

You can access them, i.e by opening them in your IDE, like CLion – press Ctrl + N and type string – it will look for class definition.
Other way is just printing it from the command line, like:

pygmentize /usr/include/c++/8/bits/basic_string.h

One way or another, we’ll find std::string definition. The chunk which interested me is:


It defines string’s fields that we’ve marked on images. There’s string’s length, pointer to its data, an array for local data (defined as a union of either capacity or array of 15 bytes) – and the field we couldn’t figure out – allocator_type. Let’s mark it on the image:

That makes sense! The s1 and s2 strings we declared, which both had their data stored locally, have the same bytes in the data_allocator field, and data_allocator of s3 is zeroed.


So there’s a different string allocator used, depending on string’s length. Local buffer’s size is 15 bytes, so if we try to allocate a bigger string, like in case of s3, it’s going to allocate on heap instead. This optimization has its name and is called:

small string optimization

If you want to read more about it, here are the sources I used:

There’s more – std::string::npos

As the cpprerefence states:

This is a special value equal to the maximum value representable by the type size_type. The exact meaning depends on context, but it is generally used either as end of string indicator by the functions that expect a string index or as the error indicator by the functions that return a string index.


Although the definition uses 1size_type is an unsigned integer type, and the value of npos is the largest positive value it can hold, due to signed-to-unsigned implicit conversion. This is a portable way to specify the largest value of any unsigned type.

On my x86_64 platform, given program:




it’s 16 times F, since:

byte = 8 bit, max value is 0b11111111 = 2 ^ 7 + 2^6 + … + 2^0 = 128 + 64 + … + 1 = 255
byte in hex = 0xff, max value is (F * 16 + F) = 15 * 16 + 15= 255.

so in other words – it’s 8 bytes = 64 bits.

But I’m mentioning it since there can be programs that use it without sanitization, like:


Which prints:


As the condition we provided lacked checking if index is equal to npos, we’ve overwritten the length of some_string, and consequently made it to try printing all
0x5800000000000003 bytes that proceed address pointed by some_string‘s data pointer.

Let’s make 2 another strings in this program, and check if same thing happen to their lengths:


That prints:


So it’s repeatable! But why? How come, that


points to its length, always?

Well, as you probably know – variables can be overflown, and pointers also.
I’ll give you a short example of unsigned char overflow and then, pointer overflow – since they work in the same way:


It prints:


If we’re adding some value, to the value that’s already a maximum value for this platform, we’ll end up with… ‘some value’ minus 1!

As you learned before in this post, std::string’s length is 8 bytes before its local data. So if we’ll overflow pointer to the local data by adding max value it can hold, we’ll end up 1 byte before its local data, in length’s area, and that’s why some_string[std::string::npos] will always point to its length(…’s last byte)!


I wish I could just find blog post like this on the internet instead of writing it myself.

My 35C3 CTF writeup II – 1996


After cloning the repository and proceeding to the distrib folder, we find a binary alongside a C++ source file, which contents are:


Example usage of given binary:


As we have an access to the source code we can spot some facts:

  • binary is presumably compiled with no stack protector, which means there’s no extra code for preventing buffer overflows
  • there’s a spawn_shell function, which is never called
  • input buffer size is 1024 bytes

Another hint is the title – “1996 – It’s 1996 all over again!” – in 1996 Aleph One wrote an article for Phrack, called “Smashing The Stack For Fun and Profit” which introduced masses to the stack buffer overflow attack.

Notice: Trying to compile it on your own with included Makefile may result in a binary still blocking stack overflows – happened in my case, since my system by default passed stack-protecting flags. Try to hack shipped binary to save your time.

Vector of attack – stack overflow

For introduction to stack overflow attack I delegate you to the article I mentioned above – it’s linked in the resources section.
What we’ll need to perform it:

  • (virtual) address of the spawn_shell function
  • offset to the return pointer, in bytes

First one can be retrieved by running our binary in gdb:


As you see, it’s 0x400897.
Now we need to figure out the offset. It must be at least [1024 + 8] bytes, since on the stack, there’s a 1024 byte buf array and there must be a pointer to the stack frame which is 8 bytes on x86_64 architecture.
From now, we can either check the value manually or with gdb.

Manual way looks like this:

Let’s write a script that prints 1024 characters and pipe its output to the 1996 binary:


It worked, but still not caused segmentation fault or illegal instruction.
Gradually adding more bytes (more A’s) would reveal, that the offset is 1048 bytes:


gdb way looks like this:

We open the binary via gdb and disassemble main function:


We set a breakpoint at 0x0000000000400954, since after this instruction the stack will be cleared out (watch LiveOverflow’s videos linked in the resources to know how to identify that):


Run the program, type whatever on input so program would stop at our breakpoint.
Then examine registers EBP and ESP:


At this point, EBP should contain the address of the beginning of the stack and ESP should contain the address of the top of the stack.
Let’s substract those addresses to eventually have the offset:

0xffffdaa0 – 0xffffd690 = 0x410 = 1040.

But, as the EBP points at the beginning of a 8 byte address, after which is the return address we want to overwrite, we need to add 8 bytes to our value, so it becomes 1048.

Final attack

As we now know both offset and spawn_shell address we can feed it to 1996 binary with python:attack

We wrote spawn_shell address in reversed notation since gdb printed address in big endian notation, not little endian which is used by x86 processor.
Shell has been successfully spawned. We can print the flag:



Calculating stack size was a good exercise for knowing how calling a function works in assembly, that return address and stack frame address are put on the stack and popped in the end, and how to examine those in gdb. All needed resources are linked below.


As I said, 0xffffdaa0 is the address, where stack frame address lies.
Let’s break where we breakpointed before, and print surroundings of this address:


Command I typed means:

print in hexadecimal the next 64 bytes after [top of the stack pointer + 1024 bytes]

So we see the 24 bytes (first row and a half) before the return address and return address itself – 0x00400897 which is value we wrote.


My 35C3 CTF writeup I – Poet


This year’s Chaos Communication Congress featured an entry-level CTF contest alongside the original one. For everyone who don’t know what a CTF is or where to start, a talk followed:

I decided to publish my own solutions alongside description for educational purposes, though you’ll probably find other writeups on people’s blogs and repositories if you don’t find it clear.

We’ll start by cloning tasks from Github:

And proceed to the poet/distrib subdirectory. What we’ll find there is a binary, which on execution asks us to type some strings to stdin, and loops on incorrect answer:

That’s for the introduction. How did I exploit it?

Vector of attack – Buffer overflow

After checking if score depends of anything, what came to my mind was to try to overflow input buffer, typing enormous quantities of characters and checking what happens, if anything.

I pasted a big chunk of characters to the first one, for the poem’s content, but nothing happened.

I typed more characters than expected to the poem’s author buffer (not, that I knew how many characters it expected; again I just guessed that a possible vector of attack may be by overflowing) and eureka, score counter got unexpected, non zero value:


Next thing I did, was to find out exactly how many characters do I need to overflow. I just iterated over how many characters I typed, starting with aaa, then aaaa, then aaaaa, etc.
After a few tries I decided to try with 33 and 65 as it was a multiplicity-of-32 overflown by 1 and someone could set that multiplicity-of-32 value for memory alignment.
I found it, buffer size was 64; after typing 65 characters for the first time I got this score value changed:


So the next thing I checked: does the score change, depending on what character is the 65th character? I tried with zero:


So for the ‘a’ it’s 97 and for the zero it’s 48… Let’s have a look at the ASCII table:

Score matches value of the character I typed! Maybe I could use that to make score having value of 1 million, so it would print the flag for me?

Well, the last clue I needed was – when the value stops to change; how many characters proceeding after the 64 have an impact on the score. Spoiler: 4.

After that I deduced, that score must be stored in a 4 byte integer, and what I needed to figure out was… How do I write 1 million in binary. Then I needed to left pad it with zeroes to 32 bits, and write it down in 8-bit brackets, and check ASCII value of characters I just put into brackets. Here’s a drawing of what I did:



asd2.jpgWhat I meant was “making it 1 million from decimal to binary”

So after figuring out that it was [aaa overflowing sequence] + [@] + [B] + [^O] (non printable character) I typed this into the program and got the flag:



Analysis having the source code, aka why overflowing buffer caused changing score value?

Afterwards, I looked at the source code of the poem binary. As you see, score field was declared just after the author buffer. Why does it matter? Because for the compiler, there’s no abstraction for structures. Under the hood, it looks as though someone allocated [1024 + 64 + 4] bytes of continuous memory when created an instance of this struct. It’s how humans interact with this structure, referring to certain bytes by aliases (text, author, score) makes it less intuitive to understand why the trick worked.



PS: The proper way to run these tasks is by Docker, since It may be handy to write some scripts that would automate buffer overflow since you could use sockets for communication.

[X11] Further tinkering with X11 root window – Conky

This post reffers to the one before and I recommend you to read it:

Root windows

As we made through our attempt to write a screensaver for XScreenSaver server we stepped on a concept of virtual root windows.
As the Wikipedia states:

 The virtual root window is also used by XScreenSaver: when the screensaver is activated, this program creates a virtual root window, places it at the top of all other windows, and calls one of its hacks (modules), which finds the virtual root window and draws in it.

Our program found the virtual root window that XScreenSaver created when 1 minute of idleness passed and used its window handle to do OpenGL calls. But as you probably imagine, if we can find the root window, which is your desktop, we can draw whatever we want over it. And apparently, that’s how widgets (aka screenlets) work.
There’s a program called Conky (named after a doll from Trailer Park Boys TV series),
that does exactly the same thing. As its FAQ states:

Conky is a program which can display arbitrary information (such as the date, CPU temperature from i2c, MPD info, and anything else you desire) to the root window in X11. Conky normally does this by drawing to the root window, however Conky can also be run in windowed mode (though this is not how conky was meant to be used).

As the concept by which Conky’s screenlets work is similiar to our screensaver’s, let’s install it and check anatomy of screenlets.


Process of installing either from sources or packages is described on their wiki:
…and I’m assuming that when you type ‘conky‘ in your terminal, it starts Conky process.
I’m using Ubuntu 16.04 with Compiz.

What’s optional is conky-manager, you may build it from source:

Sample screenlet

As Conky has built-in support for Lua scripts, it doesn’t mean that conky configuration files are written in Lua (they use Lua syntax since Conky 1.10). They’re more like configuration files that define what is drawn and where, and to get some values, or draw something, they can call Lua scripts. They can also call bash scripts. For some values they need no Lua nor bash, because they are handled by Conky itself.

Conky developers even distribute Conky-related Lua tutorial:

Making a sample screenlet consists of:

  1. Writing ~/.conkyrc file, possibly copy-pasting some portions of configuration from other screenlets because it’s redundant.
    Possible configuration settings are defined here:
  2. (optional) Writing Lua script or bash script that you may want to call in it, maybe also putting some images/other resources into script directory. You can refer to the tutorial linked above.

Example conkyrc with Lua script (not mine):

One particularly creative conky

As a fan of Thinkpads, when I’ve seen this:

I immediately downloaded scripts this guy shared and set them up on my own Ubuntu.
What was needed:

  1. Download this config file and save it as ~/.conkyrc file:
  2. Download shell scripts and save them under ~/.bin directory:
  3. Edit those sh scripts, they relate to /home/u0xpsec directory, change it to your own.
  4. In terminal, type ‘conky’.

I experienced one annoying bug; on clicking desktop, this conky disappeared.
Link below helped disappearing on desktop click, but didn’t help disappearing on alt+tab to desktop (which hides everything):

What helped me on disappearing on ‘hide all windows’ was the tip i found on Arch Linux Wiki:

Using Compiz: If the ‘Show Desktop’ button or key-binding minimizes Conky along with all other windows, start the Compiz configuration settings manager, go to “General Options” and uncheck the “Hide Skip Taskbar Windows” option.

To download Compiz configuration settings manager type:

sudo apt-get install compizconfig-settings-manager

And run it via ‘ccsm’.

Alas, this conky took ~2% of CPU (quering system status is costly), so you may think twice before installing it.


Conky has its own subreddits:

And you can find more screenlets on deviantart, i.e this one:

Which is also very amusing.

[X11] Writing X11 screensaver with C++ & OpenGL


Download XScreenSaver. In your binary you can’t use glfw to create window, use GLX instead, because you have to hook up to the virtual root window.


As of Ubuntu 11.10 screensaver server isn’t placed in the distro (from that moment on it supports only screen blanking), to enjoy graphical screensavers we’ve got to install it for ourselves:


After installing, place where screensavers are stored is /usr/lib/xscreensaver,
where listing shows some default ones:

Screenshot from 2018-12-26 23-12-16

They’re ordinary executable files:


…and when running one of them they create a window with a screensaver displayed:



That’s great, or that’s more what I thought, because as I dropped there one of my OpenGL programs (I put them on my Github) naively thinking that every arbitrary binary can be set up as a screensaver I ran:


Which launches tool for choosing & setting up a screensaver from /usr/lib/xscreensaver:


As I eventually selected my program (it’s called Screensaver on the list above), it occured to me that there are 2 problems.

  1. My program does not show in the little squared window of xscreensaver-demo when selected; it just runs in a new window, unlike screensavers shipped with package.
  2. When 1 minute passes and XScreenSaver launches my own screensaver, all what I see are logs from my screensaver on some black screen, not the window it was supposed to create (as I’ve seen for a splitsecond when moved a mouse, window was indeed created, but it wasn’t floating on top of the others despite hints I passed to glfw, this black screen was shadowing it).

What these problems have in common?

There must be some parent-window to hook up when launching my screensaver, so it wouldn’t just run in a new window but rather take a handle from another process. Looks like I can’t just select any arbitrary program and expect it to work as a screensaver, pity.

A look at the ‘Root window’ Wikipedia article confirmed my assumptions:

The virtual root window is also used by XScreenSaver: when the screensaver is activated, this program creates a virtual root window, places it at the top of all other windows, and calls one of its hacks (modules), which finds the virtual root window and draws in it.

Down the rabbit hole

I needed to get some example code of screensavers that are shipped within the XScreenSaver or any other working artifacts. I got a clever, concise example from Github:

Compiled it:


and it actually worked as other examples!


So that’s the way that RobertZenz did it in his lavanet screensaver:

  1. He included a header called vroot.h, which is an abbreviation from virtual root window. Root window is the window which is the bottom-most, it’s a parent to every other window. As Wikipedia states:

    In the X Window System, every window is contained within another window, called its parent. This makes the windows form a hierarchy. The root window is the root of this hierarchy. It is as large as the screen, and all other windows are either children or descendants of it.

    File’s content is 106 lines, more than a half of it is  description which I’ll just put here for clarity because it describes what it does better than I would:
    carbon (5)

  2. In lavanet.c, vroot.h is used it this way:carbon (4)
    Rest of the code is GLX calls and lavanet logics which is not important for us.

OK! Looks like I can’t just make a new window with glfw.
I need to get that root window first.

At this point I hoped that there’s a way in glfw to create a native X11 Window, configure it (with vroot.h) and pass it to the glfw, since glfw exposes some native calls:

…but I was wrong. There’s just no way. To get GLFWwindow object, you’ve got to call glfwCreateWindow and it’s the only way.
There’s even an issue opened on Github in 2013 which was active through the years and the last answer is from 20 days before I wrote this post:

It was exactly the same problem I was facing, but feature that would provide passing native handle is still not shipped.

What’s left?

Since I used glfw only for convenience (it abstracts creating window so developer wouldn’t bother writing platform-specific branches) I could use GLX to get that native window handle.

GLX is like an interface for OpenGL calls that can talk with an X11 server.
As Windows has its own windowing system, it has its own equivalent of GLX, called WGL.
If you’re getting confused, reffer to the Wikipedia and this answer on StackOverflow:

The glfw way (code before)

My previous code I used to create windows with glfw looked like this:

carbon (2)

Not much, right? There were some glfw calls on program start:

carbon (3)

But that’s all.

The GLX way (code after)

I got window handle exactly the same way as in the lavanet example.
Then, in my main loop, I couldn’t do anymore:


So I replaced it with:


(I also change classname to WrapperWindow so it wouldn’t conflict with X11 window).

I had a window, but I still needed to register a graphical context. And that’s where this very helpful post came:

So the class after changes looked like that:

carbon (1)


As it was inside my opengl-playground CMake project that displayed textured cubes, I simply built it and copied resulting binary into /usr/lib/xscreensaver/.

Then, typed xscreensaver-demo, selected my screensaver and could preview it – it worked.


Looks like it’s not that hard to make a screensaver for X11, just make sure you create a native window by your own, the rest is just ordinary OpenGL.

I created a separate CMake project with this X11 screensaver afterwards and put it on Github, so you could try it for yourself. For clarity, I cut the logics, so it only fills screen with colours every some amount of time. OpenGL and X11 are the only dependencies.

By the way, this time I used a service called carbon:
It saved my time – generates images from source code.

Sources (or just interesting related stuff to read)

How to make an X11 screensaver with python: