Decoding MySQL ~/.mylogin.cnf

| Created | Modified

Little tool to decode MySQL’s badly secured login-path. It does the same like the official MySQL server tools “my_print_defaults” (based on MySQL OSS python libs).

More security can be achieved by: https://www.percona.com/blog/2016/10/12/encrypt-defaults-file/

#!/usr/bin/env php
<?php

$fp = fopen(getenv('HOME') . '/.mylogin.cnf', "r");
if (!$fp) {
    die("Cannot open .mylogin.cnf");
}

fseek($fp, 4);
$key = fread($fp, 20);

// generate real key
$rkey = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
for ($i = 0; $i &lt; strlen($key); $i++) {
    $rkey[$i % 16] = ($rkey[$i % 16] ^ $key[$i]);
}

$section = null;
$settings = [];

while ($len = fread($fp, 4)) {

    // as integer
    $len = unpack("V", $len);
    $len = $len[1];

    // decrypt
    $crypt = fread($fp, $len);
    $plain = openssl_decrypt($crypt, 'aes-128-ecb', $rkey, true);
    $decoded = preg_replace("/[^\\x32-\\xFFFF]/", "", $plain);
    if (preg_match('/^\[([^\]]+)]/', $decoded, $matches)) {
        $section = $matches[1];
        $settings[$section] = [];
    } elseif (preg_match('/^(\w+)=(.*)/', $decoded, $matches)) {
        $settings[$section][$matches[1]] = $matches[2];
    }
}
fclose($fp);

echo json_encode($settings, JSON_PRETTY_PRINT);

src | [_mylogin_cnf of mycli][https://github.com/dbcli/mycli/blob/master/mycli/config.py]