summaryrefslogtreecommitdiff
path: root/lib/public_key/src/pubkey_ocsp.erl
blob: 249b4306605cbc521a5356b497b5c28027cabbf7 (plain)
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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
%%
%% %CopyrightBegin%
%%
%% Copyright Ericsson AB 2008-2020. All Rights Reserved.
%%
%% Licensed under the Apache License, Version 2.0 (the "License");
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%%     http://www.apache.org/licenses/LICENSE-2.0
%%
%% Unless required by applicable law or agreed to in writing, software
%% distributed under the License is distributed on an "AS IS" BASIS,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%
%% %CopyrightEnd%
%%

-module(pubkey_ocsp).

-include("public_key.hrl").

-export([otp_cert/1,
         get_ocsp_responder_id/1,
         get_nonce_extn/1,
         decode_ocsp_response/1,
         verify_ocsp_response/3,
         get_acceptable_response_types_extn/0,
         find_single_response/3,
         ocsp_status/1]).

ocsp_status({good, _}) ->
    valid;
ocsp_status({unknown, Reason}) ->
    {bad_cert, {revocation_status_undetermined, Reason}};
ocsp_status({revoked, Reason}) ->
    {bad_cert, {revoked, Reason}}.

%%--------------------------------------------------------------------
-spec verify_ocsp_response(binary(), list(), undefined | binary()) ->
    {ok, term()} | {error, term()}.
%%
%% Description: Verify the OCSP response to get the certificate status
%%--------------------------------------------------------------------
verify_ocsp_response(OCSPResponseDer, ResponderCerts, Nonce) ->
    do_verify_ocsp_response(
        decode_ocsp_response(OCSPResponseDer), ResponderCerts, Nonce
    ).

%%--------------------------------------------------------------------
-spec do_verify_ocsp_response({ok, #'BasicOCSPResponse'{}} | {error, term()},
                              list(), undefined | binary()) ->
    {ok, term()} | {error, term()}.
%%
%% Description: Verify the OCSP response to get the certificate status
%%--------------------------------------------------------------------
do_verify_ocsp_response(
    {ok, #'BasicOCSPResponse'{
        tbsResponseData = ResponseData,
        signatureAlgorithm = SignatureAlgo,
        signature = Signature,
        certs = Certs
    }}, ResponderCerts, Nonce) ->

    #'ResponseData'{
        responderID = ResponderID
    } = ResponseData,

    case verify_ocsp_signature(
        public_key:der_encode('ResponseData', ResponseData),
        SignatureAlgo#'AlgorithmIdentifier'.algorithm,
        Signature, Certs ++ ResponderCerts,
        ResponderID) of
        ok ->
            verify_ocsp_nonce(ResponseData, Nonce);
        {error, Reason} ->
            {error, Reason}
    end;
do_verify_ocsp_response({error, Reason}, _ResponderCerts, _Nonce) ->
    {error, Reason}.

%%--------------------------------------------------------------------
-spec verify_ocsp_nonce(#'ResponseData'{}, undefined | binary()) ->
    {ok, term()} | {error, nonce_mismatch}.
%%
%% Description: Check if the nonces matches in OCSP response
%%--------------------------------------------------------------------
verify_ocsp_nonce(ResponseData, Nonce) ->
    #'ResponseData'{
        responses = Responses,
        responseExtensions = ResponseExtns
    } = ResponseData,

    case get_nonce_value(ResponseExtns) of
        Nonce ->
            {ok, Responses};
        _Other ->
            {error, nonce_mismatch}
    end.

%%--------------------------------------------------------------------
-spec get_nonce_value(asn1_NOVALUE | list()) ->
    undefined | binary().
%%
%% Description: Get the nonce value from extensions
%%--------------------------------------------------------------------
%% no extensions present in response
get_nonce_value(asn1_NOVALUE) ->
    undefined;
%% extensions exist, but no oscp nonce
get_nonce_value([]) ->
    undefined;
get_nonce_value([#'Extension'{
                     extnID = ?'id-pkix-ocsp-nonce',
                     extnValue = Value} | _Extns]) ->
    Value;
get_nonce_value([_Extn | Rest]) ->
    get_nonce_value(Rest).

