summarylogtreecommitdiffstats
path: root/havege.c
blob: b9bbb07082d5f20869c96ef211b4f74331dc1f55 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
/**
 *   Core HAVEGE Driver
 *   Copyright (C) 2018 Leonardo Gates
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License along
 *   with this program; if not, write to the Free Software Foundation, Inc.,
 *   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include <linux/version.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/slab.h>
#include <linux/cdev.h>
#include <linux/uaccess.h>
#include <linux/semaphore.h>
#include <linux/kthread.h>
#include <linux/random.h>
#include <asm/msr.h>

/***********************
 *  Driver Constants   *
 ***********************/

#define DRIVER_AUTH					"Leonardo Gates <leogx9r>"
#define DRIVER_DESC					"Extracts entropy from the system using the HAVEGE algorithm"
#define DRIVER_NAME					"havege"
#define DRIVER_VERS					"1.00"

#define DRIVER_MAJOR				1
#define DRIVER_MINOR				0

#define KERROR						KERN_ERR DRIVER_NAME ": "
#define KNOTICE						KERN_NOTICE DRIVER_NAME ": "

/************************
 *  Driver Char Device  *
 ************************/

/* Bytes to transfer at a time. */
#define CHUNK_TRANSFER_SZ			512
/* Number of words in the pool. */
#define HAVEGE_POOL_WORDS			0x40000
/* Number of bytes in the pool. */
#define HAVEGE_POOL_SIZE			( ( HAVEGE_POOL_WORDS + 16384 ) * sizeof( u32 ) )
/* Size of the walking table in bytes. */
#define WALK_TABLE_SIZE				( 8192 * sizeof( u32 ) )

static ssize_t	havege_read( struct file* pfile, char __user* buf, size_t length, loff_t* fpos );
static int		havege_open( struct inode* inode, struct file* pfile );

static struct class*				havege_class;
static dev_t						havege_dev;

static u32							transfer_buffer[ CHUNK_TRANSFER_SZ ] __latent_entropy;

static int							havege_init_steps		= 64;
static int							havege_reseed_steps		= 64;

static struct file_operations		havege_fops				= {
	.owner													= THIS_MODULE,
	.open													= havege_open,
	.read													= havege_read,
};

/*************************
 * HAVEGE Algorithm Base *
 *************************/

struct havege_state {
	/* Pointer to the current word being read from the pool. */
	u32						pidx;
	/* Array of words containing result information. */
	u32*					pool;
	/* Size in words of the result pool. */
	ssize_t					pool_size;

	/* Table walking. */
	u32*					walk_tbl;
	u32*					walk_ptr;

	/* Permuting values. */
	u32						P1[2];
	u32						P2[2];

	/* Timing information. */
	u32						clock;
	u32						freq;

	/* Device information. */
	struct semaphore		lock;
	struct cdev				dev;

} __randomize_layout;

static struct havege_state*	cstate;

/**
  * Collects timing information from the system and adds it to the state.
  */
static void havege_collect( struct havege_state* state ) {
	u32 i, j, k, flags, *pt[4], *tmp;

	i		= 0;
	k		= 0;

	/* Update each word in the state. */
	while( i < state->pool_size ) {
		/* Do we force preemption now ? */
		if( ( i - k ) >= state->freq ) {
			k = i;
			schedule();
		}

		/* Schedule when necessary. */
		if( need_resched() )
			schedule();

		/* Perform the main loop. */
		#include "body.h"
	}
}

/**
  * Cleans up any state allocated information.
  */
static void havege_cleanup( struct havege_state* state ) {
	if( !state )
		return;

	/* Zero the walking table and free it if allocated. */
	if( state->walk_tbl ) {
		memzero_explicit( state->walk_tbl, WALK_TABLE_SIZE );
		vfree( state->walk_tbl );
	}

	/* Zero out the pool and free it if allocated. */
	if( state->pool ) {
		memzero_explicit( state->pool, HAVEGE_POOL_SIZE );
		vfree( state->pool );
	}

	/* Finally free the kernel memory. */
	memzero_explicit( state, sizeof( struct havege_state ) );
	kfree( state );
}

/**
  * Sets up a state structure for collection.
  */
static struct havege_state* havege_setup( u32 pool_size ) {
	struct havege_state* state;

	/* Allocate the actual state in the kernel. */
	state = kmalloc( sizeof( struct havege_state ), GFP_KERNEL );
	if ( !state ) {
		printk( KERROR "failed to allocate initial state\n" );
		return NULL;
	}

	/* Zero out everything. */
	memset( state, 0, sizeof( struct havege_state ) );

	/* By default, we point the pool here to schedule an initial run. */
	state->pidx = HAVEGE_POOL_WORDS * 2;

	/* And store the pool size. */
	state->pool_size = pool_size;

	/* Allocate the entire pool + 64k in virtual memory since we may not have enough kmem. */
	state->pool = vmalloc( HAVEGE_POOL_SIZE );
	if( !state->pool ) {
		printk( KERROR "failed to allocate pool table for state\n" );
		goto __bail_out;
	}

	/* Also allocate the walk table ( 32k ) virtually. */
	state->walk_tbl = vmalloc( WALK_TABLE_SIZE );
	state->walk_ptr = state->walk_tbl;
	if( !state->walk_tbl ) {
		printk( KERROR "failed to allocate walk table for state\n" );
		goto __bail_out;
	}

	/* And initialize the semaphore. We allow one read at a time. */
	sema_init( &state->lock, 1 );
	if( &state->lock == NULL ) {
		printk( KERROR "failed to initialize semaphore lock for state\n" );
		goto __bail_out;
	}

