#!/usr/bin/env python

# 1) See https://security.stackexchange.com/a/42350
# and https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format
# for the sslkeylog.log format description
# 2) See sni.cpp for the pginx ssl_secrets.log format implementation
# TODO(velavokr): tls 1.3

import argparse


def parse_ssl_secret_log_line(line):
    parsed = {}
    for token in line.split(' '):
        name, value = token.strip().split('=', 2)
        parsed[name] = value.lower()
    return parsed


def main():
    parser = argparse.ArgumentParser(
        "Converts pginx ssl_secrets.log to the sslkeylog.log format which the wireshark understands"
    )
    parser.add_argument(
        '-i', dest='inp', type=argparse.FileType('r'), default='-', metavar="ssl_secrets.log",
        help="(default is %(default)s)"
    )
    parser.add_argument(
        '-o', dest='out', type=argparse.FileType('w'), default='-', metavar="sslkeylog.log",
        help="(default is %(default)s)"
    )
    args = parser.parse_args()
    try:
        for line in args.inp:
            args.out.write("CLIENT_RANDOM {client_random} {master_secret}\n".format(
                **parse_ssl_secret_log_line(line))
            )
    finally:
        args.out.close()


if __name__ == "__main__":
    main()
