File: functions.bif

package info (click to toggle)
bro 2.5.5-1
  • links: PTS, VCS
  • area: main
  • in suites: buster, sid
  • size: 79,416 kB
  • sloc: ansic: 129,203; cpp: 96,492; yacc: 2,528; lex: 1,819; sh: 795; python: 700; makefile: 136
file content (264 lines) | stat: -rw-r--r-- 7,600 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
%%{
#include "file_analysis/analyzer/x509/X509.h"
#include "types.bif.h"

#include <openssl/x509.h>
#include <openssl/asn1.h>
#include <openssl/x509_vfy.h>
#include <openssl/ocsp.h>
#include <openssl/pem.h>
#include <openssl/err.h>

// This is the indexed map of X509 certificate stores.
static map<Val*, X509_STORE*> x509_stores;

// ### NOTE: while d2i_X509 does not take a const u_char** pointer,
// here we assume d2i_X509 does not write to <data>, so it is safe to
// convert data to a non-const pointer.  Could some X509 guru verify
// this?

X509* d2i_X509_(X509** px, const u_char** in, int len)
	{
#ifdef OPENSSL_D2I_X509_USES_CONST_CHAR
	  return d2i_X509(px, in, len);
#else
	  return d2i_X509(px, (u_char**)in, len);
#endif
	}

// construct an error record
RecordVal* x509_result_record(uint64_t num, const char* reason, Val* chainVector = 0)
	{
	RecordVal* rrecord = new RecordVal(BifType::Record::X509::Result);

	rrecord->Assign(0, new Val(num, TYPE_INT));
	rrecord->Assign(1, new StringVal(reason));
	if ( chainVector )
		rrecord->Assign(2, chainVector);

	return rrecord;
	}

X509_STORE* x509_get_root_store(TableVal* root_certs)
	{
	// If this certificate store was built previously, just reuse the old one.
	if ( x509_stores.count(root_certs) > 0 )
		return x509_stores[root_certs];

	X509_STORE* ctx = X509_STORE_new();
	ListVal* idxs = root_certs->ConvertToPureList();

	// Build the validation store
	for ( int i = 0; i < idxs->Length(); ++i )
		{
		Val* key = idxs->Index(i);
		StringVal *sv = root_certs->Lookup(key)->AsStringVal();
		assert(sv);
		const uint8* data = sv->Bytes();
		X509* x = d2i_X509_(NULL, &data, sv->Len());
		if ( ! x )
			{
			builtin_error(fmt("Root CA error: %s", ERR_error_string(ERR_get_error(),NULL)));
			return 0;
			}

		X509_STORE_add_cert(ctx, x);
		X509_free(x);
		}

	delete idxs;

	// Save the newly constructed certificate store into the cacheing map.
	x509_stores[root_certs] = ctx;

	return ctx;
	}

// get all cretificates starting at the second one (assuming the first one is the host certificate)
STACK_OF(X509)* x509_get_untrusted_stack(VectorVal* certs_vec)
	{
	STACK_OF(X509)* untrusted_certs = sk_X509_new_null();
	if ( ! untrusted_certs )
		{
		builtin_error(fmt("Untrusted certificate stack initialization error: %s", ERR_error_string(ERR_get_error(),NULL)));
		return 0;
		}

	for ( int i = 1; i < (int) certs_vec->Size(); ++i ) // start at 1 - 0 is host cert
		{
		Val *sv = certs_vec->Lookup(i);

		if ( ! sv )
			continue;

		// Fixme: check type
		X509* x = ((file_analysis::X509Val*) sv)->GetCertificate();
		if ( ! x )
			{
			sk_X509_free(untrusted_certs);
			builtin_error(fmt("No certificate in opaque in stack"));
			return 0;
			}

		sk_X509_push(untrusted_certs, x);
		}

	return untrusted_certs;
	}

%%}

## Parses a certificate into an X509::Certificate structure.
##
## cert: The X509 certificate opaque handle.
##
## Returns: A X509::Certificate structure.
##
## .. bro:see:: x509_certificate x509_extension x509_ext_basic_constraints
##              x509_ext_subject_alternative_name x509_verify
##              x509_get_certificate_string
function x509_parse%(cert: opaque of x509%): X509::Certificate
	%{
	assert(cert);
	file_analysis::X509Val* h = (file_analysis::X509Val*) cert;

	return file_analysis::X509::ParseCertificate(h);
	%}

