📄 ssh-rand-helper.c
字号:
long int i; total_entropy_estimate = 0; i = getpid(); RAND_add(&i, sizeof(i), 0.5); total_entropy_estimate += 0.1; i = getppid(); RAND_add(&i, sizeof(i), 0.5); total_entropy_estimate += 0.1; i = getuid(); RAND_add(&i, sizeof(i), 0.0); i = getgid(); RAND_add(&i, sizeof(i), 0.0); total_entropy_estimate += stir_gettimeofday(1.0); total_entropy_estimate += stir_clock(0.5); total_entropy_estimate += stir_rusage(RUSAGE_SELF, 2.0); return total_entropy_estimate;}doublestir_from_programs(void){ int c; double entropy, total_entropy; char hash[SHA_DIGEST_LENGTH]; total_entropy = 0; for(c = 0; entropy_cmds[c].path != NULL; c++) { if (!entropy_cmds[c].badness) { /* Hash output from command */ entropy = hash_command_output(&entropy_cmds[c], hash); /* Scale back estimate by command's rate */ entropy *= entropy_cmds[c].rate; /* Upper bound of entropy is SHA_DIGEST_LENGTH */ if (entropy > SHA_DIGEST_LENGTH) entropy = SHA_DIGEST_LENGTH; /* Stir it in */ RAND_add(hash, sizeof(hash), entropy); debug3("Got %0.2f bytes of entropy from '%s'", entropy, entropy_cmds[c].cmdstring); total_entropy += entropy; /* Execution time should be a bit unpredictable */ total_entropy += stir_gettimeofday(0.05); total_entropy += stir_clock(0.05); total_entropy += stir_rusage(RUSAGE_SELF, 0.1); total_entropy += stir_rusage(RUSAGE_CHILDREN, 0.1); } else { debug2("Command '%s' disabled (badness %d)", entropy_cmds[c].cmdstring, entropy_cmds[c].badness); if (entropy_cmds[c].badness > 0) entropy_cmds[c].badness--; } } return total_entropy;}/* * prng seedfile functions */intprng_check_seedfile(char *filename){ struct stat st; /* * XXX raceable: eg replace seed between this stat and subsequent * open. Not such a problem because we don't really trust the * seed file anyway. * XXX: use secure path checking as elsewhere in OpenSSH */ if (lstat(filename, &st) == -1) { /* Give up on hard errors */ if (errno != ENOENT) debug("WARNING: Couldn't stat random seed file " "\"%.100s\": %s", filename, strerror(errno)); return 0; } /* regular file? */ if (!S_ISREG(st.st_mode)) fatal("PRNG seedfile %.100s is not a regular file", filename); /* mode 0600, owned by root or the current user? */ if (((st.st_mode & 0177) != 0) || !(st.st_uid == getuid())) { debug("WARNING: PRNG seedfile %.100s must be mode 0600, " "owned by uid %d", filename, getuid()); return 0; } return 1;}voidprng_write_seedfile(void){ int fd; char seed[SEED_FILE_SIZE], filename[MAXPATHLEN]; struct passwd *pw; pw = getpwuid(getuid()); if (pw == NULL) fatal("Couldn't get password entry for current user " "(%i): %s", getuid(), strerror(errno)); /* Try to ensure that the parent directory is there */ snprintf(filename, sizeof(filename), "%.512s/%s", pw->pw_dir, _PATH_SSH_USER_DIR); mkdir(filename, 0700); snprintf(filename, sizeof(filename), "%.512s/%s", pw->pw_dir, SSH_PRNG_SEED_FILE); debug("writing PRNG seed to file %.100s", filename); RAND_bytes(seed, sizeof(seed)); /* Don't care if the seed doesn't exist */ prng_check_seedfile(filename); if ((fd = open(filename, O_WRONLY|O_TRUNC|O_CREAT, 0600)) == -1) { debug("WARNING: couldn't access PRNG seedfile %.100s " "(%.100s)", filename, strerror(errno)); } else { if (atomicio(write, fd, &seed, sizeof(seed)) < sizeof(seed)) fatal("problem writing PRNG seedfile %.100s " "(%.100s)", filename, strerror(errno)); close(fd); }}voidprng_read_seedfile(void){ int fd; char seed[SEED_FILE_SIZE], filename[MAXPATHLEN]; struct passwd *pw; pw = getpwuid(getuid()); if (pw == NULL) fatal("Couldn't get password entry for current user " "(%i): %s", getuid(), strerror(errno)); snprintf(filename, sizeof(filename), "%.512s/%s", pw->pw_dir, SSH_PRNG_SEED_FILE); debug("loading PRNG seed from file %.100s", filename); if (!prng_check_seedfile(filename)) { verbose("Random seed file not found or invalid, ignoring."); return; } /* open the file and read in the seed */ fd = open(filename, O_RDONLY); if (fd == -1) fatal("could not open PRNG seedfile %.100s (%.100s)", filename, strerror(errno)); if (atomicio(read, fd, &seed, sizeof(seed)) < sizeof(seed)) { verbose("invalid or short read from PRNG seedfile " "%.100s - ignoring", filename); memset(seed, '\0', sizeof(seed)); } close(fd); /* stir in the seed, with estimated entropy zero */ RAND_add(&seed, sizeof(seed), 0.0);}/* * entropy command initialisation functions */intprng_read_commands(char *cmdfilename){ char cmd[SEED_FILE_SIZE], *cp, line[1024], path[SEED_FILE_SIZE]; double est; entropy_cmd_t *entcmd; FILE *f; int cur_cmd, linenum, num_cmds, arg; if ((f = fopen(cmdfilename, "r")) == NULL) { fatal("couldn't read entropy commands file %.100s: %.100s", cmdfilename, strerror(errno)); } num_cmds = 64; entcmd = xmalloc(num_cmds * sizeof(entropy_cmd_t)); memset(entcmd, '\0', num_cmds * sizeof(entropy_cmd_t)); /* Read in file */ cur_cmd = linenum = 0; while (fgets(line, sizeof(line), f)) { linenum++; /* Skip leading whitespace, blank lines and comments */ cp = line + strspn(line, WHITESPACE); if ((*cp == 0) || (*cp == '#')) continue; /* done with this line */ /* * The first non-whitespace char should be a double quote * delimiting the commandline */ if (*cp != '"') { error("bad entropy command, %.100s line %d", cmdfilename, linenum); continue; } /* * First token, command args (incl. argv[0]) in double * quotes */ cp = strtok(cp, "\""); if (cp == NULL) { error("missing or bad command string, %.100s " "line %d -- ignored", cmdfilename, linenum); continue; } strlcpy(cmd, cp, sizeof(cmd)); /* Second token, full command path */ if ((cp = strtok(NULL, WHITESPACE)) == NULL) { error("missing command path, %.100s " "line %d -- ignored", cmdfilename, linenum); continue; } /* Did configure mark this as dead? */ if (strncmp("undef", cp, 5) == 0) continue; strlcpy(path, cp, sizeof(path)); /* Third token, entropy rate estimate for this command */ if ((cp = strtok(NULL, WHITESPACE)) == NULL) { error("missing entropy estimate, %.100s " "line %d -- ignored", cmdfilename, linenum); continue; } est = strtod(cp, NULL); /* end of line */ if ((cp = strtok(NULL, WHITESPACE)) != NULL) { error("garbage at end of line %d in %.100s " "-- ignored", linenum, cmdfilename); continue; } /* save the command for debug messages */ entcmd[cur_cmd].cmdstring = xstrdup(cmd); /* split the command args */ cp = strtok(cmd, WHITESPACE); arg = 0; do { entcmd[cur_cmd].args[arg] = xstrdup(cp); arg++; } while(arg < NUM_ARGS && (cp = strtok(NULL, WHITESPACE))); if (strtok(NULL, WHITESPACE)) error("ignored extra commands (max %d), %.100s " "line %d", NUM_ARGS, cmdfilename, linenum); /* Copy the command path and rate estimate */ entcmd[cur_cmd].path = xstrdup(path); entcmd[cur_cmd].rate = est; /* Initialise other values */ entcmd[cur_cmd].sticky_badness = 1; cur_cmd++; /* * If we've filled the array, reallocate it twice the size * Do this now because even if this we're on the last * command we need another slot to mark the last entry */ if (cur_cmd == num_cmds) { num_cmds *= 2; entcmd = xrealloc(entcmd, num_cmds * sizeof(entropy_cmd_t)); } } /* zero the last entry */ memset(&entcmd[cur_cmd], '\0', sizeof(entropy_cmd_t)); /* trim to size */ entropy_cmds = xrealloc(entcmd, (cur_cmd + 1) * sizeof(entropy_cmd_t)); debug("Loaded %d entropy commands from %.100s", cur_cmd, cmdfilename); return cur_cmd < MIN_ENTROPY_SOURCES ? -1 : 0;}voidusage(void){ fprintf(stderr, "Usage: %s [options]\n", __progname); fprintf(stderr, " -v Verbose; display verbose debugging messages.\n"); fprintf(stderr, " Multiple -v increases verbosity.\n"); fprintf(stderr, " -x Force output in hexidecimal (for debugging)\n"); fprintf(stderr, " -X Force output in binary\n"); fprintf(stderr, " -b bytes Number of bytes to output (default %d)\n", OUTPUT_SEED_SIZE);}int main(int argc, char **argv){ unsigned char *buf; int ret, ch, debug_level, output_hex, bytes; extern char *optarg; LogLevel ll; __progname = get_progname(argv[0]); log_init(argv[0], SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_USER, 1); ll = SYSLOG_LEVEL_INFO; debug_level = output_hex = 0; bytes = OUTPUT_SEED_SIZE; /* Don't write binary data to a tty, unless we are forced to */ if (isatty(STDOUT_FILENO)) output_hex = 1; while ((ch = getopt(argc, argv, "vxXhb:")) != -1) { switch (ch) { case 'v': if (debug_level < 3) ll = SYSLOG_LEVEL_DEBUG1 + debug_level++; break; case 'x': output_hex = 1; break; case 'X': output_hex = 0; break; case 'b': if ((bytes = atoi(optarg)) <= 0) fatal("Invalid number of output bytes"); break; case 'h': usage(); exit(0); default: error("Invalid commandline option"); usage(); } } log_init(argv[0], ll, SYSLOG_FACILITY_USER, 1); #ifdef USE_SEED_FILES prng_read_seedfile();#endif buf = xmalloc(bytes); /* * Seed the RNG from wherever we can */ /* Take whatever is on the stack, but don't credit it */ RAND_add(buf, bytes, 0); debug("Seeded RNG with %i bytes from system calls", (int)stir_from_system());#ifdef PRNGD_PORT if (get_random_bytes_prngd(buf, bytes, PRNGD_PORT, NULL) == -1) fatal("Entropy collection failed"); RAND_add(buf, bytes, bytes);#elif defined(PRNGD_SOCKET) if (get_random_bytes_prngd(buf, bytes, 0, PRNGD_SOCKET) == -1) fatal("Entropy collection failed"); RAND_add(buf, bytes, bytes);#else /* Read in collection commands */ if (prng_read_commands(SSH_PRNG_COMMAND_FILE) == -1) fatal("PRNG initialisation failed -- exiting."); debug("Seeded RNG with %i bytes from programs", (int)stir_from_programs());#endif#ifdef USE_SEED_FILES prng_write_seedfile();#endif /* * Write the seed to stdout */ if (!RAND_status()) fatal("Not enough entropy in RNG"); RAND_bytes(buf, bytes); if (output_hex) { for(ret = 0; ret < bytes; ret++) printf("%02x", (unsigned char)(buf[ret])); printf("\n"); } else ret = atomicio(write, STDOUT_FILENO, buf, bytes); memset(buf, '\0', bytes); xfree(buf); return ret == bytes ? 0 : 1;}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -