-
Notifications
You must be signed in to change notification settings - Fork 2
/
password_buffer.h
108 lines (97 loc) · 2.22 KB
/
password_buffer.h
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
#ifndef PWD_BUF_H
#define PWD_BUF_H
#include <errno.h>
#include <limits.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <unistd.h>
static bool mlock_supported = true;
static long int page_size = 0;
static long int get_page_size()
{
if (!page_size)
{
page_size = sysconf(_SC_PAGESIZE);
}
return page_size;
}
// Password buffer lock expects addr to be page aligned
static bool password_buffer_lock(char* addr, size_t size)
{
int retries = 5;
while (mlock(addr, size) != 0 && retries > 0)
{
switch (errno)
{
case EAGAIN:
retries--;
if (retries == 0)
{
log_message(LOG_LEVEL_ERROR, "mlock() supported but failed too often.");
return false;
}
break;
case EPERM:
log_message(LOG_LEVEL_ERROR, "Unable to mlock() password memory: Unsupported!");
mlock_supported = false;
return true;
default:
log_message(LOG_LEVEL_ERROR, "Unable to mlock() password memory.");
return false;
}
}
return true;
}
// Password buffer unlock expects addr to be page aligned
static bool password_buffer_unlock(char* addr, size_t size)
{
if (mlock_supported)
{
if (munlock(addr, size) != 0)
{
log_message(LOG_LEVEL_ERROR, "Unable to munlock() password memory.");
return false;
}
}
return true;
}
// Create a secure password buffer
char* password_buffer_create(size_t size)
{
void* buffer;
int result = posix_memalign(&buffer, get_page_size(), size);
if (result)
{
errno = result; // posix_memalign doesn't set errno according to the man page
log_message(LOG_LEVEL_ERROR, "Failed to allocate password buffer");
return NULL;
}
if (!password_buffer_lock(buffer, size))
{
free(buffer);
return NULL;
}
return (char*)buffer;
}
// Clear the buffer securely
void clear_buffer(char* buffer, size_t size)
{
if (buffer)
{
memset(buffer, 0, size); // Clear the buffer
}
}
// Destroy the password buffer securely
void password_buffer_destroy(char* buffer, size_t size)
{
if (buffer)
{
clear_buffer(buffer, size);
password_buffer_unlock(buffer, size);
free(buffer);
}
}
#endif