chiark / gitweb /
pubkeys: Provide parser (and spec) for peer pubkeys files
[secnet.git] / pubkeys.fl.pl
1 #!/usr/bin/perl -w
2 # -*- C -*-
3 #
4 # secnet - pubkeys.fl.pl
5 #
6 # This file is part of secnet.
7 # See README for full list of copyright holders.
8 #
9 # secnet is free software; you can redistribute it and/or modify it
10 # under the terms of the GNU General Public License as published by
11 # the Free Software Foundation; either version 3 of the License, or
12 # (at your option) any later version.
13
14 # secnet is distributed in the hope that it will be useful, but
15 # WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17 # General Public License for more details.
18
19 # You should have received a copy of the GNU General Public License
20 # version 3 along with secnet; if not, see
21 # https://www.gnu.org/licenses/gpl.html.
22
23 # We process __DATA__ of this file first through the perl code,
24 # and then through flex.  We do it like this because directives
25 # with positional arguments are otherwise rather tedious to specify
26 # in flex.  Of course we could have used bison too but this seems
27 # better overall.
28
29 use strict;
30
31 our $do = '';
32 our $co = '';
33 our $kw;
34 our $kwid;
35 our @next_kw;
36 our $in_s;
37 our $data_off;
38
39 our %subst = (GRPIDSZ => 4, SERIALSZ => 4);
40
41 our $last_lno = -1;
42 sub lineno (;$$) {
43     my ($always, $delta) = @_;
44     my $o = '';
45     $delta //= 0;
46     if ($always || $. != $last_lno+1) {
47         $o .= sprintf "#line %d \"%s\"\n", $delta+$data_off+$., $0;
48     }
49     $last_lno = $.;
50     $o;
51 }
52
53 while (<DATA>) {
54         last if m/^\%\%\s*$/;
55         if (m/^!SUBSTCHECKS\s*$/) {
56                 foreach (keys %subst) {
57                         $do .= <<END
58 #if $_ != $subst{$_}
59 # error $_ value disagrees between pubkeys.fl.pl and C headers
60 #endif
61 END
62                 }
63                 next;
64         }
65         $do .= lineno();
66         $do .= $_;
67 }
68
69 sub inst ($) {
70         $do .= "%x $_[0]\n";
71         "<$_[0]>";
72 }
73
74 while (<DATA>) {
75     s#\{!2(\w+)\}# '{'.(2 * ($subst{$1}//die "$1 ?")).'}' #ge;
76     if (m/^!KEYWORD ([-0-9a-z]+)$/) {
77         die if $kw;
78         $kw = $1;
79         $kwid = $kw; $kwid =~ y/-/_/;
80         $in_s = "HK_${kwid}";
81         $co .= "{L}$kw { BEGIN($in_s); }\n";
82         next;
83     }
84     if (m/^!ARG (\w+) (\S.*\S) \{\s*$/) {
85         die unless $kw;
86         die if @next_kw;
87         $co .= inst("$in_s")."{S} { BEGIN(D_${kwid}_$1); }\n";
88         $co .= inst("D_${kwid}_$1")."$2 {\n";
89         $in_s = "HA_${kwid}_$1";
90         $co .= "\tBEGIN($in_s);\n";
91         @next_kw = ($kw);
92         $co .= lineno(1,1);
93         next;
94     }
95     if (m/^!\}\s*$/) {
96         die unless @next_kw;
97         $co .= lineno(1,0);
98         $co .= "}\n";
99         $kw = shift @next_kw;
100         next;
101     }
102     if (m/^!FINAL \{\s*$/) {
103         die unless $kw;
104         die if @next_kw;
105         $co .= inst("FIN_$kwid")."\\n { BEGIN(0); c->lno++; }\n";
106         $co .= inst("$in_s")."{L}/\\n {\n";
107         $co .= "\tBEGIN(FIN_$kwid);\n";
108         $co .= lineno(1,1);
109         @next_kw = (undef);
110         next;
111     }
112     if (m/^!/) {
113         die;
114     }
115     $co .= $_;
116     if (m/^\%\%\s*$/) {
117         $co .= lineno(1,1);
118     }
119 }
120
121 print $do, "%%\n", $co or die $!;
122
123 BEGIN { $data_off = __LINE__ + 1; }
124 __DATA__
125
126 L       [ \t]*
127 S       [ \t]+
128 BASE91S []-~!#-&(-[]+
129 %x SKIPNL
130
131 %option yylineno
132 %option noyywrap
133 %option batch
134 %option 8bit
135 %option nodefault
136 %option never-interactive
137
138 %option prefix="pkyy"
139
140 %option warn
141
142 %{
143
144 #include "secnet.h"
145 #include "pubkeys.h"
146 #include "util.h"
147 #include "unaligned.h"
148 #include "base91s/base91.h"
149
150 !SUBSTCHECKS
151
152 struct pubkeyset_context {
153     /* filled in during setup: */
154     struct log_if *log;
155     struct buffer_if *data_buf;
156     struct peer_keyset *building;
157     /* runtime: */
158     bool_t had_serial;
159     int lno;
160     const struct sigscheme_info *scheme;
161     uint8_t grpid[GRPIDSZ];
162     serialt serial;
163 };
164
165 static struct pubkeyset_context c[1];
166
167 #define LI (c->log)
168 #define HEX2BIN(v,l) ({                                                 \
169         int32_t outlen;                                                 \
170         bool_t ok=hex_decode((v), ((l)), &outlen, yytext, False);       \
171         assert(ok);                                                     \
172         assert(outlen==((l)));                                          \
173     })
174 #define HEX2BIN_ARRAY(v) HEX2BIN((v),sizeof((v)))
175 #define DOSKIPQ ({                                      \
176         BEGIN(SKIPNL);                                  \
177         break;                                          \
178     })
179 #define DOSKIP(m) ({                                    \
180         slilog(LI,M_INFO,"l.%d: " m, c->lno);   \
181         DOSKIPQ;                                        \
182     })
183 #define FAIL(m) do{                                     \
184         slilog(LI,M_ERR,"l.%d: " m, c->lno);    \
185         return -1;                                      \
186     }while(0)
187
188 %}
189
190 %%
191
192 !KEYWORD pkg
193 !ARG id [0-9a-f]{!2GRPIDSZ} {
194     HEX2BIN_ARRAY(c->grpid);
195 !}
196 !FINAL {
197 !}
198 !KEYWORD pub
199 !ARG algo [-0-9a-z]+ {
200     c->scheme = sigscheme_lookup(yytext);
201     if (!c->scheme) DOSKIP("unknown pk algorithm");
202 !}
203 !ARG data {BASE91S} {
204     /* baseE91 and thus base91s can sometimes store 14 bits per
205      * character pair, so the max decode ratio is 14/16. */
206     size_t maxl = base91s_decode_maxlen(yyleng);
207     buffer_init(c->data_buf,0);
208     if (buf_remaining_space(c->data_buf) < maxl) DOSKIP("pk data too long");
209     struct base91s b91;
210     base91s_init(&b91);
211     size_t l = base91s_decode(&b91, yytext, yyleng, c->data_buf->start);
212     l += base91s_decode_end(&b91, c->data_buf->start + l);
213     assert(l <= maxl);
214     buf_append(c->data_buf,l);
215 !}
216 !FINAL {
217     if (c->building->nkeys >= MAX_SIG_KEYS) DOSKIP("too many public keys");
218     struct sigpubkey_if *pubkey;
219     bool_t ok=c->scheme->loadpub(c->scheme,c->data_buf,
220                                  &pubkey,c->log);
221     if (!ok) break;
222     memcpy(c->building->keys[c->building->nkeys].id.b,
223            c->grpid,
224            GRPIDSZ);
225     assert(ALGIDSZ==1); /* otherwise need htons or htonl or something */
226     c->building->keys[c->building->nkeys].id.b[GRPIDSZ]=
227       c->scheme->algid;
228     c->building->keys[c->building->nkeys++].pubkey=pubkey;
229 !}
230
231 !KEYWORD serial
232 !ARG id [0-9a-f]{!2SERIALSZ} {
233     if (c->had_serial) FAIL("`serial' repeated");
234     c->had_serial = 1;
235     uint8_t sb[SERIALSZ];
236     HEX2BIN_ARRAY(sb);
237     c->serial=get_uint32(sb);
238 !}
239 !FINAL {
240 !}
241
242 {L}[-0-9a-z]+ {
243     DOSKIP("unknown directive");
244 }
245
246 {L}\# {
247     BEGIN(SKIPNL);
248 }
249 {L}\n {
250     c->lno++;
251 }
252
253 <SKIPNL>.*\n {
254     c->lno++;
255     BEGIN(0);
256 }
257
258 <INITIAL><<EOF>>        { return 0; }
259
260 <*>. { FAIL("syntax error"); }
261 <*>\n { FAIL("syntax error - unexpected newline"); }
262 <<EOF>> { FAIL("syntax error - unexpected eof"); }
263
264 %%
265
266 extern struct peer_keyset *
267 keyset_load(const char *path, struct buffer_if *data_buf,
268             struct log_if *log, int logcl_enoent) {
269     assert(!c->building);
270     c->log=log;
271     pkyyin = fopen(path, "r");
272     if (!pkyyin) {
273         slilog(LI,
274                errno==ENOENT ? logcl_enoent : M_ERR,
275                "could not open keyset file %s: %s",
276                path,strerror(errno));
277         goto err;
278     }
279
280     pkyyrestart(pkyyin);
281     BEGIN(0);
282     c->data_buf=data_buf;
283     NEW(c->building);
284     c->building->nkeys=0;
285     c->building->refcount=1;
286     c->had_serial=0;
287     c->lno=1;
288     FILLZERO(c->grpid);
289     FILLZERO(c->serial);
290     int r=pkyylex();
291     if (r) goto err_bad;
292
293     if (!c->had_serial) {
294         slilog(LI,M_ERR,"missing serial number in %s",path);
295         goto err_bad;
296     }
297     if (!c->building->nkeys) {
298         slilog(LI,M_ERR,"no useable keys in %s",path);
299         goto err_bad;
300     }
301     fclose(pkyyin);
302     struct peer_keyset *built=c->building;
303     c->building=0;
304     return built;
305
306  err_bad:
307     errno=EBADMSG;
308  err:
309     if (c->building) { free(c->building); c->building=0; }
310     if (pkyyin) { fclose(pkyyin); pkyyin=0; }
311     return 0;
312 }
313