	/* Preemption refills the pool roughly 1/16th tick. */
	state->freq = pool_size >> 4;

	return state;


__bail_out:

	/* Cleanup allocated memory if any. */
	havege_cleanup( state );

	printk( KERROR "unable to allocate resources required\n" );
	return NULL;
}

/**
  * Extracts a word from the state.
  * Updates the state internally prior to extraction if required.
  */
static inline u32 havege_extract( void ) {
	u32 i, steps;

	/* Do we need to regather entropy ? */
	if( cstate->pidx >= cstate->pool_size ) {
		/* Perform initial gathering if required. */
		if( cstate->pidx >= cstate->pool_size * 2 ) {
			cstate->walk_ptr = ( u32* )( ( ( unsigned long long )&cstate->walk_tbl[ 4096 ] ) & 0xfffffffffffff000 );

			steps = ( havege_init_steps * HAVEGE_POOL_WORDS ) / cstate->pool_size;

			for( i = 0; i < steps; i++ )
				havege_collect( cstate );
		}
		/* Normal sequential stepping. */
		else for( i = 0; i < havege_reseed_steps; i++ )
			havege_collect( cstate );

		cstate->pidx = 0;
	}

	/* Return the next word. */
	return cstate->pool[ cstate->pidx++ ];
}

/*************************
 *    Device Methods     *
 *************************/

/**
  * Poll the state for entropy and transfer it to the user.
  */
static ssize_t havege_read( struct file* pfile, char __user* buf, size_t length, loff_t* fpos ) {
	ssize_t sz;
	u32 i, j;

	sz = length;

	/* Try acquiring the lock. */
	if( down_interruptible( &cstate->lock ) )
		return -ERESTARTSYS;

	/* We're copying to the user in chunks. */
	while( length > 0 ) {
		i = min_t( u32, CHUNK_TRANSFER_SZ, length / sizeof( u32 ) );

		/* Fill up the buffer. */
		for( j = 0; j < i; j++ )
			transfer_buffer[ j ] = havege_extract();

		/* Try transferring to the user. Bail out if we can only do a partial transfer. */
		if( copy_to_user( buf, transfer_buffer, i * sizeof( u32 ) ) ) {
			sz = -EFAULT;
			goto __bail_out;
		}

		length -= i * sizeof( u32 );
		buf += i * sizeof( u32 );
	}

	fpos += sz;

__bail_out:

	/* Clear out sensitive memory and release the lock. */
	memzero_explicit( transfer_buffer, sizeof( transfer_buffer ) );
	up( &cstate->lock );

	return sz;
}

/**
  * When opening the device, ensure we're only doing read operations.
  */
static int havege_open( struct inode* inode, struct file* pfile ) {
	/* Only allow reading from the device. */
	if( !( pfile->f_mode & FMODE_READ ) || pfile->f_mode & FMODE_WRITE )
		return -EINVAL;

	pfile->f_op = &havege_fops;
	return 0;
}

/**************************
 *     Module Methods     *
 **************************/

/**
  * Allocates and initializes the internal state and character device.
  */
static int module_do_init( void ) {
	int res;

	/* Allocate the character device for usage. */
	res = alloc_chrdev_region( &havege_dev, DRIVER_MINOR, DRIVER_MAJOR, DRIVER_NAME );
	if( res < 0 ) {
		printk( KERROR "failed to register character device\n" );
		return res;
	}

	/* Register the device class. */
	havege_class = class_create( THIS_MODULE, DRIVER_NAME );
	if( IS_ERR( havege_class ) ) {
		printk( KERROR "failed to create device class\n" );
		return PTR_ERR( havege_class );
	}

	/* Set up the internal state. */
	cstate = havege_setup( HAVEGE_POOL_WORDS );
	if( !cstate )
		return -ENOMEM;

	/* Initialize the character device. */
	cdev_init( &cstate->dev, &havege_fops );
	cstate->dev.owner = THIS_MODULE;
	cstate->dev.ops   = &havege_fops;

	/* Add the device internally. */
	res = cdev_add( &cstate->dev, havege_dev, 1 );
	if( res ) {
		printk( KERROR "failed to add character device\n" );
		return -EFAULT;
	}

	/* Link and mark it ready for usage. */
	device_create( havege_class, NULL, havege_dev, NULL, DRIVER_NAME );
	kobject_set_name( &cstate->dev.kobj, DRIVER_NAME );

	printk( KNOTICE "created character device\n" );
	return 0;
}

/**
  * Cleans up any allocated memory and removes the character device.
  */
static void module_do_exit( void ) {
	/* free character device */
	cdev_del( &cstate->dev );
	unregister_chrdev_region( havege_dev, DRIVER_MAJOR );

	/* remove & destroy class object */
	device_destroy( havege_class, havege_dev );
	class_destroy( havege_class );

	/* destroy state */
	havege_cleanup( cstate );

	printk( KNOTICE "removed from kernel.\n" );
}

/**************************
 *     Driver Exports     *
 **************************/

module_init( module_do_init );
module_exit( module_do_exit );

module_param_named( init_steps, havege_init_steps, int, 0 );
MODULE_PARM_DESC( init_steps, "inital steps to run when reseeding. default: 64" );

module_param_named( reseed_steps, havege_reseed_steps, int, 0 );
MODULE_PARM_DESC( reseed_steps, "number of steps to use during reseeding. default: 64" );

MODULE_LICENSE( "GPL" );
MODULE_AUTHOR( DRIVER_AUTH );
MODULE_DESCRIPTION( DRIVER_DESC );
MODULE_VERSION( DRIVER_VERS );