1 /* lib_ksils12.h - rsyslog's KSI-LS12 support library
2  *
3  * Copyright 2013-2017 Adiscon GmbH and Guardtime, Inc.
4  *
5  * This file is part of rsyslog.
6  *
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *       http://www.apache.org/licenses/LICENSE-2.0
12  *       -or-
13  *       see COPYING.ASL20 in the source distribution
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  */
21 #ifndef INCLUDED_KSILS12_H
22 #define INCLUDED_KSILS12_H
23 #include <ksi/ksi.h>
24 
25 #include "lib_ksi_queue.h"
26 
27 #define MAX_ROOTS 64
28 
29 /* Flags and record types for TLV handling */
30 #define RSGT_FLAG_NONCRIT 0x20
31 #define RSGT_FLAG_FORWARD 0x40
32 #define RSGT_TYPE_MASK 0x1f
33 #define RSGT_FLAG_TLV16 0x80
34 
35 /* check return state of operation and abort, if non-OK */
36 #define CHKr(code) if((r = code) != 0) goto done
37 
38 /* check the return value of a ksi api call and log a message in case of error */
39 #define CHECK_KSI_API(code, context, msg) if((res = code) != 0) do { \
40 	reportKSIAPIErr(context, NULL, msg, res); \
41 	goto cleanup; \
42 	} while (0)
43 
44 
45 typedef enum LOGSIG_SyncMode_en {
46 	/** The block hashes and ksi signatures in one file */
47 	LOGSIG_ASYNCHRONOUS = 0x00,
48 	/** The block hashes and ksi signatures split into separate files */
49 	LOGSIG_SYNCHRONOUS = 0x01
50 } LOGSIG_SyncMode;
51 
52 enum {
53 	/* Signer state assigned before the signer thread is initialized. State remains
54 	 * until thread initialization begins. In case of system failure to create new
55 	 * thread state remains the same.
56 	 */
57 	SIGNER_IDLE = 0x01,
58 
59 	/* Signer state assigned while signer thread initialization is in progress.
60 	 */
61 	SIGNER_INIT = 0x02,
62 
63 	/* Signer state assigned when signer thread is initialized and ready to work.
64 	 */
65 	SIGNER_STARTED = 0x04,
66 
67 	/* Thread state assigned when signer thread is being closed (signer thread returns).
68 	 */
69 	SIGNER_STOPPED = 0x08
70 };
71 
72 /* Max number of roots inside the forest. This permits blocks of up to
73  * 2^MAX_ROOTS records. We assume that 64 is sufficient for all use
74  * cases ;) [and 64 is not really a waste of memory, so we do not even
75  * try to work with reallocs and such...]
76  */
77 
78 typedef struct rsksictx_s *rsksictx;
79 typedef struct ksifile_s *ksifile;
80 typedef struct ksierrctx_s ksierrctx_t;
81 
82 
83 /* context for gt calls. This primarily serves as a container for the
84  * config settings. The actual file-specific data is kept in ksifile.
85  */
86 struct rsksictx_s {
87 	KSI_CTX *ksi_ctx;	/* libksi's context object */
88 	KSI_DataHasher *hasher;
89 	KSI_HashAlgorithm hashAlg;
90 	KSI_HashAlgorithm hmacAlg;
91 	uint8_t bKeepRecordHashes;
92 	uint8_t bKeepTreeHashes;
93 	uint64_t blockLevelLimit;
94 	uint32_t blockTimeLimit;
95 	uint32_t effectiveBlockLevelLimit; /* level limit adjusted by gateway settings */
96 	uint8_t syncMode;
97 	uid_t	fileUID;	/* IDs for creation */
98 	uid_t	dirUID;
99 	gid_t	fileGID;
100 	gid_t	dirGID;
101 	int fCreateMode; /* mode to use when creating files */
102 	int fDirCreateMode; /* mode to use when creating files */
103 	char* aggregatorUri;
104 	char* aggregatorId;
105 	char* aggregatorKey;
106 	char* aggregatorEndpoints[KSI_CTX_HA_MAX_SUBSERVICES];
107 	int aggregatorEndpointCount;
108 	char* random_source;
109 	pthread_mutex_t module_lock;
110 	pthread_t signer_thread;
111 	ProtectedQueue *signer_queue;
112 	int signer_state;
113 	uint8_t disabled;	/* permits to disable the plugin --> set to 1 */
114 
115 	ksifile *ksi;		/* List of signature files for keeping track of block timeouts. */
116 	size_t ksiCapacity;
117 	size_t ksiCount;
118 
119 	char *debugFileName;
120 	int debugLevel;
121 	FILE *debugFile;
122 	uint64_t max_requests;
123 	void (*errFunc)(void *, unsigned char*);
124 	void (*logFunc)(void *, unsigned char*);
125 	void *usrptr; /* for error function */
126 };
127 
128 /* this describes a file, as far as librsksi is concerned */
129 struct ksifile_s {
130 	/* the following data items are mirrored from rsksictx to
131 	 * increase cache hit ratio (they are frequently accesed).
132 	 */
133 	KSI_HashAlgorithm hashAlg;
134 	uint8_t bKeepRecordHashes;
135 	uint8_t bKeepTreeHashes;
136 	uint64_t blockSizeLimit;
137 	uint32_t blockTimeLimit;
138 	/* end mirrored properties */
139 	uint8_t disabled; /* permits to disable this file --> set to 1 */
140 	uint8_t *IV; /* initial value for blinding masks */
141 	unsigned char lastLeaf[KSI_MAX_IMPRINT_LEN]; /* last leaf hash (maybe of previous block)
142 							--> preserve on term */
143 	unsigned char *blockfilename;
144 	unsigned char *ksifilename;
145 	unsigned char *statefilename;
146 	uint64_t nRecords;  /* current number of records in current block */
147 	uint64_t bInBlk;    /* are we currently inside a blk --> need to finish on close */
148 	time_t blockStarted;
149 	int8_t nRoots;
150 	/* algo engineering: roots structure is split into two arrays
151 	 * in order to improve cache hits.
152 	 */
153 	KSI_DataHash *roots[MAX_ROOTS];
154 	/* data members for the associated TLV file */
155 	FILE *blockFile;
156 	FILE *sigFile;	/* Note that this may only be closed by signer thread or when signer thread has terminated. */
157 	rsksictx ctx;
158 };
159 
160 /* the following defines the ksistate file record. Currently, this record
161  * is fixed, we may change that over time.
162  */
163 struct rsksistatefile {
164 	char hdr[9];	/* must be "KSISTAT10" */
165 	uint8_t hashID;
166 	uint8_t lenHash;
167 	/* after that, the hash value is contained within the file */
168 };
169 
170 /* error states */
171 #define RSGTE_SUCCESS 0 /* Success state */
172 #define RSGTE_IO 1 	/* any kind of io error */
173 #define RSGTE_FMT 2	/* data fromat error */
174 #define RSGTE_INVLTYP 3	/* invalid TLV type record (unexcpected at this point) */
175 #define RSGTE_OOM 4	/* ran out of memory */
176 #define RSGTE_LEN 5	/* error related to length records */
177 #define RSGTE_SIG_EXTEND 6/* error extending signature */
178 #define RSGTE_INVLD_RECCNT 7/* mismatch between actual records and records
179 				given in block-sig record */
180 #define RSGTE_INVLHDR 8/* invalid file header */
181 #define RSGTE_EOF 9 	/* specific EOF */
182 #define RSGTE_MISS_REC_HASH 10 /* record hash missing when expected */
183 #define RSGTE_MISS_TREE_HASH 11 /* tree hash missing when expected */
184 #define RSGTE_INVLD_REC_HASH 12 /* invalid record hash (failed verification) */
185 #define RSGTE_INVLD_TREE_HASH 13 /* invalid tree hash (failed verification) */
186 #define RSGTE_INVLD_REC_HASHID 14 /* invalid record hash ID (failed verification) */
187 #define RSGTE_INVLD_TREE_HASHID 15 /* invalid tree hash ID (failed verification) */
188 #define RSGTE_MISS_BLOCKSIG 16 /* block signature record missing when expected */
189 #define RSGTE_INVLD_SIGNATURE 17 /* Signature is invalid (KSI_Signature_verifyDataHash)*/
190 #define RSGTE_TS_CREATEHASH 18 /* error creating HASH (KSI_DataHash_create) */
191 #define RSGTE_TS_DERENCODE 19 /* error DER-Encoding a timestamp */
192 #define RSGTE_HASH_CREATE 20 /* error creating a hash */
193 #define RSGTE_END_OF_SIG 21 /* unexpected end of signature - more log line exist */
194 #define RSGTE_END_OF_LOG 22 /* unexpected end of log file - more signatures exist */
195 #define RSGTE_EXTRACT_HASH 23 /* error extracting hashes for record */
196 #define RSGTE_CONFIG_ERROR 24 /* Configuration error */
197 #define RSGTE_NETWORK_ERROR 25 /* Network error */
198 #define RSGTE_MISS_KSISIG 26 /* KSI signature missing */
199 #define RSGTE_INTERNAL 27 /* Internal error */
200 
201 #define getIVLenKSI(bh) (hashOutputLengthOctetsKSI((bh)->hashID))
202 #define rsksiSetBlockLevelLimit(ctx, limit) ((ctx)->blockLevelLimit = (ctx)->effectiveBlockLevelLimit = limit)
203 #define rsksiSetBlockTimeLimit(ctx, limit) ((ctx)->blockTimeLimit = limit)
204 #define rsksiSetKeepRecordHashes(ctx, val) ((ctx)->bKeepRecordHashes = val)
205 #define rsksiSetKeepTreeHashes(ctx, val) ((ctx)->bKeepTreeHashes = val)
206 #define rsksiSetFileFormat(ctx, val) ((ctx)->fileFormat = val)
207 #define rsksiSetSyncMode(ctx, val) ((ctx)->syncMode = val)
208 #define rsksiSetRandomSource(ctx, val) ((ctx)->random_source = strdup(val))
209 #define rsksiSetFileUID(ctx, val) ((ctx)->fileUID = val)	/* IDs for creation */
210 #define rsksiSetDirUID(ctx, val) ((ctx)->dirUID = val)
211 #define rsksiSetFileGID(ctx, val) ((ctx)->fileGID= val)
212 #define rsksiSetDirGID(ctx, val) ((ctx)->dirGID = val)
213 #define rsksiSetCreateMode(ctx, val) ((ctx)->fCreateMode= val)
214 #define rsksiSetDirCreateMode(ctx, val) ((ctx)->fDirCreateMode = val)
215 #define rsksiSetDebugLevel(ctx, val) ((ctx)->debugLevel = val)
216 
217 
218 int rsksiSetDebugFile(rsksictx ctx, char *val);
219 int rsksiSetAggregator(rsksictx ctx, char *uri, char *loginid, char *key);
220 int rsksiSetHashFunction(rsksictx ctx, char *algName);
221 int rsksiSetHmacFunction(rsksictx ctx, char *algName);
222 int rsksiInitModule(rsksictx ctx);
223 rsksictx rsksiCtxNew(void);
224 void rsksisetErrFunc(rsksictx ctx, void (*func)(void*, unsigned char *), void *usrptr);
225 void rsksisetLogFunc(rsksictx ctx, void (*func)(void*, unsigned char *), void *usrptr);
226 void reportKSIAPIErr(rsksictx ctx, ksifile ksi, const char *apiname, int ecode);
227 ksifile rsksiCtxOpenFile(rsksictx ctx, unsigned char *logfn);
228 int rsksifileDestruct(ksifile ksi);
229 void rsksiCtxDel(rsksictx ctx);
230 void sigblkInitKSI(ksifile ksi);
231 int sigblkAddRecordKSI(ksifile ksi, const unsigned char *rec, const size_t len);
232 int sigblkAddLeaf(ksifile ksi, const unsigned char *rec, const size_t len, bool metadata);
233 unsigned sigblkCalcLevel(unsigned leaves);
234 int sigblkFinishKSI(ksifile ksi);
235 int sigblkAddMetadata(ksifile ksi, const char *key, const char *value);
236 int sigblkCreateMask(ksifile ksi, KSI_DataHash **m);
237 int sigblkCreateHash(ksifile ksi, KSI_DataHash **r, const unsigned char *rec, const size_t len);
238 int sigblkHashTwoNodes(ksifile ksi, KSI_DataHash **node, KSI_DataHash *m, KSI_DataHash *r, uint8_t level);
239 
240 #endif  /* #ifndef INCLUDED_KSILS12_H */
241