summaryrefslogtreecommitdiff
path: root/src/sign.erl
blob: f7c71944d4bfbeef8742ef86a8570f3045d913c5 (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
%%% Copyright (c) 2014-2016, NORDUnet A/S.
%%% See LICENSE for licensing information.
%%%
%%% @doc Signing service

-module(sign).
-behaviour(gen_server).

%% API.
-export([start_link/0, stop/0]).
-export([sign_sct/2, sign_sth/1, get_pubkey/0, get_logid/0, verify_sth/2]).
-export([read_keyfile_ec/1, pem_entry_decode/1]).
%% API for tests.
-export([read_keyfile_rsa/2]).
%% gen_server callbacks.
-export([init/1, handle_call/3, terminate/2,
         handle_cast/2, handle_info/2, code_change/3]).

-include("timeouts.hrl").

-define(CERTIFICATE_TIMESTAMP, 0).
-define(TREE_HASH, 1).

-import(stacktrace, [call/2]).

-include_lib("public_key/include/public_key.hrl").

-record(state, {pubkey :: public_key:rsa_public_key(),
                privkey :: public_key:rsa_private_key(),
                hsmport :: port(),
                logid :: binary()
               }).

start_link() ->
    gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).

stop() ->
    call(?MODULE, stop).

get_log_public_key() ->
    Der = application:get_env(plop, log_public_key, none),
    pem_entry_decode({'SubjectPublicKeyInfo', Der, []}).

init([]) ->
    %% Read RSA keypair.
    %% {Private_key, Public_key} = read_keyfile_rsa(Keyfile, Passphrase),
    %% LogID = crypto:hash(sha256,
    %%                     public_key:der_encode('RSAPublicKey', Public_key)),
    %% Read EC keypair.
    Public_key = get_log_public_key(),
    LogID = get_logid(),

    case application:get_env(plop, hsm) of
        {ok, Args} ->
            Port = open_port({spawn_executable,
                              code:priv_dir(plop) ++ "/hsmhelper"},
                             [{args, Args},
                              exit_status,
                              {packet, 4}]),
            {ok, #state{pubkey = Public_key,
                        hsmport = Port,
                        logid = LogID}};
        undefined ->
            PrivKeyfile = application:get_env(plop, log_private_key, none),
            Private_key = read_keyfile_ec(PrivKeyfile),
            {ok, #state{pubkey = Public_key,
                        privkey = Private_key,
                        logid = LogID}}
    end.

%% TODO: Merge the keyfile reading functions.
%% @doc Read one password protected PEM file with an RSA keypair.
read_keyfile_rsa(Filename, Passphrase) ->
    {ok, PemBin} = file:read_file(Filename),
    [KeyPem] = public_key:pem_decode(PemBin),   % Use first entry.
    Privatekey = decode_key(KeyPem, Passphrase),
    {Privatekey, public_key(Privatekey)}.

filter_pem_types(ParsedPem, Types) ->
    [E || E <- ParsedPem,
          lists:member(element(1, E), Types)].

read_keyfile_ec(KeyFile) ->
    lager:debug("reading file ~p", [KeyFile]),
    {ok, PemBin} = file:read_file(KeyFile),
    [KeyPem] = filter_pem_types(public_key:pem_decode(PemBin), ['ECPrivateKey', 'SubjectPublicKeyInfo']),
    decode_key(KeyPem).

pem_entry_decode({'SubjectPublicKeyInfo', Der, _}) ->
    SPKI = public_key:der_decode('SubjectPublicKeyInfo', Der),
    {Octets, Algorithm} = plop_compat:unpack_spki(SPKI),
    #'AlgorithmIdentifier'{parameters = ECParams} = Algorithm,
    Params = public_key:der_decode('EcpkParameters', ECParams),
    Point = #'ECPoint'{point = Octets},
    {Point, Params};
pem_entry_decode(Entry) ->
    public_key:pem_entry_decode(Entry).

%% -spec signhash_rsa(iolist() | binary(), public_key:rsa_private_key()) -> binary().
%% signhash_rsa(Data, PrivKey) ->
%%     %% Was going to just crypto:sign/3 the hash but looking at
%%     %% digitally_signed() in lib/ssl/src/ssl_handshake.erl it seems
%%     %% like we should rather use (undocumented) encrypt_private/3.
%%     %public_key:sign(hash(sha256, BinToSign), sha256, PrivKey)
%%     public_key:encrypt_private(crypto:hash(sha256, Data),
%%                                PrivKey,
%%                                [{rsa_pad, rsa_pkcs1_padding}]).

-spec signhash_ec(iolist() | binary(), public_key:ec_private_key()) -> binary().
signhash_ec(Data, PrivKey) ->
    public_key:sign(Data, sha256, PrivKey).

decode_key(Entry) ->
    pem_entry_decode(Entry).
decode_key(Entry, Passphrase) ->
    public_key:pem_entry_decode(Entry, Passphrase).

