aboutsummaryrefslogtreecommitdiffstats
path: root/lib/ssl/src/ssl_certificate_db.erl
blob: 80fdc5201aa09efeccf44273d6ff2c4102547515 (plain) (blame)
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
%%
%% %CopyrightBegin%
%%
%% Copyright Ericsson AB 2007-2012. All Rights Reserved.
%%
%% The contents of this file are subject to the Erlang Public License,
%% Version 1.1, (the "License"); you may not use this file except in
%% compliance with the License. You should have received a copy of the
%% Erlang Public License along with this software. If not, it can be
%% retrieved online at http://www.erlang.org/.
%%
%% Software distributed under the License is distributed on an "AS IS"
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%% the License for the specific language governing rights and limitations
%% under the License.
%%
%% %CopyrightEnd%
%%

%%----------------------------------------------------------------------
%% Purpose: Storage for trused certificats 
%%----------------------------------------------------------------------

-module(ssl_certificate_db).
-include("ssl_internal.hrl").
-include_lib("public_key/include/public_key.hrl").
-include_lib("kernel/include/file.hrl").

-export([create/0, remove/1, add_trusted_certs/3, 
	 remove_trusted_certs/2, insert/3, remove/2, clean/1,
	 ref_count/3, lookup_trusted_cert/4, foldl/3,
	 lookup_cached_pem/2, cache_pem_file/3, cache_pem_file/4,
	 lookup/2]).

-type time()      :: {non_neg_integer(), non_neg_integer(), non_neg_integer()}.

-define(NOT_TO_BIG, 10).

%%====================================================================
%% Internal application API
%%====================================================================

%%--------------------------------------------------------------------
-spec create() -> [db_handle()].
%% 
%% Description: Creates a new certificate db.
%% Note: lookup_trusted_cert/4 may be called from any process but only
%% the process that called create may call the other functions.
%%--------------------------------------------------------------------
create() ->
    [%% Let connection process delete trusted certs
     %% that can only belong to one connection. (Supplied directly
     %% on DER format to ssl:connect/listen.)
     ets:new(ssl_otp_cacertificate_db, [set, public]),
     %% Let connection processes call ref_count/3 directly
     ets:new(ssl_otp_ca_file_ref, [set, public]),
     ets:new(ssl_otp_pem_cache, [set, protected])
    ].

%%--------------------------------------------------------------------
-spec remove([db_handle()]) -> term().
%%
%% Description: Removes database db  
%%--------------------------------------------------------------------
remove(Dbs) ->
    lists:foreach(fun(Db) ->
			  true = ets:delete(Db)
		  end, Dbs).

