1 /*
2  * Copyright 1999-2022 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9 
10 /*-
11  * This is a generic 32 bit "collector" for message digest algorithms.
12  * Whenever needed it collects input character stream into chunks of
13  * 32 bit values and invokes a block function that performs actual hash
14  * calculations.
15  *
16  * Porting guide.
17  *
18  * Obligatory macros:
19  *
20  * DATA_ORDER_IS_BIG_ENDIAN or DATA_ORDER_IS_LITTLE_ENDIAN
21  *      this macro defines byte order of input stream.
22  * HASH_CBLOCK
23  *      size of a unit chunk HASH_BLOCK operates on.
24  * HASH_LONG
25  *      has to be at least 32 bit wide.
26  * HASH_CTX
27  *      context structure that at least contains following
28  *      members:
29  *              typedef struct {
30  *                      ...
31  *                      HASH_LONG       Nl,Nh;
32  *                      either {
33  *                      HASH_LONG       data[HASH_LBLOCK];
34  *                      unsigned char   data[HASH_CBLOCK];
35  *                      };
36  *                      unsigned int    num;
37  *                      ...
38  *                      } HASH_CTX;
39  *      data[] vector is expected to be zeroed upon first call to
40  *      HASH_UPDATE.
41  * HASH_UPDATE
42  *      name of "Update" function, implemented here.
43  * HASH_TRANSFORM
44  *      name of "Transform" function, implemented here.
45  * HASH_FINAL
46  *      name of "Final" function, implemented here.
47  * HASH_BLOCK_DATA_ORDER
48  *      name of "block" function capable of treating *unaligned* input
49  *      message in original (data) byte order, implemented externally.
50  * HASH_MAKE_STRING
51  *      macro converting context variables to an ASCII hash string.
52  *
53  * MD5 example:
54  *
55  *      #define DATA_ORDER_IS_LITTLE_ENDIAN
56  *
57  *      #define HASH_LONG               MD5_LONG
58  *      #define HASH_CTX                MD5_CTX
59  *      #define HASH_CBLOCK             MD5_CBLOCK
60  *      #define HASH_UPDATE             MD5_Update
61  *      #define HASH_TRANSFORM          MD5_Transform
62  *      #define HASH_FINAL              MD5_Final
63  *      #define HASH_BLOCK_DATA_ORDER   md5_block_data_order
64  */
65 
66 #ifndef OSSL_CRYPTO_MD32_COMMON_H
67 # define OSSL_CRYPTO_MD32_COMMON_H
68 # pragma once
69 
70 # include <openssl/crypto.h>
71 /*
72  * For ossl_(un)likely
73  */
74 # include <internal/common.h>
75 
76 # if !defined(DATA_ORDER_IS_BIG_ENDIAN) && !defined(DATA_ORDER_IS_LITTLE_ENDIAN)
77 #  error "DATA_ORDER must be defined!"
78 # endif
79 
80 # ifndef HASH_CBLOCK
81 #  error "HASH_CBLOCK must be defined!"
82 # endif
83 # ifndef HASH_LONG
84 #  error "HASH_LONG must be defined!"
85 # endif
86 # ifndef HASH_CTX
87 #  error "HASH_CTX must be defined!"
88 # endif
89 
90 # ifndef HASH_UPDATE
91 #  error "HASH_UPDATE must be defined!"
92 # endif
93 # ifndef HASH_TRANSFORM
94 #  error "HASH_TRANSFORM must be defined!"
95 # endif
96 # ifndef HASH_FINAL
97 #  error "HASH_FINAL must be defined!"
98 # endif
99 
100 # ifndef HASH_BLOCK_DATA_ORDER
101 #  error "HASH_BLOCK_DATA_ORDER must be defined!"
102 # endif
103 
104 # define ROTATE(a,n)     (((a)<<(n))|(((a)&0xffffffff)>>(32-(n))))
105 
106 #ifndef PEDANTIC
107 # if defined(__GNUC__) && __GNUC__>=2 && \
108      !defined(OPENSSL_NO_ASM) && !defined(OPENSSL_NO_INLINE_ASM)
109 #  if defined(__riscv_zbb) || defined(__riscv_zbkb)
110 #   if __riscv_xlen == 64
111 #   undef ROTATE
112 #   define ROTATE(x, n) ({ MD32_REG_T ret;            \
113                        asm ("roriw %0, %1, %2"        \
114                        : "=r"(ret)                    \
115                        : "r"(x), "i"(32 - (n))); ret;})
116 #   endif
117 #   if __riscv_xlen == 32
118 #   undef ROTATE
119 #   define ROTATE(x, n) ({ MD32_REG_T ret;            \
120                        asm ("rori %0, %1, %2"         \
121                        : "=r"(ret)                    \
122                        : "r"(x), "i"(32 - (n))); ret;})
123 #   endif
124 #  endif
125 # endif
126 #endif
127 
128 # if defined(DATA_ORDER_IS_BIG_ENDIAN)
129 
130 #  define HOST_c2l(c,l)  (l =(((unsigned long)(*((c)++)))<<24),          \
131                          l|=(((unsigned long)(*((c)++)))<<16),          \
132                          l|=(((unsigned long)(*((c)++)))<< 8),          \
133                          l|=(((unsigned long)(*((c)++)))    )           )
134 #  define HOST_l2c(l,c)  (*((c)++)=(unsigned char)(((l)>>24)&0xff),      \
135                          *((c)++)=(unsigned char)(((l)>>16)&0xff),      \
136                          *((c)++)=(unsigned char)(((l)>> 8)&0xff),      \
137                          *((c)++)=(unsigned char)(((l)    )&0xff),      \
138                          l)
139 
140 # elif defined(DATA_ORDER_IS_LITTLE_ENDIAN)
141 
142 #  define HOST_c2l(c,l)  (l =(((unsigned long)(*((c)++)))    ),          \
143                          l|=(((unsigned long)(*((c)++)))<< 8),          \
144                          l|=(((unsigned long)(*((c)++)))<<16),          \
145                          l|=(((unsigned long)(*((c)++)))<<24)           )
146 #  define HOST_l2c(l,c)  (*((c)++)=(unsigned char)(((l)    )&0xff),      \
147                          *((c)++)=(unsigned char)(((l)>> 8)&0xff),      \
148                          *((c)++)=(unsigned char)(((l)>>16)&0xff),      \
149                          *((c)++)=(unsigned char)(((l)>>24)&0xff),      \
150                          l)
151 
152 # endif
153 
154 /*
155  * Time for some action :-)
156  */
157 
HASH_UPDATE(HASH_CTX * c,const void * data_,size_t len)158 int HASH_UPDATE(HASH_CTX *c, const void *data_, size_t len)
159 {
160     const unsigned char *data = data_;
161     unsigned char *p;
162     HASH_LONG l;
163     size_t n;
164 
165     if (ossl_unlikely(len == 0))
166         return 1;
167 
168     l = (c->Nl + (((HASH_LONG) len) << 3)) & 0xffffffffUL;
169     if (ossl_unlikely(l < c->Nl))              /* overflow */
170         c->Nh++;
171     c->Nh += (HASH_LONG) (len >> 29); /* might cause compiler warning on
172                                        * 16-bit */
173     c->Nl = l;
174 
175     n = c->num;
176     if (ossl_likely(n != 0)) {
177         p = (unsigned char *)c->data;
178 
179         if (len >= HASH_CBLOCK || len + n >= HASH_CBLOCK) {
180             memcpy(p + n, data, HASH_CBLOCK - n);
181             HASH_BLOCK_DATA_ORDER(c, p, 1);
182             n = HASH_CBLOCK - n;
183             data += n;
184             len -= n;
185             c->num = 0;
186             /*
187              * We use memset rather than OPENSSL_cleanse() here deliberately.
188              * Using OPENSSL_cleanse() here could be a performance issue. It
189              * will get properly cleansed on finalisation so this isn't a
190              * security problem.
191              */
192             memset(p, 0, HASH_CBLOCK); /* keep it zeroed */
193         } else {
194             memcpy(p + n, data, len);
195             c->num += (unsigned int)len;
196             return 1;
197         }
198     }
199 
200     n = len / HASH_CBLOCK;
201     if (n > 0) {
202         HASH_BLOCK_DATA_ORDER(c, data, n);
203         n *= HASH_CBLOCK;
204         data += n;
205         len -= n;
206     }
207 
208     if (len != 0) {
209         p = (unsigned char *)c->data;
210         c->num = (unsigned int)len;
211         memcpy(p, data, len);
212     }
213     return 1;
214 }
215 
HASH_TRANSFORM(HASH_CTX * c,const unsigned char * data)216 void HASH_TRANSFORM(HASH_CTX *c, const unsigned char *data)
217 {
218     HASH_BLOCK_DATA_ORDER(c, data, 1);
219 }
220 
HASH_FINAL(unsigned char * md,HASH_CTX * c)221 int HASH_FINAL(unsigned char *md, HASH_CTX *c)
222 {
223     unsigned char *p = (unsigned char *)c->data;
224     size_t n = c->num;
225 
226     p[n] = 0x80;                /* there is always room for one */
227     n++;
228 
229     if (n > (HASH_CBLOCK - 8)) {
230         memset(p + n, 0, HASH_CBLOCK - n);
231         n = 0;
232         HASH_BLOCK_DATA_ORDER(c, p, 1);
233     }
234     memset(p + n, 0, HASH_CBLOCK - 8 - n);
235 
236     p += HASH_CBLOCK - 8;
237 # if   defined(DATA_ORDER_IS_BIG_ENDIAN)
238     (void)HOST_l2c(c->Nh, p);
239     (void)HOST_l2c(c->Nl, p);
240 # elif defined(DATA_ORDER_IS_LITTLE_ENDIAN)
241     (void)HOST_l2c(c->Nl, p);
242     (void)HOST_l2c(c->Nh, p);
243 # endif
244     p -= HASH_CBLOCK;
245     HASH_BLOCK_DATA_ORDER(c, p, 1);
246     c->num = 0;
247     OPENSSL_cleanse(p, HASH_CBLOCK);
248 
249 # ifndef HASH_MAKE_STRING
250 #  error "HASH_MAKE_STRING must be defined!"
251 # else
252     HASH_MAKE_STRING(c, md);
253 # endif
254 
255     return 1;
256 }
257 
258 # ifndef MD32_REG_T
259 #  if defined(__alpha) || defined(__sparcv9) || defined(__mips)
260 #   define MD32_REG_T long
261 /*
262  * This comment was originally written for MD5, which is why it
263  * discusses A-D. But it basically applies to all 32-bit digests,
264  * which is why it was moved to common header file.
265  *
266  * In case you wonder why A-D are declared as long and not
267  * as MD5_LONG. Doing so results in slight performance
268  * boost on LP64 architectures. The catch is we don't
269  * really care if 32 MSBs of a 64-bit register get polluted
270  * with eventual overflows as we *save* only 32 LSBs in
271  * *either* case. Now declaring 'em long excuses the compiler
272  * from keeping 32 MSBs zeroed resulting in 13% performance
273  * improvement under SPARC Solaris7/64 and 5% under AlphaLinux.
274  * Well, to be honest it should say that this *prevents*
275  * performance degradation.
276  */
277 #  else
278 /*
279  * Above is not absolute and there are LP64 compilers that
280  * generate better code if MD32_REG_T is defined int. The above
281  * pre-processor condition reflects the circumstances under which
282  * the conclusion was made and is subject to further extension.
283  */
284 #   define MD32_REG_T int
285 #  endif
286 # endif
287 
288 #endif
289