1 /*	$NetBSD: tls_seed.c,v 1.1.1.1 2009/06/23 10:08:57 tron Exp $	*/
2 
3 /*++
4 /* NAME
5 /*	tls_seed 3
6 /* SUMMARY
7 /*	TLS PRNG seeding routines
8 /* SYNOPSIS
9 /*	#define TLS_INTERNAL
10 /*	#include <tls.h>
11 /*
12 /*	int	tls_ext_seed(nbytes)
13 /*	int	nbytes;
14 /*
15 /*	void	tls_int_seed()
16 /* DESCRIPTION
17 /*	tls_ext_seed() requests the specified number of bytes
18 /*	from the tlsmgr(8) PRNG pool and updates the local PRNG.
19 /*	The result is zero in case of success, -1 otherwise.
20 /*
21 /*	tls_int_seed() mixes the process ID and time of day into
22 /*	the PRNG pool. This adds a few bits of entropy with each
23 /*	call, provided that the calls aren't made frequently.
24 /* LICENSE
25 /* .ad
26 /* .fi
27 /*	The Secure Mailer license must be distributed with this
28 /*	software.
29 /* AUTHOR(S)
30 /*	Wietse Venema
31 /*	IBM T.J. Watson Research
32 /*	P.O. Box 704
33 /*	Yorktown Heights, NY 10598, USA
34 /*--*/
35 
36 /* System library. */
37 
38 #include <sys_defs.h>
39 #include <sys/time.h>			/* gettimeofday() */
40 #include <unistd.h>			/* getpid() */
41 
42 #ifdef USE_TLS
43 
44 /* OpenSSL library. */
45 
46 #include <openssl/rand.h>		/* RAND_seed() */
47 
48 /* Utility library. */
49 
50 #include <msg.h>
51 #include <vstring.h>
52 
53 /* TLS library. */
54 
55 #include <tls_mgr.h>
56 #define TLS_INTERNAL
57 #include <tls.h>
58 
59 /* Application-specific. */
60 
61 /* tls_int_seed - add entropy to the pool by adding the time and PID */
62 
tls_int_seed(void)63 void    tls_int_seed(void)
64 {
65     static struct {
66 	pid_t   pid;
67 	struct timeval tv;
68     }       randseed;
69 
70     if (randseed.pid == 0)
71 	randseed.pid = getpid();
72     GETTIMEOFDAY(&randseed.tv);
73     RAND_seed(&randseed, sizeof(randseed));
74 }
75 
76 /* tls_ext_seed - request entropy from tlsmgr(8) server */
77 
tls_ext_seed(int nbytes)78 int     tls_ext_seed(int nbytes)
79 {
80     VSTRING *buf;
81     int     status;
82 
83     buf = vstring_alloc(nbytes);
84     status = tls_mgr_seed(buf, nbytes);
85     RAND_seed(vstring_str(buf), VSTRING_LEN(buf));
86     vstring_free(buf);
87     return (status == TLS_MGR_STAT_OK ? 0 : -1);
88 }
89 
90 #endif
91