// util to search for a lost ssh key password,
// searches password for files specified on the commandline, passwords taken from stdin
//
// to build: copy this file to the openssh source directory
// add this to the Makefile
//
// findpw$(EXEEXT): $(LIBCOMPAT) libssh.a findpw.o
// 	$(LD) -o $@ findpw.o $(LDFLAGS) -lssh -lopenbsd-compat $(LIBS)
//
// and add findpw$(EXEEXT)  to the TARGETS=  list
//
#include "includes.h"

#include <sys/types.h>
#include <sys/stat.h>
#include <sys/param.h>

#include <openssl/evp.h>
#include "openbsd-compat/openssl-compat.h"

#include <fcntl.h>
#include <pwd.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include "xmalloc.h"
#include "ssh.h"
#include "rsa.h"
#include "log.h"
#include "key.h"
#include "buffer.h"
#include "authfd.h"
#include "authfile.h"
#include "pathnames.h"
#include "misc.h"


extern char *__progname;

void sanitizepw(char *pw)
{
    int i= strlen(pw);
    while (i>=0 && pw[i]<=' ')
        pw[i--]= 0;
}
int main(int argc, char**argv)
{
    __progname = ssh_get_progname(argv[0]);
    init_rng();
    seed_rng();
    OpenSSL_add_all_algorithms();

    char *found= malloc(argc);
    memset(found, 0, argc);

    int i;
    char passphrase[256];
    while (fgets(passphrase, 255, stdin))
    {
        passphrase[255]= 0;
        sanitizepw(passphrase);

        for (i=1 ; i<argc ; i++) {
            if (found[i])
                continue;
            char *fname= argv[i];
            if (key_load_private(fname, passphrase, NULL)) {
                printf("found: %s %s\n", fname, passphrase);
                found[i]= 1;
            }
        }
    }
    for (i=1 ; i<argc ; i++) {
        if (!found[i])
            printf("unknown: %s\n", argv[i]);
    }
    return 0;
}


