1 /* This Source Code Form is subject to the terms of the Mozilla Public
2  * License, v. 2.0. If a copy of the MPL was not distributed with this
3  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4 
5 /*
6  * secport.h - portability interfaces for security libraries
7  */
8 
9 #ifndef _SECPORT_H_
10 #define _SECPORT_H_
11 
12 #include "utilrename.h"
13 #include "prlink.h"
14 
15 /*
16  * define XP_WIN, XP_BEOS, or XP_UNIX, in case they are not defined
17  * by anyone else
18  */
19 #ifdef _WINDOWS
20 #ifndef XP_WIN
21 #define XP_WIN
22 #endif
23 #if defined(_WIN32) || defined(WIN32)
24 #ifndef XP_WIN32
25 #define XP_WIN32
26 #endif
27 #endif
28 #endif
29 
30 #ifdef __BEOS__
31 #ifndef XP_BEOS
32 #define XP_BEOS
33 #endif
34 #endif
35 
36 #ifdef unix
37 #ifndef XP_UNIX
38 #define XP_UNIX
39 #endif
40 #endif
41 
42 #include <sys/types.h>
43 
44 #include <ctype.h>
45 #include <string.h>
46 #include <stddef.h>
47 #include <stdlib.h>
48 #include <stdint.h>
49 #include "prtypes.h"
50 #include "prlog.h" /* for PR_ASSERT */
51 #include "plarena.h"
52 #include "plstr.h"
53 
54 /*
55  * HACK for NSS 2.8 to allow Admin to compile without source changes.
56  */
57 #ifndef SEC_BEGIN_PROTOS
58 #include "seccomon.h"
59 #endif
60 
61 /*
62  * The PORT_*Arena* function signatures mostly involve PLArenaPool* arguments.
63  * But this is misleading! It's not actually safe to use vanilla PLArenaPools
64  * with them. There are two "subclasses" of PLArenaPool that should be used
65  * instead.
66  *
67  * - PORTArenaPool (defined in secport.c): this "subclass" is always
68  *   heap-allocated and uses a (heap-allocated) lock to protect all accesses.
69  *   Use PORT_NewArena() and PORT_FreeArena() to create and destroy
70  *   PORTArenaPools.
71  *
72  * - PORTCheapArenaPool (defined here): this "subclass" can be stack-allocated
73  *   and does not use a lock to protect accesses. This makes it cheaper but
74  *   less general. It is best used for arena pools that (a) are hot, (b) have
75  *   lifetimes bounded within a single function, and (c) don't need locking.
76  *   Use PORT_InitCheapArena() and PORT_DestroyCheapArena() to initialize and
77  *   finalize PORTCheapArenaPools.
78  *
79  * All the other PORT_Arena* functions will operate safely with either
80  * subclass.
81  */
82 typedef struct PORTCheapArenaPool_str {
83     PLArenaPool arena;
84     PRUint32 magic; /* This is used to distinguish the two subclasses. */
85 } PORTCheapArenaPool;
86 
87 SEC_BEGIN_PROTOS
88 
89 extern void *PORT_Alloc(size_t len);
90 extern void *PORT_Realloc(void *old, size_t len);
91 extern void *PORT_ZAlloc(size_t len);
92 extern void *PORT_ZAllocAligned(size_t bytes, size_t alignment, void **mem);
93 extern void *PORT_ZAllocAlignedOffset(size_t bytes, size_t alignment,
94                                       size_t offset);
95 extern void PORT_Free(void *ptr);
96 extern void PORT_ZFree(void *ptr, size_t len);
97 extern char *PORT_Strdup(const char *s);
98 extern void PORT_SetError(int value);
99 extern int PORT_GetError(void);
100 
101 /* These functions are for use with PORTArenaPools. */
102 extern PLArenaPool *PORT_NewArena(unsigned long chunksize);
103 extern void PORT_FreeArena(PLArenaPool *arena, PRBool zero);
104 
105 /* These functions are for use with PORTCheapArenaPools. */
106 extern void PORT_InitCheapArena(PORTCheapArenaPool *arena,
107                                 unsigned long chunksize);
108 extern void PORT_DestroyCheapArena(PORTCheapArenaPool *arena);
109 
110 /* These functions work with both kinds of arena pool. */
111 extern void *PORT_ArenaAlloc(PLArenaPool *arena, size_t size);
112 extern void *PORT_ArenaZAlloc(PLArenaPool *arena, size_t size);
113 extern void *PORT_ArenaGrow(PLArenaPool *arena, void *ptr,
114                             size_t oldsize, size_t newsize);
115 extern void *PORT_ArenaMark(PLArenaPool *arena);
116 extern void PORT_ArenaRelease(PLArenaPool *arena, void *mark);
117 extern void PORT_ArenaZRelease(PLArenaPool *arena, void *mark);
118 extern void PORT_ArenaUnmark(PLArenaPool *arena, void *mark);
119 extern char *PORT_ArenaStrdup(PLArenaPool *arena, const char *str);
120 
121 SEC_END_PROTOS
122 
123 #define PORT_Assert PR_ASSERT
124 /* This is a variation of PORT_Assert where the arguments will be always
125  * used either in Debug or not. But, in optimized mode the result will be
126  * ignored. See more details in Bug 1588015. */
127 #define PORT_AssertArg PR_ASSERT_ARG
128 
129 /* Assert the current location can't be reached, passing a reason-string. */
130 #define PORT_AssertNotReached(reasonStr) PR_NOT_REACHED(reasonStr)
131 
132 /* macros to handle endian based byte conversion */
133 #define PORT_GET_BYTE_BE(value, offset, len) \
134     ((unsigned char)(((len) - (offset)-1) >= sizeof(value) ? 0 : (((value) >> (((len) - (offset)-1) * PR_BITS_PER_BYTE)) & 0xff)))
135 #define PORT_GET_BYTE_LE(value, offset, len) \
136     ((unsigned char)((offset) > sizeof(value) ? 0 : (((value) >> ((offset)*PR_BITS_PER_BYTE)) & 0xff)))
137 
138 /* This runs a function that should return SECSuccess.
139  * Intended for NSS internal use only.
140  * The return value is asserted in a debug build, otherwise it is ignored.
141  * This is no substitute for proper error handling.  It is OK only if you
142  * have ensured that the function cannot fail by other means such as checking
143  * prerequisites.  In that case this can be used as a safeguard against
144  * unexpected changes in a function.
145  */
146 #ifdef DEBUG
147 #define PORT_CheckSuccess(f) PR_ASSERT((f) == SECSuccess)
148 #else
149 #define PORT_CheckSuccess(f) (f)
150 #endif
151 #define PORT_ZNew(type) (type *)PORT_ZAlloc(sizeof(type))
152 #define PORT_ZNewAligned(type, alignment, mem) \
153     (type *)PORT_ZAllocAlignedOffset(sizeof(type), alignment, offsetof(type, mem))
154 #define PORT_New(type) (type *)PORT_Alloc(sizeof(type))
155 #define PORT_ArenaNew(poolp, type) \
156     (type *)PORT_ArenaAlloc(poolp, sizeof(type))
157 #define PORT_ArenaZNew(poolp, type) \
158     (type *)PORT_ArenaZAlloc(poolp, sizeof(type))
159 #define PORT_NewArray(type, num) \
160     (type *)PORT_Alloc(sizeof(type) * (num))
161 #define PORT_ZNewArray(type, num) \
162     (type *)PORT_ZAlloc(sizeof(type) * (num))
163 #define PORT_ArenaNewArray(poolp, type, num) \
164     (type *)PORT_ArenaAlloc(poolp, sizeof(type) * (num))
165 #define PORT_ArenaZNewArray(poolp, type, num) \
166     (type *)PORT_ArenaZAlloc(poolp, sizeof(type) * (num))
167 
168 /* Please, keep these defines sorted alphabetically.  Thanks! */
169 
170 #define PORT_Atoi(buff) (int)strtol(buff, NULL, 10)
171 
172 /* Returns a UTF-8 encoded constant error string for err.
173  * Returns NULL if initialization of the error tables fails
174  * due to insufficient memory.
175  *
176  * This string must not be modified by the application.
177  */
178 #define PORT_ErrorToString(err) PR_ErrorToString((err), PR_LANGUAGE_I_DEFAULT)
179 
180 #define PORT_ErrorToName PR_ErrorToName
181 
182 #define PORT_Memcmp memcmp
183 #define PORT_Memcpy memcpy
184 #ifndef SUNOS4
185 #define PORT_Memmove memmove
186 #else /*SUNOS4*/
187 #define PORT_Memmove(s, ct, n) bcopy((ct), (s), (n))
188 #endif /*SUNOS4*/
189 #define PORT_Memset memset
190 
191 #define PORT_Strcasecmp PL_strcasecmp
192 #define PORT_Strcat strcat
193 #define PORT_Strchr strchr
194 #define PORT_Strrchr strrchr
195 #define PORT_Strcmp strcmp
196 #define PORT_Strcpy strcpy
197 #define PORT_Strlen(s) strlen(s)
198 #define PORT_Strncasecmp PL_strncasecmp
199 #define PORT_Strncat strncat
200 #define PORT_Strncmp strncmp
201 #define PORT_Strncpy strncpy
202 #define PORT_Strpbrk strpbrk
203 #define PORT_Strstr strstr
204 #define PORT_Strtok strtok
205 
206 #define PORT_Tolower tolower
207 
208 typedef PRBool(PR_CALLBACK *PORTCharConversionWSwapFunc)(PRBool toUnicode,
209                                                          unsigned char *inBuf, unsigned int inBufLen,
210                                                          unsigned char *outBuf, unsigned int maxOutBufLen,
211                                                          unsigned int *outBufLen, PRBool swapBytes);
212 
213 typedef PRBool(PR_CALLBACK *PORTCharConversionFunc)(PRBool toUnicode,
214                                                     unsigned char *inBuf, unsigned int inBufLen,
215                                                     unsigned char *outBuf, unsigned int maxOutBufLen,
216                                                     unsigned int *outBufLen);
217 
218 SEC_BEGIN_PROTOS
219 
220 void PORT_SetUCS4_UTF8ConversionFunction(PORTCharConversionFunc convFunc);
221 void PORT_SetUCS2_ASCIIConversionFunction(PORTCharConversionWSwapFunc convFunc);
222 PRBool PORT_UCS4_UTF8Conversion(PRBool toUnicode, unsigned char *inBuf,
223                                 unsigned int inBufLen, unsigned char *outBuf,
224                                 unsigned int maxOutBufLen, unsigned int *outBufLen);
225 PRBool PORT_UCS2_ASCIIConversion(PRBool toUnicode, unsigned char *inBuf,
226                                  unsigned int inBufLen, unsigned char *outBuf,
227                                  unsigned int maxOutBufLen, unsigned int *outBufLen,
228                                  PRBool swapBytes);
229 void PORT_SetUCS2_UTF8ConversionFunction(PORTCharConversionFunc convFunc);
230 PRBool PORT_UCS2_UTF8Conversion(PRBool toUnicode, unsigned char *inBuf,
231                                 unsigned int inBufLen, unsigned char *outBuf,
232                                 unsigned int maxOutBufLen, unsigned int *outBufLen);
233 
234 /* One-way conversion from ISO-8859-1 to UTF-8 */
235 PRBool PORT_ISO88591_UTF8Conversion(const unsigned char *inBuf,
236                                     unsigned int inBufLen, unsigned char *outBuf,
237                                     unsigned int maxOutBufLen, unsigned int *outBufLen);
238 
239 extern PRBool
240 sec_port_ucs4_utf8_conversion_function(
241     PRBool toUnicode,
242     unsigned char *inBuf,
243     unsigned int inBufLen,
244     unsigned char *outBuf,
245     unsigned int maxOutBufLen,
246     unsigned int *outBufLen);
247 
248 extern PRBool
249 sec_port_ucs2_utf8_conversion_function(
250     PRBool toUnicode,
251     unsigned char *inBuf,
252     unsigned int inBufLen,
253     unsigned char *outBuf,
254     unsigned int maxOutBufLen,
255     unsigned int *outBufLen);
256 
257 /* One-way conversion from ISO-8859-1 to UTF-8 */
258 extern PRBool
259 sec_port_iso88591_utf8_conversion_function(
260     const unsigned char *inBuf,
261     unsigned int inBufLen,
262     unsigned char *outBuf,
263     unsigned int maxOutBufLen,
264     unsigned int *outBufLen);
265 
266 extern int NSS_PutEnv(const char *envVarName, const char *envValue);
267 
268 extern int NSS_SecureMemcmp(const void *a, const void *b, size_t n);
269 extern unsigned int NSS_SecureMemcmpZero(const void *mem, size_t n);
270 
271 /*
272  * Load a shared library called "newShLibName" in the same directory as
273  * a shared library that is already loaded, called existingShLibName.
274  * A pointer to a static function in that shared library,
275  * staticShLibFunc, is required.
276  *
277  * existingShLibName:
278  *   The file name of the shared library that shall be used as the
279  *   "reference library". The loader will attempt to load the requested
280  *   library from the same directory as the reference library.
281  *
282  * staticShLibFunc:
283  *   Pointer to a static function in the "reference library".
284  *
285  * newShLibName:
286  *   The simple file name of the new shared library to be loaded.
287  *
288  * We use PR_GetLibraryFilePathname to get the pathname of the loaded
289  * shared lib that contains this function, and then do a
290  * PR_LoadLibraryWithFlags with an absolute pathname for the shared
291  * library to be loaded.
292  *
293  * On Windows, the "alternate search path" strategy is employed, if available.
294  * On Unix, if existingShLibName is a symbolic link, and no link exists for the
295  * new library, the original link will be resolved, and the new library loaded
296  * from the resolved location.
297  *
298  * If the new shared library is not found in the same location as the reference
299  * library, it will then be loaded from the normal system library path.
300  */
301 PRLibrary *
302 PORT_LoadLibraryFromOrigin(const char *existingShLibName,
303                            PRFuncPtr staticShLibFunc,
304                            const char *newShLibName);
305 
306 SEC_END_PROTOS
307 
308 /*
309  * Constant time macros
310  */
311 /* These macros use the fact that arithmetic shift shifts-in the sign bit.
312  * However, this is not ensured by the C standard so you may need to replace
313  * them with something else for odd compilers. These macros work for object
314  * sizes up to 32 bits. The inequalities will produce incorrect results if
315  * abs(a-b) >= PR_UINT32_MAX/2. This can be a voided if unsigned values stay
316  * within the range 0-PRUINT32_MAX/2 and signed values stay within the range
317  * -PRINT32_MAX/2-PRINT32_MAX/2. If these are insufficient, we can fix
318  * this by either expanding the PORT_CT_DUPLICATE_MSB_TO_ALL to PRUint64
319  * or by creating the following new macros for inequality:
320  *
321  * PORT_CT_OVERFLOW prevents the overflow condition by handling the case
322  * where the high bits in a and b are different specially. Basically if
323  * the high bit in a and b differs we can just
324  * copy the high bit of one of the parameters to determine the result as
325  * follows:
326  *    GxU if a has the high bit on, a>b, so d=a
327  *    LxU if b has the high bit on, a<b, so d=b
328  *    GxS if b has the high bit on, it's negative a>b so d=b
329  *    LxS if a has the high bit on, it's negative a<b so d=a
330  * where PORT_CT_xxU() macros do unsigned compares and PORT_CT_xxS() do signed
331  * compares.
332  *
333  * #define PORT_CT_OVERFLOW(a,b,c,d) \
334  *       PORT_CT_SEL(PORT_CT_DUPLICATE_MSB_TO_ALL((a)^(b)), \
335  *                  (PORT_CT_DUPLICATE_MSB_TO_ALL(d)),c)
336  * #define PORT_CT_GTU(a,b) PORT_CT_OVERFLOW(a,b,PORT_CT_GT(a,b),a)
337  * #define PORT_CT_LTU(a,b) PORT_CT_OVERFLOW(a,b,PORT_CT_LT(a,b),b)
338  * #define PORT_CT_GEU(a,b) PORT_CT_OVERFLOW(a,b,PORT_CT_GE(a,b),a)
339  * #define PORT_CT_LEU(a,b) PORT_CT_OVERFLOW(a,b,PORT_CT_LE(a,b),b)
340  * #define PORT_CT_GTS(a,b) PORT_CT_OVERFLOW(a,b,PORT_CT_GT(a,b),b)
341  * #define PORT_CT_LTS(a,b) PORT_CT_OVERFLOW(a,b,PORT_CT_LT(a,b),a)
342  * #define PORT_CT_GES(a,b) PORT_CT_OVERFLOW(a,b,PORT_CT_GE(a,b),b)
343  * #define PORT_CT_LES(a,b) PORT_CT_OVERFLOW(a,b,PORT_CT_LE(a,b),a)
344  *
345  *
346  * */
347 /* Constant-time helper macro that copies the MSB of x to all other bits. */
348 #define PORT_CT_DUPLICATE_MSB_TO_ALL(x) ((PRUint32)((PRInt32)(x) >> (sizeof(PRInt32) * 8 - 1)))
349 
350 /* Constant-time helper macro that selects l or r depending on all-1 or all-0
351  * mask m */
352 #define PORT_CT_SEL(m, l, r) (((m) & (l)) | (~(m) & (r)))
353 
354 /* Constant-time helper macro that returns all-1s if x is not 0; and all-0s
355  * otherwise. */
356 #define PORT_CT_NOT_ZERO(x) (PORT_CT_DUPLICATE_MSB_TO_ALL(((x) | (0 - (x)))))
357 
358 /* Constant-time helper macro that returns all-1s if x is 0; and all-0s
359  * otherwise. */
360 #define PORT_CT_ZERO(x) (~PORT_CT_DUPLICATE_MSB_TO_ALL(((x) | (0 - (x)))))
361 
362 /* Constant-time helper macro for equalities and inequalities.
363  * returns all-1's for true and all-0's for false */
364 #define PORT_CT_EQ(a, b) PORT_CT_ZERO(((a) - (b)))
365 #define PORT_CT_NE(a, b) PORT_CT_NOT_ZERO(((a) - (b)))
366 #define PORT_CT_GT(a, b) PORT_CT_DUPLICATE_MSB_TO_ALL((b) - (a))
367 #define PORT_CT_LT(a, b) PORT_CT_DUPLICATE_MSB_TO_ALL((a) - (b))
368 #define PORT_CT_GE(a, b) (~PORT_CT_LT(a, b))
369 #define PORT_CT_LE(a, b) (~PORT_CT_GT(a, b))
370 #define PORT_CT_TRUE (~0)
371 #define PORT_CT_FALSE 0
372 
373 #endif /* _SECPORT_H_ */
374