## Returns the string form of a certificate.
##
## cert: The X509 certificate opaque handle.
##
## pem: A boolean that specifies if the certificate is returned
##      in pem-form (true), or as the raw ASN1 encoded binary
##      (false).
##
## Returns: X509 certificate as a string.
##
## .. bro:see:: x509_certificate x509_extension x509_ext_basic_constraints
##              x509_ext_subject_alternative_name x509_parse x509_verify
function x509_get_certificate_string%(cert: opaque of x509, pem: bool &default=F%): string
	%{
	assert(cert);
	file_analysis::X509Val* h = (file_analysis::X509Val*) cert;

	BIO *bio = BIO_new(BIO_s_mem());

	if ( pem )
		PEM_write_bio_X509(bio, h->GetCertificate());

	else
		i2d_X509_bio(bio, h->GetCertificate());

	StringVal* ext_val = file_analysis::X509::GetExtensionFromBIO(bio);

	if ( ! ext_val )
		ext_val = new StringVal("");

	return ext_val;
	%}


## Verifies a certificate.
##
## certs: Specifies a certificate chain that is being used to validate
##        the given certificate against the root store given in *root_certs*.
##        The host certificate has to be at index 0.
##
## root_certs: A list of root certificates to validate the certificate chain.
##
## verify_time: Time for the validity check of the certificates.
##
## Returns: A record of type X509::Result containing the result code of the
##          verify operation. In case of success also returns the full
##          certificate chain.
##
## .. bro:see:: x509_certificate x509_extension x509_ext_basic_constraints
##              x509_ext_subject_alternative_name x509_parse
##              x509_get_certificate_string x509_ocsp_verify
function x509_verify%(certs: x509_opaque_vector, root_certs: table_string_of_string, verify_time: time &default=network_time()%): X509::Result
	%{
	X509_STORE* ctx = x509_get_root_store(root_certs->AsTableVal());
	if ( ! ctx )
		return x509_result_record(-1, "Problem initializing root store");


	VectorVal *certs_vec = certs->AsVectorVal();
	if ( ! certs_vec || certs_vec->Size() < 1 )
		{
		reporter->Error("No certificates given in vector");
		return x509_result_record(-1, "no certificates");
		}

	// host certificate
	unsigned int index = 0; // to prevent overloading to 0pointer
	Val *sv = certs_vec->Lookup(index);
	if ( !sv )
		{
		builtin_error("undefined value in certificate vector");
		return x509_result_record(-1, "undefined value in certificate vector");
		}
	file_analysis::X509Val* cert_handle = (file_analysis::X509Val*) sv;

	X509* cert = cert_handle->GetCertificate();
	if ( ! cert )
		{
		builtin_error(fmt("No certificate in opaque"));
		return x509_result_record(-1, "No certificate in opaque");
		}

	STACK_OF(X509)* untrusted_certs = x509_get_untrusted_stack(certs_vec);
	if ( ! untrusted_certs )
		return x509_result_record(-1, "Problem initializing list of untrusted certificates");

	X509_STORE_CTX *csc = X509_STORE_CTX_new();
	X509_STORE_CTX_init(csc, ctx, cert, untrusted_certs);
	X509_STORE_CTX_set_time(csc, 0, (time_t) verify_time);
	X509_STORE_CTX_set_flags(csc, X509_V_FLAG_USE_CHECK_TIME);

	int result = X509_verify_cert(csc);

	VectorVal* chainVector = 0;

	if ( result == 1 ) // we have a valid chain. try to get it...
		{
		STACK_OF(X509)* chain = X509_STORE_CTX_get1_chain(csc); // get1 = deep copy

		if ( ! chain )
			{
			reporter->Error("Encountered valid chain that could not be resolved");
			sk_X509_pop_free(chain, X509_free);
			goto x509_verify_chainerror;
			}

		int num_certs = sk_X509_num(chain);
		chainVector = new VectorVal(internal_type("x509_opaque_vector")->AsVectorType());

		for ( int i = 0; i < num_certs; i++ )
			{
			X509* currcert = sk_X509_value(chain, i);

			if ( currcert )
				// X509Val takes ownership of currcert.
				chainVector->Assign(i, new file_analysis::X509Val(currcert));
			else
				{
				reporter->InternalWarning("OpenSSL returned null certificate");
				sk_X509_pop_free(chain, X509_free);
				goto x509_verify_chainerror;
				}
			}

		sk_X509_free(chain);
		}

x509_verify_chainerror:

	X509_STORE_CTX_cleanup(csc);

	sk_X509_free(untrusted_certs);

	RecordVal* rrecord = x509_result_record(X509_STORE_CTX_get_error(csc), X509_verify_cert_error_string(X509_STORE_CTX_get_error(csc)), chainVector);

	return rrecord;
	%}