Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sudo-project
GitHub Repository: sudo-project/sudo
Path: blob/main/plugins/sudoers/filedigest.c
1532 views
1
/*
2
* SPDX-License-Identifier: ISC
3
*
4
* Copyright (c) 2013-2018 Todd C. Miller <[email protected]>
5
*
6
* Permission to use, copy, modify, and distribute this software for any
7
* purpose with or without fee is hereby granted, provided that the above
8
* copyright notice and this permission notice appear in all copies.
9
*
10
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17
*/
18
19
#include <config.h>
20
21
#include <stdio.h>
22
#include <stdlib.h>
23
#include <string.h>
24
#include <unistd.h>
25
#include <fcntl.h>
26
#include <errno.h>
27
28
#include <sudoers.h>
29
#include <sudo_digest.h>
30
31
unsigned char *
32
sudo_filedigest(int fd, const char *file, unsigned int digest_type,
33
size_t *digest_len)
34
{
35
unsigned char *file_digest = NULL;
36
unsigned char buf[32 * 1024];
37
struct sudo_digest *dig = NULL;
38
FILE *fp = NULL;
39
size_t nread;
40
int fd2;
41
debug_decl(sudo_filedigest, SUDOERS_DEBUG_UTIL);
42
43
*digest_len = sudo_digest_getlen(digest_type);
44
if (*digest_len == 0) {
45
sudo_warnx(U_("unsupported digest type %u for %s"), digest_type, file);
46
debug_return_ptr(NULL);
47
}
48
49
if ((fd2 = dup(fd)) == -1) {
50
sudo_debug_printf(SUDO_DEBUG_INFO, "unable to dup %s: %s",
51
file, strerror(errno));
52
debug_return_ptr(NULL);
53
}
54
if ((fp = fdopen(fd2, "r")) == NULL) {
55
sudo_debug_printf(SUDO_DEBUG_INFO, "unable to fdopen %s: %s",
56
file, strerror(errno));
57
close(fd2);
58
goto bad;
59
}
60
if ((file_digest = malloc(*digest_len)) == NULL) {
61
sudo_warnx(U_("%s: %s"), __func__, U_("unable to allocate memory"));
62
goto bad;
63
}
64
if ((dig = sudo_digest_alloc(digest_type)) == NULL) {
65
sudo_warnx(U_("%s: %s"), __func__, U_("unable to allocate memory"));
66
goto bad;
67
}
68
while ((nread = fread(buf, 1, sizeof(buf), fp)) != 0) {
69
sudo_digest_update(dig, buf, nread);
70
}
71
if (ferror(fp)) {
72
sudo_warnx(U_("%s: read error"), file);
73
goto bad;
74
}
75
sudo_digest_final(dig, file_digest);
76
sudo_digest_free(dig);
77
fclose(fp);
78
79
debug_return_ptr(file_digest);
80
bad:
81
sudo_digest_free(dig);
82
free(file_digest);
83
if (fp != NULL)
84
fclose(fp);
85
debug_return_ptr(NULL);
86
}
87
88