1
2
3
4
5
6
7
8
9#if !ENABLE_USE_BB_CRYPT
10# if !defined(__FreeBSD__)
11# include <crypt.h>
12# endif
13#endif
14#include "libbb.h"
15
16
17
18
19
20static int i64c(int i)
21{
22 i &= 0x3f;
23 if (i == 0)
24 return '.';
25 if (i == 1)
26 return '/';
27 if (i < 12)
28 return ('0' - 2 + i);
29 if (i < 38)
30 return ('A' - 12 + i);
31 return ('a' - 38 + i);
32}
33
34int FAST_FUNC crypt_make_salt(char *p, int cnt )
35{
36
37 unsigned x = getpid() + monotonic_us();
38 do {
39
40
41
42 x = x*1664525 + 1013904223;
43
44
45
46
47
48 *p++ = i64c(x >> 16);
49 *p++ = i64c(x >> 22);
50 } while (--cnt);
51 *p = '\0';
52 return x;
53}
54
55char* FAST_FUNC crypt_make_pw_salt(char salt[MAX_PW_SALT_LEN], const char *algo)
56{
57 int len = 2/2;
58 char *salt_ptr = salt;
59
60
61
62
63 if ((algo[0]|0x20) != 'd') {
64 len = 8/2;
65 *salt_ptr++ = '$';
66 *salt_ptr++ = '1';
67 *salt_ptr++ = '$';
68#if !ENABLE_USE_BB_CRYPT || ENABLE_USE_BB_CRYPT_SHA
69 if ((algo[0]|0x20) == 's') {
70 salt[1] = '5' + (strcasecmp(algo, "sha512") == 0);
71 len = 16/2;
72 }
73#endif
74 }
75 crypt_make_salt(salt_ptr, len);
76 return salt_ptr;
77}
78
79#if ENABLE_USE_BB_CRYPT
80
81static char*
82to64(char *s, unsigned v, int n)
83{
84 while (--n >= 0) {
85
86 *s++ = i64c(v);
87 v >>= 6;
88 }
89 return s;
90}
91
92
93
94
95
96
97#include "pw_encrypt_des.c"
98#include "pw_encrypt_md5.c"
99#if ENABLE_USE_BB_CRYPT_SHA
100#include "pw_encrypt_sha.c"
101#endif
102
103
104
105
106static struct const_des_ctx *des_cctx;
107static struct des_ctx *des_ctx;
108
109
110static char *my_crypt(const char *key, const char *salt)
111{
112
113 if (salt[0] == '$' && salt[1] && salt[2] == '$') {
114 if (salt[1] == '1')
115 return md5_crypt(xzalloc(MD5_OUT_BUFSIZE), (unsigned char*)key, (unsigned char*)salt);
116#if ENABLE_USE_BB_CRYPT_SHA
117 if (salt[1] == '5' || salt[1] == '6')
118 return sha_crypt((char*)key, (char*)salt);
119#endif
120 }
121
122 if (!des_cctx)
123 des_cctx = const_des_init();
124 des_ctx = des_init(des_ctx, des_cctx);
125
126 return des_crypt(des_ctx, xzalloc(DES_OUT_BUFSIZE), (unsigned char*)key, (unsigned char*)salt);
127}
128
129
130static void my_crypt_cleanup(void)
131{
132 free(des_cctx);
133 free(des_ctx);
134 des_cctx = NULL;
135 des_ctx = NULL;
136}
137
138char* FAST_FUNC pw_encrypt(const char *clear, const char *salt, int cleanup)
139{
140 char *encrypted;
141
142 encrypted = my_crypt(clear, salt);
143 if (!encrypted)
144 bb_simple_error_msg_and_die("bad salt");
145
146 if (cleanup)
147 my_crypt_cleanup();
148
149 return encrypted;
150}
151
152#else
153
154char* FAST_FUNC pw_encrypt(const char *clear, const char *salt, int cleanup)
155{
156 char *encrypted;
157
158 encrypted = crypt(clear, salt);
159
160
161
162
163 if (!encrypted || !encrypted[0])
164 bb_simple_error_msg_and_die("bad salt");
165 return xstrdup(encrypted);
166}
167
168#endif
169