c5e438ec |
1 | /* |
2 | * Noise generation for PuTTY's cryptographic random number |
3 | * generator. |
4 | */ |
5 | |
6 | #include <stdio.h> |
7 | #include <fcntl.h> |
8 | #include <unistd.h> |
9 | #include <sys/time.h> |
10 | |
11 | #include "putty.h" |
12 | #include "ssh.h" |
13 | #include "storage.h" |
14 | |
15 | /* |
16 | * FIXME. This module currently depends critically on /dev/urandom, |
17 | * because it has no fallback mechanism for doing anything else. |
18 | */ |
19 | |
20 | static void read_dev_urandom(char *buf, int len) |
21 | { |
22 | int fd; |
23 | int ngot, ret; |
24 | |
25 | fd = open("/dev/urandom", O_RDONLY); |
26 | if (fd < 0) { |
27 | perror("/dev/urandom: open"); |
28 | exit(1); |
29 | } |
30 | |
31 | ngot = 0; |
32 | while (ngot < len) { |
33 | ret = read(fd, buf+ngot, len-ngot); |
34 | if (ret < 0) { |
35 | perror("/dev/urandom: read"); |
36 | exit(1); |
37 | } |
38 | ngot += ret; |
39 | } |
40 | } |
41 | |
42 | /* |
43 | * This function is called once, at PuTTY startup. Currently it |
44 | * will read 32 bytes out of /dev/urandom and seed the internal |
45 | * generator with them. |
46 | */ |
47 | |
48 | void noise_get_heavy(void (*func) (void *, int)) |
49 | { |
50 | char buf[32]; |
51 | read_dev_urandom(buf, sizeof(buf)); |
52 | func(buf, sizeof(buf)); |
53 | } |
54 | |
55 | void random_save_seed(void) |
56 | { |
57 | /* Currently we do nothing here. FIXME? */ |
58 | } |
59 | |
60 | /* |
61 | * This function is called every time the urandom pool needs |
62 | * stirring, and will acquire the system time. |
63 | */ |
64 | void noise_get_light(void (*func) (void *, int)) |
65 | { |
66 | struct timeval tv; |
67 | gettimeofday(&tv, NULL); |
68 | func(&tv, sizeof(tv)); |
69 | } |
70 | |
71 | /* |
72 | * This function is called on a timer, and it will just pull some |
73 | * stuff out of /dev/urandom. FIXME: really I suspect we ought not |
74 | * to deplete /dev/urandom like this. Better to grab something more |
75 | * harmless. |
76 | */ |
77 | void noise_regular(void) |
78 | { |
79 | char buf[4]; |
80 | read_dev_urandom(buf, sizeof(buf)); |
81 | random_add_noise(buf, sizeof(buf)); |
82 | } |
83 | |
84 | /* |
85 | * This function is called on every keypress or mouse move, and |
86 | * will add the current time to the noise pool. It gets the scan |
87 | * code or mouse position passed in, and adds that too. |
88 | */ |
89 | void noise_ultralight(unsigned long data) |
90 | { |
91 | struct timeval tv; |
92 | gettimeofday(&tv, NULL); |
93 | random_add_noise(&tv, sizeof(tv)); |
94 | random_add_noise(&data, sizeof(data)); |
95 | } |