summaryrefslogtreecommitdiff
path: root/src/plop.erl
blob: 8af641815d67512fcc083b1b4a8dae6404134e35 (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
%%% @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').
-include("plop.hrl").
-include_lib("public_key/include/public_key.hrl").
-include_lib("eunit/include/eunit.hrl").

-export([start/2, loop/1, dummy_add/1]).

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

-spec start(string(), string()) -> pid().
start(Keyfile, Passphrase) ->
    {Private_key, Public_key} = read_keyfile(Keyfile, Passphrase),
    LogID = crypto:hash(sha256, public_key:der_encode('RSAPublicKey', Public_key)),
    Plop = #plop{pubkey = Public_key,
                 privkey = Private_key,
                 logid = LogID,
                 hashtree = ht:create()},
    Pid = spawn_link(plop, loop, [Plop]),
    register(plop, Pid),
    Pid.

log(Format, Data) ->
    io:format(Format, Data).

loop(Plop) ->
    receive
        {From, quit} ->
            From ! {ok, quit};
        {From, Data} ->
            handle_req(From, Plop, Data),
            loop(Plop);
        Unknown ->
            log("DEBUG: Received malformed command: ~p~n", [Unknown]),
            loop(Plop)
    end.

-spec serialise(plop_entry() | plop_data()) -> iolist().
serialise(#plop_entry{type = EntryType, entry = Entry}) ->
    [<<EntryType:16>>, Entry];
serialise(#plop_data{version = Version,
                     signature_type = Sigtype,
                     timestamp = Timestamp,
                     entry = Entry}) ->
    [<<Version:8, Sigtype:8, Timestamp:64>>, serialise(Entry)].

handle_req(From,
           #plop{privkey = Privkey,
                 logid = LogID,
                 hashtree = Tree},
           Arg) ->
    case Arg of
        {add, PlopData = #plop_data{entry = Entry}} when is_record(Entry, plop_entry) ->
            %% fixme: add Entry to db,
            H = ht:append(Tree, serialise(Entry)),
            SPT = spt(LogID, Privkey, PlopData),
            %%io:format("adding ~p to ~p -> H: ~p, SPT: ~p~n",
                      [Entry, Tree, H, SPT]),
            From ! {ok, SPT};
        sth ->                                  % Signed tree head.
            From ! {ok, sth(Tree)};
        Unknown ->
            From ! {error, Unknown}
    end.

%% RFC6962
       %% Signed Timestamp
       %% struct {
       %%     Version sct_version;
       %%     LogID id;
       %%     uint64 timestamp;
       %%     CtExtensions extensions;
       %%     digitally-signed struct {
       %%         Version sct_version;
       %%         SignatureType signature_type = certificate_timestamp;
       %%         uint64 timestamp;
       %%         LogEntryType entry_type;
       %%         select(entry_type) {
       %%             case x509_entry: ASN.1Cert;
       %%             case precert_entry: PreCert;
       %%         } signed_entry;
       %%        CtExtensions extensions;
       %%     };
       %% } SignedCertificateTimestamp;
%% RRC 5246
   %% A digitally-signed element is encoded as a struct DigitallySigned:
   %%    struct {
   %%       SignatureAndHashAlgorithm algorithm;
   %%       opaque signature<0..2^16-1>;
   %%    } DigitallySigned;

-define(PLOPVERSION, 1).

%% @doc Signed Plop Timestamp.
spt(LogID, PrivKey, #plop_data{version = Version,        % >= 1
                               signature_type = Sigtype, % >= 0
                               timestamp = Timestamp_in,
                               entry = Entry = #plop_entry{}}) when is_binary(LogID) ->
    Timestamp = case Timestamp_in of
             now ->
                 {NowMegaSec, NowSec, NowMicroSec} = now(),
                 trunc(NowMegaSec * 1.0e9 + NowSec * 1.0e3 + NowMicroSec / 1.0e3);
             _ -> Timestamp_in
         end,
    BinToSign = list_to_binary(
                  serialise(#plop_data{version = Version,
                                       signature_type = Sigtype,
                                       timestamp = Timestamp,
                                       entry = Entry})),

    %% Was going to just 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)
    Signature = public_key:encrypt_private(crypto:hash(sha256, BinToSign),
                                           PrivKey,
                                           [{rsa_pad, rsa_pkcs1_padding}]),
    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
       %% digitally-signed struct {
       %%     Version version;
       %%     SignatureType signature_type = tree_hash;
       %%     uint64 timestamp;
       %%     uint64 tree_size;
       %%     opaque sha256_root_hash[32];
       %% } TreeHeadSignature;
sth(Tree) ->
    "FIXME: signed tree head for " ++ Tree.

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}.

%%%%%%%%%%%%%%%%%%%%
%% Playing around
dummy_add(String) ->
    String.

%%%%%%%%%%%%%%%%%%%%
%% Tests.
serialise_test_() ->
    Entry = #plop_entry{type = ?PLOP_ENTRY_TYPE_X509, entry = "foo"},
    Entry_serialised = <<0:16, "foo">>,
    [?_assertEqual(Entry_serialised, list_to_binary(serialise(Entry))),
     ?_assertEqual(<<1:8, 0:8, 0:64, Entry_serialised/binary>>,
                   list_to_binary(serialise(#plop_data{signature_type = 0,
                                                       timestamp = 0,
                                                       entry = Entry})))].