1 /*
2  * crypt.c
3  *
4  * ufdbGuard is copyrighted (C) 2005-2020 by URLfilterDB with all rights reserved.
5  *
6  * Parts of the ufdbGuard daemon are based on squidGuard.
7  * This module is NOT based on squidGuard.
8  *
9  * Encryption module
10  *
11  * $Id: crypt.c,v 1.15 2020/07/24 11:40:28 root Exp root $
12  */
13 
14 /* do not overprotect these tested functions. We need speed! */
15 #undef _FORTIFY_SOURCE
16 
17 #include "ufdb.h"
18 
19 #ifdef __cplusplus
20 extern "C" {
21 #endif
22 
23 
24 /* We want agressive optimisations: */
25 /* These pragmas only work for GCC 4.4 and above */
26 #if (__GNUC__ > 4)  ||  (__GNUC__ == 4  &&  __GNUC_MINOR__ >= 4)
27 #pragma GCC optimize ("O3")
28 #pragma GCC optimize ("inline-functions")
29 #endif
30 
31 
ufdbCryptInit(ufdbCrypt * uc,const unsigned char * key,unsigned int keySize,char * version)32 void ufdbCryptInit( ufdbCrypt * uc, const unsigned char * key, unsigned int keySize, char * version )
33 {
34    int             i;
35    unsigned int    t, u;
36    unsigned int    ki;
37    unsigned int    sti;
38    unsigned char * state;
39 
40    state = uc->state;
41 
42    uc->x = 0;
43    uc->y = 0;
44    for (i = 0; i < 256; i++)
45       state[i] = i;
46 
47 #if UFDB_DBFORMAT_3
48 #include <crypt3.c>
49 #else
50    if (version == NULL)         // prevent compiler warning
51       { ; }
52 #endif
53 
54    ki = 0;
55    sti = 0;
56    for (i = 0; i < 256; i++)
57    {
58       t = state[i];
59       sti = (sti + key[ki] + t) & 0x00FF;
60       u = state[sti];
61       state[sti] = t;
62       state[i] = u;
63       ki = (ki + 1) % keySize;
64    }
65 }
66 
67 
_nextByte(ufdbCrypt * uc)68 static UFDB_GCC_INLINE unsigned int _nextByte( ufdbCrypt * uc )
69 {
70    unsigned int x;
71    unsigned int y;
72    unsigned int sx, sy;
73    unsigned char * state;
74 
75    state = uc->state;
76 
77    x = (uc->x + 1) & 0x00FF;
78    sx = state[x];
79 
80    y = (sx + uc->y) & 0x00FF;
81    sy = state[y];
82 
83    uc->x = x;
84    uc->y = y;
85    state[y] = sx;
86    state[x] = sy;
87 
88    return state[(sx + sy) & 0x00FF];
89 }
90 
91 
ufdbEncryptText(ufdbCrypt * uc,unsigned char * dest,const unsigned char * src,unsigned int len)92 void ufdbEncryptText(
93    ufdbCrypt *           uc,
94    unsigned char *       dest,
95    const unsigned char * src,
96    unsigned int          len )
97 {
98    while (len > 0)
99    {
100       *dest = *src ^ _nextByte( uc );
101       src++;
102       dest++;
103       len--;
104    }
105 }
106 
107 
108 #ifdef __cplusplus
109 }
110 #endif
111 
112