public_key(#'RSAPrivateKey'{modulus = Mod, publicExponent = Exp}) ->
    #'RSAPublicKey'{modulus = Mod, publicExponent = Exp}.


remote_sign_request([], _Request) ->
    none;
remote_sign_request([URL|RestURLs], Request) ->
    case plop_httputil:request("signing", URL, [{"Content-Type", "text/json"}], list_to_binary(mochijson2:encode(Request))) of
        {error, Error} ->
            lager:info("request error: ~p", [Error]),
            remote_sign_request(RestURLs, Request);
        {failure, _StatusLine, _RespHeaders, _Body}  ->
            lager:debug("auth check failed"),
            remote_sign_request(RestURLs, Request);
        {success, {_HttpVersion, StatusCode, _ReasonPhrase}, _RespHeaders, Body} when StatusCode == 200 ->
            lager:debug("auth check succeeded"),
            case (catch mochijson2:decode(Body)) of
                {error, E} ->
                    lager:error("json parse error: ~p", [E]),
                    remote_sign_request(RestURLs, Request);
                {struct, PropList} ->
                    base64:decode(proplists:get_value(<<"result">>, PropList))
            end;
        {noauth, _StatusLine, _RespHeaders, _Body} ->
            lager:debug("no auth"),
            remote_sign_request(RestURLs, Request);
        _ ->
            remote_sign_request(RestURLs, Request)
    end.

verify_storage_signature(Data, Signature) ->
    case string:tokens(Signature, ":") of
        [Nodename, Sig] ->
            case http_auth:verify_stored(Nodename, Data, base64:decode(Sig)) of
                true ->
                    {ok, Nodename};
                _ ->
                    error
            end;
        _ ->
            error
    end.

verify_storage_signatures(Data, Signatures) ->
    Nodenames = sets:from_list(verify_storage_signatures(Data, Signatures, [])),
    AllowedStorageNodes = sets:from_list(plopconfig:get_env(storage_node_names, [])),
    sets:intersection(Nodenames, AllowedStorageNodes).

verify_storage_signatures(_Data, [], Nodes) ->
    Nodes;
verify_storage_signatures(Data, [Signature | Rest], Nodes) ->
    case verify_storage_signature(Data, Signature) of
        {ok, Node} ->
            verify_storage_signatures(Data, Rest, [Node | Nodes]);
        _ ->
            []
    end.

%%%%%%%%%%%%%%%%%%%%
%% Public API.

sign_sct(Data = <<_Version:8,
                  ?CERTIFICATE_TIMESTAMP:8,
                  _/binary>>, Signatures) ->
    Nodenames = verify_storage_signatures(Data, Signatures),
    lager:debug("sign_sct: signatures ~p ~p", [Signatures, sets:to_list(Nodenames)]),
    {ok, Quorum} = plopconfig:get_env(storage_sign_quorum),
    case sets:size(Nodenames) >= Quorum of
        true ->
            case plopconfig:get_env(signing_nodes) of
                {ok, URLBases} ->
                    Request = {[{plop_version, 1},
                                {data, base64:encode(Data)},
                                {signatures, Signatures}
                               ]},
                    remote_sign_request([URLBase ++ "sct" || URLBase <- URLBases], Request);
                undefined ->
                    call(?MODULE, {sign, Data})
            end;
        _ ->
            lager:error("signatures (~p) less than quorum (~p)", [sets:size(Nodenames), Quorum]),
            error
    end.

sign_sth(Data = <<_Version:8,
                  ?TREE_HASH:8,
                  _/binary>>) ->
    case plopconfig:get_env(signing_nodes) of
        {ok, URLBases} ->
            Request = {[{plop_version, 1},
                        {data, base64:encode(Data)}
                       ]},
            remote_sign_request([URLBase ++ "sth" || URLBase <- URLBases], Request);
        undefined ->
            call(?MODULE, {sign, Data})
    end.

get_pubkey() ->
    call(?MODULE, {get, pubkey}).

get_logid() ->
    Der = application:get_env(plop, log_public_key, none),
    crypto:hash(sha256, Der).

verify_sth(STH, Signature) ->
    lager:debug("verifying ~p: ~p", [STH, Signature]),
    PublicKey = get_log_public_key(),
    public_key:verify(STH, sha256, Signature, PublicKey).

encode_ec_signature(RawSignature, SignatureLength) ->
    <<R:SignatureLength, S:SignatureLength>> = RawSignature,
    {ok, Signature} = 'Dss':encode('Dss-Sig-Value', #'Dss-Sig-Value'{r = R, s = S}),
    Signature.


%%%%%%%%%%%%%%%%%%%%
%% gen_server callbacks.

handle_cast(_Request, State) ->
    {noreply, State}.

handle_info(_Info, State) ->
    {noreply, State}.

code_change(_OldVsn, State, _Extra) ->
    {ok, State}.

terminate(_Reason, _State) ->
    io:format("~p terminating~n", [?MODULE]),
    ok.

handle_call(stop, _From, State) ->
    {stop, normal, stopped, State};

handle_call({get, logid}, _From, State) ->
    {reply, State#state.logid, State};

handle_call({get, pubkey}, _From, State) ->
    {reply, State#state.pubkey, State};

handle_call({sign, Data}, _From, State) ->
    %% FIXME: Merge RSA and DC.
    case State#state.hsmport of
        undefined ->
            Signature = signhash_ec(Data, State#state.privkey),
            lager:debug("signing ~p: ~p", [Data, Signature]),
            {reply, Signature, State};
        Port ->
            lager:debug("sending signing request to HSM"),
            Port ! {self(), {command, crypto:hash(sha256, Data)}},
            receive
                {Port, {data, RawSignature}} when is_port(Port) ->
                    Signature = encode_ec_signature(list_to_binary(RawSignature), 256),
                    lager:debug("received signing reply from HSM: ~p", [Signature]),
                    {reply, Signature, State};
                {Port, {exit_status, ExitStatus}} ->
                    lager:error("hsmhelper port ~p exiting with status ~p",
                                [Port, ExitStatus]),
                    {stop, portexit, State}
            after
                ?SIGN_HSM_PORT_TIMEOUT ->
                    lager:error("HSM timeout"),
                    {stop, timeout, State}
            end
    end.