⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 cmdgen.c

📁 远程登陆工具软件源码 用于远程登陆unix
💻 C
📖 第 1 页 / 共 3 页
字号:
/*
 * cmdgen.c - command-line form of PuTTYgen
 */

#define PUTTY_DO_GLOBALS

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <limits.h>
#include <assert.h>
#include <time.h>

#include "putty.h"
#include "ssh.h"

#ifdef TEST_CMDGEN
/*
 * This section overrides some definitions below for test purposes.
 * When compiled with -DTEST_CMDGEN:
 * 
 *  - Calls to get_random_data() are replaced with the diagnostic
 *    function below (I #define the name so that I can still link
 *    with the original set of modules without symbol clash), in
 *    order to avoid depleting the test system's /dev/random
 *    unnecessarily.
 * 
 *  - Calls to console_get_line() are replaced with the diagnostic
 *    function below, so that I can run tests in an automated
 *    manner and provide their interactive passphrase inputs.
 * 
 *  - main() is renamed to cmdgen_main(); at the bottom of the file
 *    I define another main() which calls the former repeatedly to
 *    run tests.
 */
#define get_random_data get_random_data_diagnostic
char *get_random_data(int len)
{
    char *buf = snewn(len, char);
    memset(buf, 'x', len);
    return buf;
}
#define console_get_line console_get_line_diagnostic
int nprompts, promptsgot;
const char *prompts[3];
int console_get_line(const char *prompt, char *str, int maxlen, int is_pw)
{
    if (promptsgot < nprompts) {
	assert(strlen(prompts[promptsgot]) < maxlen);
	strcpy(str, prompts[promptsgot++]);
	return TRUE;
    } else {
	promptsgot++;		       /* track number of requests anyway */
	return FALSE;
    }
}
#define main cmdgen_main
#endif

struct progress {
    int phase, current;
};

static void progress_update(void *param, int action, int phase, int iprogress)
{
    struct progress *p = (struct progress *)param;
    if (action != PROGFN_PROGRESS)
	return;
    if (phase > p->phase) {
	if (p->phase >= 0)
	    fputc('\n', stderr);
	p->phase = phase;
	if (iprogress >= 0)
	    p->current = iprogress - 1;
	else
	    p->current = iprogress;
    }
    while (p->current < iprogress) {
	fputc('+', stdout);
	p->current++;
    }
    fflush(stdout);
}

static void no_progress(void *param, int action, int phase, int iprogress)
{
}

void modalfatalbox(char *p, ...)
{
    va_list ap;
    fprintf(stderr, "FATAL ERROR: ");
    va_start(ap, p);
    vfprintf(stderr, p, ap);
    va_end(ap);
    fputc('\n', stderr);
    cleanup_exit(1);
}

/*
 * Stubs to let everything else link sensibly.
 */
void log_eventlog(void *handle, const char *event)
{
}
char *x_get_default(const char *key)
{
    return NULL;
}
void sk_cleanup(void)
{
}

void showversion(void)
{
    char *verstr = dupstr(ver);
    verstr[0] = tolower(verstr[0]);
    printf("PuTTYgen %s\n", verstr);
    sfree(verstr);
}

void usage(void)
{
    fprintf(stderr,
	    "Usage: puttygen ( keyfile | -t type [ -b bits ] )\n"
	    "                [ -C comment ] [ -P ]\n"
	    "                [ -o output-keyfile ] [ -O type | -l | -L"
	    " | -p ]\n");
}

void help(void)
{
    /*
     * Help message is an extended version of the usage message. So
     * start with that, plus a version heading.
     */
    showversion();
    usage();
    fprintf(stderr,
	    "  -t    specify key type when generating (rsa, dsa, rsa1)\n"
	    "  -b    specify number of bits when generating key\n"
	    "  -C    change or specify key comment\n"
	    "  -P    change key passphrase\n"
	    "  -O    specify output type:\n"
	    "           private             output PuTTY private key format\n"
	    "           private-openssh     export OpenSSH private key\n"
	    "           private-sshcom      export ssh.com private key\n"
	    "           public              standard / ssh.com public key\n"
	    "           public-openssh      OpenSSH public key\n"
	    "           fingerprint         output the key fingerprint\n"
	    "  -o    specify output file\n"
	    "  -l    equivalent to `-O fingerprint'\n"
	    "  -L    equivalent to `-O public-openssh'\n"
	    "  -p    equivalent to `-O public'\n"
	    );
}