%%--------------------------------------------------------------------
-spec lookup_trusted_cert(db_handle(), certdb_ref(), serialnumber(), issuer()) ->
				 undefined | {ok, {der_cert(), #'OTPCertificate'{}}}.

%%
%% Description: Retrives the trusted certificate identified by 
%% <SerialNumber, Issuer>. Ref is used as it is specified  
%% for each connection which certificates are trusted.
%%--------------------------------------------------------------------
lookup_trusted_cert(DbHandle, Ref, SerialNumber, Issuer) ->
    case lookup({Ref, SerialNumber, Issuer}, DbHandle) of
	undefined ->
	    undefined;
	[Certs] ->
	    {ok, Certs}
    end.

lookup_cached_pem([_, _, PemChache], MD5) ->
    lookup_cached_pem(PemChache, MD5);
lookup_cached_pem(PemChache, MD5) ->
    lookup(MD5, PemChache).

%%--------------------------------------------------------------------
-spec add_trusted_certs(pid(), string() | {der, list()}, [db_handle()]) -> {ok, [db_handle()]}.
%%
%% Description: Adds the trusted certificates from file <File> to the
%% runtime database. Returns Ref that should be handed to lookup_trusted_cert
%% together with the cert serialnumber and issuer.
%%--------------------------------------------------------------------
add_trusted_certs(_Pid, {der, DerList}, [CerDb, _,_]) ->
    NewRef = make_ref(),
    add_certs_from_der(DerList, NewRef, CerDb),
    {ok, NewRef};

add_trusted_certs(_Pid, File, [CertsDb, RefDb, PemChache] = Db) ->
    {ok, #file_info{mtime = LastWrite}} = file:read_file_info(File),
    MD5 = crypto:md5(File),
    case lookup_cached_pem(Db, MD5) of
	[{Mtime, Content}] ->
	    case LastWrite of
		Mtime ->
		    Ref0 = make_ref(),
		    insert(Ref0, [], 1, RefDb),
		    insert(MD5, {Mtime, Content, Ref0}, PemChache),
		    add_certs_from_pem(Content, Ref0, CertsDb),
		    {ok, Ref0};
		_ ->
		    new_trusted_cert_entry(File, LastWrite, Db)
	    end;
	[{Mtime, _Content, Ref0}] ->
	    case LastWrite of
		Mtime ->
		    ref_count(Ref0, RefDb, 1),
		    {ok, Ref0};
		_ ->
		    new_trusted_cert_entry(File, LastWrite, Db)
	    end;
	undefined ->
	    new_trusted_cert_entry(File, LastWrite, Db)
    end.
%%--------------------------------------------------------------------
-spec cache_pem_file(string(), time(), [db_handle()]) -> term().
-spec cache_pem_file(reference(), string(), time(), [db_handle()]) -> term().
%%
%% Description: Cache file as binary in DB
%%--------------------------------------------------------------------
cache_pem_file(File, Time, [_CertsDb, _RefDb, PemChache]) ->
    {ok, PemBin} = file:read_file(File), 
    Content = public_key:pem_decode(PemBin),
    MD5 = crypto:md5(File),
    insert(MD5, {Time, Content}, PemChache),
    {ok, Content}.

cache_pem_file(Ref, File, Time, [_CertsDb, _RefDb, PemChache]) ->
    {ok, PemBin} = file:read_file(File),
    Content = public_key:pem_decode(PemBin),
    MD5 = crypto:md5(File),
    insert(MD5, {Time, Content, Ref}, PemChache),
    {ok, Content}.

remove_trusted_certs(Ref, CertsDb) ->
    remove_certs(Ref, CertsDb).

%%--------------------------------------------------------------------
-spec remove(term(), db_handle()) -> term().
%%
%% Description: Removes an element in a <Db>.
%%--------------------------------------------------------------------
remove(Key, Db) ->
    _ = ets:delete(Db, Key).

%%--------------------------------------------------------------------
-spec lookup(term(), db_handle()) -> term() | undefined.
%%
%% Description: Looks up an element in a <Db>.
%%--------------------------------------------------------------------
lookup(Key, Db) ->
    case ets:lookup(Db, Key) of
	[] ->
	    undefined;
	Contents  ->
	    Pick = fun({_, Data}) -> Data;
		      ({_,_,Data}) -> Data
		   end,
	    [Pick(Data) || Data <- Contents]
    end.
%%--------------------------------------------------------------------
-spec foldl(fun(), term(), db_handle()) -> term().
%%
%% Description: Calls Fun(Elem, AccIn) on successive elements of the
%% cache, starting with AccIn == Acc0. Fun/2 must return a new
%% accumulator which is passed to the next call. The function returns
%% the final value of the accumulator. Acc0 is returned if the certifate
%% db is empty.
%%--------------------------------------------------------------------
foldl(Fun, Acc0, Cache) ->
    ets:foldl(Fun, Acc0, Cache).

%%--------------------------------------------------------------------
-spec ref_count(term(), db_handle(), integer()) -> integer().
%%
%% Description: Updates a reference counter in a <Db>.
%%--------------------------------------------------------------------
ref_count(Key, Db, N) ->
    ets:update_counter(Db,Key,N).

%%--------------------------------------------------------------------
-spec clean(db_handle()) -> term().
%%
%% Description: Updates a reference counter in a <Db>.
%%--------------------------------------------------------------------
clean(Db) ->
    case ets:info(Db, size) of
	N  when N < ?NOT_TO_BIG ->
	    ok;
	_ ->
	    ets:delete_all_objects(Db)
    end.
%%--------------------------------------------------------------------
%%-spec insert(Key::term(), Data::term(), Db::db_handle()) -> no_return().
%%
%% Description: Inserts data into <Db>
%%--------------------------------------------------------------------
insert(Key, Data, Db) ->
    true = ets:insert(Db, {Key, Data}).

%%--------------------------------------------------------------------
%%% Internal functions
%%--------------------------------------------------------------------
insert(Key, [], Count, Db) ->
    true = ets:insert(Db, {Key, Count});
insert(Key, Data, Count, Db) ->
    true = ets:insert(Db, {Key, Count, Data}).

remove_certs(Ref, CertsDb) ->
    ets:match_delete(CertsDb, {{Ref, '_', '_'}, '_'}).

add_certs_from_der(DerList, Ref, CertsDb) ->
    Add = fun(Cert) -> add_certs(Cert, Ref, CertsDb) end,
     [Add(Cert) || Cert <- DerList].

add_certs_from_pem(PemEntries, Ref, CertsDb) ->
    Add = fun(Cert) -> add_certs(Cert, Ref, CertsDb) end,
    [Add(Cert) || {'Certificate', Cert, not_encrypted} <- PemEntries].
    
add_certs(Cert, Ref, CertsDb) ->
    try  ErlCert = public_key:pkix_decode_cert(Cert, otp),
	 TBSCertificate = ErlCert#'OTPCertificate'.tbsCertificate,
	 SerialNumber = TBSCertificate#'OTPTBSCertificate'.serialNumber,
	 Issuer = public_key:pkix_normalize_name(
		    TBSCertificate#'OTPTBSCertificate'.issuer),
	 insert({Ref, SerialNumber, Issuer}, {Cert,ErlCert}, CertsDb)
    catch
	error:_ ->
	    Report = io_lib:format("SSL WARNING: Ignoring a CA cert as "
				   "it could not be correctly decoded.~n", []),
	    error_logger:info_report(Report)
    end.

new_trusted_cert_entry(File, LastWrite, [CertsDb,RefDb,PemChache] = Db) ->
    Ref = make_ref(),
    insert(Ref, [], 1, RefDb),
    {ok, Content} = cache_pem_file(Ref, File, LastWrite, Db),
    add_certs_from_pem(Content, Ref, CertsDb),
    {ok, Ref}.