%%--------------------------------------------------------------------
-spec decode_ocsp_response(binary()) ->
    {ok, #'BasicOCSPResponse'{}} | {error, term()}.
%%
%% Description: Decode the OCSP response der
%%--------------------------------------------------------------------
decode_ocsp_response(Response) ->
    Resp = public_key:der_decode('OCSPResponse', Response),
    case Resp#'OCSPResponse'.responseStatus of
        successful ->
             decode_response_bytes(
                 Resp#'OCSPResponse'.responseBytes
             );
        Error ->
            {error, Error}
    end.

%%--------------------------------------------------------------------
-spec decode_response_bytes(#'ResponseBytes'{}) ->
    {ok, #'BasicOCSPResponse'{}} | {error, term()}.
%%
%% Description: Get basic ocsp response field
%%--------------------------------------------------------------------
decode_response_bytes(#'ResponseBytes'{
                          responseType = ?'id-pkix-ocsp-basic',
                          response = Data}) ->
    {ok, public_key:der_decode('BasicOCSPResponse', Data)};
decode_response_bytes(#'ResponseBytes'{responseType = RespType}) ->
    {error, {ocsp_response_type_not_supported, RespType}}.

%%--------------------------------------------------------------------
-spec verify_ocsp_signature(binary(), term(), term(), list(), term()) ->
    ok | {error, term()}.
%%
%% Description: Verify the signature of OCSP response
%%--------------------------------------------------------------------
verify_ocsp_signature(
    ResponseDataDer, SignatureAlgo, Signature, Certs, ResponderID) ->
    case find_responder_cert(ResponderID, Certs) of
        {ok, Cert} ->
            do_verify_ocsp_signature(
                ResponseDataDer, Signature, SignatureAlgo, Cert);
        {error, Reason} ->
            {error, Reason}
    end.

%%--------------------------------------------------------------------
-spec find_responder_cert(term(), list()) ->
    {ok, #'Certificate'{} | #'OTPCertificate'{}} | {error, term()}.
%%
%% Description: Find the OCSP responder's cert in input list
%%--------------------------------------------------------------------
find_responder_cert(_ResponderID, []) ->
    {error, ocsp_responder_cert_not_found};
find_responder_cert(ResponderID, [Cert | TCerts]) ->
    case is_responder(ResponderID, Cert) of
        true ->
            {ok, Cert};
        false ->
            find_responder_cert(ResponderID, TCerts)
    end.

%%--------------------------------------------------------------------
-spec do_verify_ocsp_signature(
        binary(), term(), term(), #'Certificate'{} | #'OTPCertificate'{}) ->
    ok | {error, term()}.
%%
%% Description: Verify the signature of OCSP response
%%--------------------------------------------------------------------
do_verify_ocsp_signature(ResponseDataDer, Signature, AlgorithmID, Cert) ->
    {DigestType, _SignatureType} = public_key:pkix_sign_types(AlgorithmID),
    case public_key:verify(
             ResponseDataDer, DigestType, Signature,
             get_public_key_rec(Cert)) of
        true ->
            ok;
        false ->
            {error, ocsp_response_bad_signature}
    end.

%%--------------------------------------------------------------------
-spec get_public_key_rec(#'Certificate'{} | #'OTPCertificate'{}) ->
    term().
%%
%% Description: Get the subject public key field
%%--------------------------------------------------------------------
get_public_key_rec(#'Certificate'{} = Cert) ->
    get_public_key_rec(otp_cert(Cert));
get_public_key_rec(#'OTPCertificate'{tbsCertificate = TbsCert}) ->
    PKInfo = TbsCert#'OTPTBSCertificate'.subjectPublicKeyInfo,
    PKInfo#'OTPSubjectPublicKeyInfo'.subjectPublicKey.

%%--------------------------------------------------------------------
-spec is_responder(tuple(), #'Certificate'{} | #'OTPCertificate'{}) ->
    boolean().
%%
%% Description: Check if is OCSP responder's cert
%%--------------------------------------------------------------------
is_responder({byName, Name}, Cert) ->
    public_key:der_encode('Name', Name) == get_subject_name(Cert);
is_responder({byKey, Key}, Cert) ->
    Key == crypto:hash(sha, get_public_key(Cert)).

%%--------------------------------------------------------------------
-spec otp_cert(#'Certificate'{} | #'OTPCertificate'{} | binary()) ->
    #'OTPCertificate'{}.
%%
%% Description: Convert to #'OTPCertificate'{}
%%--------------------------------------------------------------------
otp_cert(#'OTPCertificate'{} = Cert) ->
    Cert;
otp_cert(#'Certificate'{} = Cert) ->
    public_key:pkix_decode_cert(
        public_key:der_encode('Certificate', Cert), otp);
otp_cert(CertDer) when is_binary(CertDer) ->
    public_key:pkix_decode_cert(CertDer, otp).

%%--------------------------------------------------------------------
-spec get_ocsp_responder_id(#'Certificate'{}) -> binary().
%%
%% Description: Get the OCSP responder ID der
%%--------------------------------------------------------------------
get_ocsp_responder_id(#'Certificate'{tbsCertificate = TbsCert}) ->
    public_key:der_encode(
        'ResponderID', {byName, TbsCert#'TBSCertificate'.subject}).

%%--------------------------------------------------------------------
-spec get_subject_name(#'Certificate'{} | #'OTPCertificate'{}) -> binary().
%%
%% Description: Get the subject der from cert
%%--------------------------------------------------------------------
get_subject_name(#'Certificate'{} = Cert) ->
    get_subject_name(otp_cert(Cert));
get_subject_name(#'OTPCertificate'{tbsCertificate = TbsCert}) ->
    public_key:pkix_encode('Name', TbsCert#'OTPTBSCertificate'.subject, otp).

%%--------------------------------------------------------------------
-spec get_public_key(#'Certificate'{} | #'OTPCertificate'{}) -> binary().
%%
%% Description: Get the public key from cert
%%--------------------------------------------------------------------
get_public_key(#'Certificate'{} = Cert) ->
    get_public_key(otp_cert(Cert));
get_public_key(#'OTPCertificate'{tbsCertificate = TbsCert}) ->
    PKInfo = TbsCert#'OTPTBSCertificate'.subjectPublicKeyInfo,
    enc_pub_key(PKInfo#'OTPSubjectPublicKeyInfo'.subjectPublicKey).

enc_pub_key(Key = #'RSAPublicKey'{}) ->
    public_key:der_encode('RSAPublicKey', Key);
enc_pub_key({DsaInt, #'Dss-Parms'{}}) when is_integer(DsaInt) ->
    public_key:der_encode('DSAPublicKey', DsaInt);
enc_pub_key({#'ECPoint'{point = Key}, _ECParam}) ->
    Key.

%%--------------------------------------------------------------------
-spec get_nonce_extn(undefined | binary()) -> undefined | #'Extension'{}.
%%
%% Description: Get an OCSP nonce der
%%--------------------------------------------------------------------
get_nonce_extn(undefined) ->
    undefined;
get_nonce_extn(Nonce) when is_binary(Nonce) ->
    #'Extension'{
        extnID    = ?'id-pkix-ocsp-nonce',
        extnValue = Nonce
    }.

%%--------------------------------------------------------------------
-spec get_acceptable_response_types_extn() -> #'Extension'{}.
%%
%% Description: Get an acceptable response types der
%%--------------------------------------------------------------------
get_acceptable_response_types_extn() ->
    #'Extension'{
        extnID    = ?'id-pkix-ocsp-response',
        extnValue = public_key:der_encode(
            'AcceptableResponses', [?'id-pkix-ocsp-basic'])
    }.

%%--------------------------------------------------------------------
-spec get_serial_num(binary | #'Certificate'{} | #'OTPCertificate'{}) ->
    term().
%%
%% Description: Get the serial number of a certificate
%%--------------------------------------------------------------------
get_serial_num(Cert) ->
    #'OTPCertificate'{tbsCertificate = TbsCert} = otp_cert(Cert),
    TbsCert#'OTPTBSCertificate'.serialNumber.


%%--------------------------------------------------------------------
%% -spec find_single_response(#'OTPCertificate'{}, #'OTPCertificate'{}, 
%%                            [#'SingleResponse'{}]) ->
%%           #'SingleResponse'{} | {error, no_matched_response}.
%% %%
%% Description: Find the matched single response.
%%--------------------------------------------------------------------
find_single_response(Cert, IssuerCert, SingleResponseList) ->
    IssuerName = get_subject_name(IssuerCert),
    IssuerKey = get_public_key(IssuerCert),
    SerialNum = get_serial_num(Cert),
    match_single_response(
      IssuerName, IssuerKey, SerialNum, SingleResponseList).

match_single_response(_IssuerName, _IssuerKey, _SerialNum, []) ->
    {error, no_matched_response};
match_single_response(
    IssuerName, IssuerKey, SerialNum,
    [#'SingleResponse'{
        certID = #'CertID'{hashAlgorithm = Algo} = CertID
     } = Response | Responses]) ->
    HashType = public_key:pkix_hash_type(
        Algo#'AlgorithmIdentifier'.algorithm),
    case (SerialNum == CertID#'CertID'.serialNumber) andalso
         (crypto:hash(
             HashType, IssuerName) == CertID#'CertID'.issuerNameHash) andalso
         (crypto:hash(
             HashType, IssuerKey) == CertID#'CertID'.issuerKeyHash) of
        true ->
            {ok, Response};
        false ->
            match_single_response(IssuerName, IssuerKey, SerialNum, Responses)
    end.