static int save_ssh2_pubkey(char *filename, char *comment,
			    void *v_pub_blob, int pub_len)
{
    unsigned char *pub_blob = (unsigned char *)v_pub_blob;
    char *p;
    int i, column;
    FILE *fp;

    if (filename) {
	fp = fopen(filename, "wb");
	if (!fp)
	    return 0;
    } else
	fp = stdout;

    fprintf(fp, "---- BEGIN SSH2 PUBLIC KEY ----\n");

    if (comment) {
	fprintf(fp, "Comment: \"");
	for (p = comment; *p; p++) {
	    if (*p == '\\' || *p == '\"')
		fputc('\\', fp);
	    fputc(*p, fp);
	}
	fprintf(fp, "\"\n");
    }

    i = 0;
    column = 0;
    while (i < pub_len) {
	char buf[5];
	int n = (pub_len - i < 3 ? pub_len - i : 3);
	base64_encode_atom(pub_blob + i, n, buf);
	i += n;
	buf[4] = '\0';
	fputs(buf, fp);
	if (++column >= 16) {
	    fputc('\n', fp);
	    column = 0;
	}
    }
    if (column > 0)
	fputc('\n', fp);
    
    fprintf(fp, "---- END SSH2 PUBLIC KEY ----\n");
    if (filename)
	fclose(fp);
    return 1;
}

static int move(char *from, char *to)
{
    int ret;

    ret = rename(from, to);
    if (ret) {
	/*
	 * This OS may require us to remove the original file first.
	 */
	remove(to);
	ret = rename(from, to);
    }
    if (ret) {
	perror("puttygen: cannot move new file on to old one");
	return FALSE;
    }
    return TRUE;
}

static char *blobfp(char *alg, int bits, char *blob, int bloblen)
{
    char buffer[128];
    unsigned char digest[16];
    struct MD5Context md5c;
    int i;

    MD5Init(&md5c);
    MD5Update(&md5c, blob, bloblen);
    MD5Final(digest, &md5c);

    sprintf(buffer, "%s ", alg);
    if (bits > 0)
	sprintf(buffer + strlen(buffer), "%d ", bits);
    for (i = 0; i < 16; i++)
	sprintf(buffer + strlen(buffer), "%s%02x", i ? ":" : "",
		digest[i]);

    return dupstr(buffer);
}

