summaryrefslogtreecommitdiff
path: root/src/plop.erl
blob: 390299d459d3aec124196a97eab27df105b7c5b9 (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
%%% @doc Server holding log entries in a database and hashes in a Merkle tree.
%%%
%%% When you submit data for insertion in the log, the data and a hash
%%% of it is stored in a way that [mumble FIXME and FIXME]. In return
%%% you will get a proof of your entry being included in the log. This
%%% proof can later, together with the public key of the log, be used
%%% to prove that your entry is indeed present in the log.

-module('plop').
-behaviour(gen_server).

%% API.
-export([start_link/0, start_link/2, stop/0]).
-export([add/1, sth/0]).
%% API for tests.
-export([sth/1]).
%% gen_server callbacks.
-export([init/1, handle_call/3, terminate/2,
         handle_cast/2, handle_info/2, code_change/3]).

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

-define(PLOPVERSION, 1).
-record(plop, {pubkey :: public_key:rsa_public_key(),
               privkey :: public_key:rsa_private_key(),
               logid :: binary(),
               hashtree :: ht:head()}).

start_link() ->
    start_link("test/rsakey.pem", "sikrit").
start_link(Keyfile, Passphrase) ->
    gen_server:start_link({local, ?MODULE}, ?MODULE, [Keyfile, Passphrase], []).

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

%%%%%%%%%%%%%%%%%%%%
init([Keyfile, Passphrase]) ->
    {Private_key, Public_key} = read_keyfile(Keyfile, Passphrase),
    LogID = crypto:hash(sha256,
                        public_key:der_encode('RSAPublicKey', Public_key)),
    {ok, #plop{pubkey = Public_key,
               privkey = Private_key,
               logid = LogID,
               hashtree = ht:create()}}.

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

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

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

terminate(_Reason, _State) ->
    ok.

%%%%%%%%%%%%%%%%%%%%
add(Data) when is_record(Data, spt) ->
    gen_server:call(?MODULE, {add, Data}).

sth() ->
    gen_server:call(?MODULE, {sth, []}).
sth(Data) ->
    gen_server:call(?MODULE, {sth, Data}).

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

handle_call({add, Data = #spt{entry = Entry}}, _From,
            Plop = #plop{privkey = Privkey,
                         logid = LogID,
                         hashtree = Tree}) ->
    %% fixme: add Entry to db,
    NewTree = ht:append(Tree, serialise(Entry)),
    io:format("Tree: ~p~nNewTree: ~p~n", [Tree, NewTree]),
    SPT = spt(LogID, Privkey, Data),
    {reply, SPT, Plop#plop{hashtree = NewTree}};

handle_call({sth, Data}, _From,
            Plop = #plop{privkey = PrivKey,
                         hashtree = Tree}) ->
    {reply, sth(PrivKey, Tree, Data), Plop}.

%%%%%%%%%%%%%%%%%%%%

%% @doc Signed Plop Timestamp according to RFC6962 3.2 and RFC5246 4.7.
-spec spt(binary(), binary(), spt()) -> binary().
spt(LogID, PrivKey, Data = #spt{timestamp = Timestamp_in}) ->
    Timestamp = timestamp(Timestamp_in),
    BinToSign =
        list_to_binary(serialise(Data#spt{
                                   signature_type = certificate_timestamp,
                                   timestamp = Timestamp})),
    Signature = signhash(BinToSign, PrivKey),
    SPT = <<?PLOPVERSION:8,
            LogID/binary,
            Timestamp:64,
            Signature/binary>>,
    %%io:format("SPT: ~p~nBinToSign: ~p~nSignature = ~p~n",
    %%          [SPT, BinToSign, Signature]),
    SPT.

%% @doc Signed Tree Head as described in RFC6962 section 3.2.
sth(PrivKey, Tree, []) ->
    sth(PrivKey, Tree, #sth{timestamp = now});
sth(PrivKey, Tree, #sth{version = Version, timestamp = Timestamp_in}) ->
    Timestamp = timestamp(Timestamp_in),
    Treesize = ht:size(Tree),
    Roothash = ht:tree_hash(Tree),
    BinToSign =
        list_to_binary(serialise(#sth{version = Version,
                                      signature_type = tree_hash,
                                      timestamp = Timestamp,
                                      tree_size = Treesize,
                                      root_hash = Roothash})),
    Signature = signhash(BinToSign, PrivKey),
    STH = <<Treesize:64,
            Timestamp:64,
            Roothash/binary,
            Signature/binary>>,
    %% io:format("STH: ~p~nBinToSign: ~p~nSignature: ~p~nTimestamp: ~p~n",
    %%           [STH, BinToSign, Signature, Timestamp]),
    STH.

read_keyfile(Filename, Passphrase) ->
    {ok, PemBin} = file:read_file(Filename),
    [Entry] = public_key:pem_decode(PemBin),
    Privatekey = public_key:pem_entry_decode(Entry, Passphrase),
    {Privatekey, public_key(Privatekey)}.

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

-spec signhash(iolist() | binary(), binary()) -> binary().
signhash(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 timestamp(now | integer()) -> integer().
timestamp(Timestamp) ->
    case Timestamp of
        now ->
            {NowMegaSec, NowSec, NowMicroSec} = now(),
            trunc(NowMegaSec * 1.0e9
                  + NowSec * 1.0e3
                  + NowMicroSec / 1.0e3);
        _ -> Timestamp
    end.

-spec serialise(spt() | sth() | plop_entry()) -> iolist().
serialise(#spt{version = Version,
               signature_type = SigtypeAtom,
               timestamp = Timestamp,
               entry = Entry}) ->
    Sigtype = signature_type(SigtypeAtom),
    [<<Version:8, Sigtype:8, Timestamp:64>>, serialise(Entry)];
serialise(#plop_entry{type = TypeAtom, data = Data}) ->
    Type = entry_type(TypeAtom),
    [<<Type:16>>, Data];
serialise(#sth{version = Version,
               signature_type = SigtypeAtom,
               timestamp = Timestamp,
               tree_size = Treesize,
               root_hash = Roothash}) ->
    Sigtype = signature_type(SigtypeAtom),
    [<<Version:8, Sigtype:8, Timestamp:64, Treesize:64, Roothash/binary>>].

-spec signature_type(signature_type()) -> integer().
signature_type(certificate_timestamp) -> 0;
signature_type(tree_hash) -> 1;
signature_type(test) -> 2.

-spec entry_type(entry_type()) -> integer().
entry_type(x509) -> 0;
entry_type(precert) -> 1;
entry_type(test) -> 2.

%%%%%%%%%%%%%%%%%%%%
%% Tests.
serialise_test_() ->
    [?_assertEqual(
        <<1:8, 0:8, 0:64, 0:16, "foo">>,
        list_to_binary(serialise(#spt{
                                    signature_type = certificate_timestamp,
                                    timestamp = 0,
                                    entry = #plop_entry{type = x509,
                                                        data = <<"foo">>}})))].