int main(int argc, char **argv)
{
    char *infile = NULL;
    Filename infilename;
    enum { NOKEYGEN, RSA1, RSA2, DSA } keytype = NOKEYGEN;    
    char *outfile = NULL, *outfiletmp = NULL;
    Filename outfilename;
    enum { PRIVATE, PUBLIC, PUBLICO, FP, OPENSSH, SSHCOM } outtype = PRIVATE;
    int bits = 1024;
    char *comment = NULL, *origcomment = NULL;
    int change_passphrase = FALSE;
    int errs = FALSE, nogo = FALSE;
    int intype = SSH_KEYTYPE_UNOPENABLE;
    int sshver = 0;
    struct ssh2_userkey *ssh2key = NULL;
    struct RSAKey *ssh1key = NULL;
    char *ssh2blob = NULL, *ssh2alg = NULL;
    const struct ssh_signkey *ssh2algf = NULL;
    int ssh2bloblen;
    char *passphrase = NULL;
    int load_encrypted;
    progfn_t progressfn = is_interactive() ? progress_update : no_progress;

    /* ------------------------------------------------------------------
     * Parse the command line to figure out what we've been asked to do.
     */

    /*
     * If run with no arguments at all, print the usage message and
     * return success.
     */
    if (argc <= 1) {
	usage();
	return 0;
    }

    /*
     * Parse command line arguments.
     */
    while (--argc) {
	char *p = *++argv;
	if (*p == '-') {
	    /*
	     * An option.
	     */
	    while (p && *++p) {
		char c = *p;
		switch (c) {
		  case '-':
		    /*
		     * Long option.
		     */
		    {
			char *opt, *val;
			opt = p++;     /* opt will have _one_ leading - */
			while (*p && *p != '=')
			    p++;	       /* find end of option */
			if (*p == '=') {
			    *p++ = '\0';
			    val = p;
			} else
			    val = NULL;
			if (!strcmp(opt, "-help")) {
			    help();
			    nogo = TRUE;
			} else if (!strcmp(opt, "-version")) {
			    showversion();
			    nogo = TRUE;
			}
			/*
			 * A sample option requiring an argument:
			 * 
			 * else if (!strcmp(opt, "-output")) {
			 *     if (!val)
			 *         errs = TRUE, error(err_optnoarg, opt);
			 *     else
			 *         ofile = val;
			 * }
			 */
			else {
			    errs = TRUE;
			    fprintf(stderr,
				    "puttygen: no such option `--%s'\n", opt);
			}
		    }
		    p = NULL;
		    break;
		  case 'h':
		  case 'V':
		  case 'P':
		  case 'l':
		  case 'L':
		  case 'p':
		  case 'q':
		    /*
		     * Option requiring no parameter.
		     */
		    switch (c) {
		      case 'h':
			help();
			nogo = TRUE;
			break;
		      case 'V':
			showversion();
			nogo = TRUE;
			break;
		      case 'P':
			change_passphrase = TRUE;
			break;
		      case 'l':
			outtype = FP;
			break;
		      case 'L':
			outtype = PUBLICO;
			break;
		      case 'p':
			outtype = PUBLIC;
			break;
		      case 'q':
			progressfn = no_progress;
			break;
		    }
		    break;
		  case 't':
		  case 'b':
		  case 'C':
		  case 'O':
		  case 'o':
		    /*
		     * Option requiring parameter.
		     */
		    p++;
		    if (!*p && argc > 1)
			--argc, p = *++argv;
		    else if (!*p) {
			fprintf(stderr, "puttygen: option `-%c' expects a"
				" parameter\n", c);
			errs = TRUE;
		    }
		    /*
		     * Now c is the option and p is the parameter.
		     */
		    switch (c) {
		      case 't':
			if (!strcmp(p, "rsa") || !strcmp(p, "rsa2"))
			    keytype = RSA2, sshver = 2;
			else if (!strcmp(p, "rsa1"))
			    keytype = RSA1, sshver = 1;
			else if (!strcmp(p, "dsa") || !strcmp(p, "dss"))
			    keytype = DSA, sshver = 2;
			else {
			    fprintf(stderr,
				    "puttygen: unknown key type `%s'\n", p);
			    errs = TRUE;
			}
                        break;
		      case 'b':
			bits = atoi(p);
                        break;
		      case 'C':
			comment = p;
                        break;
		      case 'O':
			if (!strcmp(p, "public"))
			    outtype = PUBLIC;
			else if (!strcmp(p, "public-openssh"))
			    outtype = PUBLICO;
			else if (!strcmp(p, "private"))
			    outtype = PRIVATE;
			else if (!strcmp(p, "fingerprint"))
			    outtype = FP;
			else if (!strcmp(p, "private-openssh"))
			    outtype = OPENSSH, sshver = 2;
			else if (!strcmp(p, "private-sshcom"))
			    outtype = SSHCOM, sshver = 2;
			else {
			    fprintf(stderr,
				    "puttygen: unknown output type `%s'\n", p);
			    errs = TRUE;
			}
                        break;
		      case 'o':
			outfile = p;
                        break;
		    }
		    p = NULL;	       /* prevent continued processing */
		    break;
		  default:
		    /*
		     * Unrecognised option.
		     */
		    errs = TRUE;
		    fprintf(stderr, "puttygen: no such option `-%c'\n", c);
		    break;
		}
	    }
	} else {
	    /*
	     * A non-option argument.
	     */
	    if (!infile)
		infile = p;
	    else {
		errs = TRUE;
		fprintf(stderr, "puttygen: cannot handle more than one"
			" input file\n");
	    }
	}
    }

    if (errs)
	return 1;

    if (nogo)
	return 0;

    /*
     * If run with at least one argument _but_ not the required
     * ones, print the usage message and return failure.
     */
    if (!infile && keytype == NOKEYGEN) {
	usage();
	return 1;
    }

    /* ------------------------------------------------------------------
     * Figure out further details of exactly what we're going to do.
     */

    /*
     * Bomb out if we've been asked to both load and generate a
     * key.
     */
    if (keytype != NOKEYGEN && intype) {
	fprintf(stderr, "puttygen: cannot both load and generate a key\n");
	return 1;
    }

    /*
     * Analyse the type of the input file, in case this affects our
     * course of action.
     */
    if (infile) {
	infilename = filename_from_str(infile);

	intype = key_type(&infilename);

	switch (intype) {
	    /*
	     * It would be nice here to be able to load _public_
	     * key files, in any of a number of forms, and (a)
	     * convert them to other public key types, (b) print
	     * out their fingerprints. Or, I suppose, for real
	     * orthogonality, (c) change their comment!
	     * 
	     * In fact this opens some interesting possibilities.
	     * Suppose ssh2_userkey_loadpub() were able to load
	     * public key files as well as extracting the public
	     * key from private ones. And suppose I did the thing
	     * I've been wanting to do, where specifying a
	     * particular private key file for authentication
	     * causes any _other_ key in the agent to be discarded.
	     * Then, if you had an agent forwarded to the machine
	     * you were running Unix PuTTY or Plink on, and you
	     * needed to specify which of the keys in the agent it
	     * should use, you could do that by supplying a

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -