Remove silly debug print from reg_handler()
[platform/upstream/crda.git] / crda.c
1 /*
2  * Central Regulatory Domain Agent for Linux
3  *
4  * Userspace helper which sends regulatory domains to Linux via nl80211
5  */
6
7 #include <errno.h>
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <sys/mman.h>
11 #include <sys/stat.h>
12 #include <fcntl.h>
13 #include <arpa/inet.h>
14
15 #include <netlink/genl/genl.h>
16 #include <netlink/genl/family.h>
17 #include <netlink/genl/ctrl.h>
18 #include <netlink/msg.h>
19 #include <netlink/attr.h>
20 #include <linux/nl80211.h>
21
22 #include "regdb.h"
23
24 #ifdef USE_OPENSSL
25 #include <openssl/objects.h>
26 #include <openssl/bn.h>
27 #include <openssl/rsa.h>
28 #include <openssl/sha.h>
29
30 #include "keys-ssl.c"
31 #endif
32
33 #ifdef USE_GCRYPT
34 #include <gcrypt.h>
35
36 #include "keys-gcrypt.c"
37 #endif
38
39 struct nl80211_state {
40         struct nl_handle *nl_handle;
41         struct nl_cache *nl_cache;
42         struct genl_family *nl80211;
43 };
44
45 static int nl80211_init(struct nl80211_state *state)
46 {
47         int err;
48
49         state->nl_handle = nl_handle_alloc();
50         if (!state->nl_handle) {
51                 fprintf(stderr, "Failed to allocate netlink handle.\n");
52                 return -ENOMEM;
53         }
54
55         if (genl_connect(state->nl_handle)) {
56                 fprintf(stderr, "Failed to connect to generic netlink.\n");
57                 err = -ENOLINK;
58                 goto out_handle_destroy;
59         }
60
61         state->nl_cache = genl_ctrl_alloc_cache(state->nl_handle);
62         if (!state->nl_cache) {
63                 fprintf(stderr, "Failed to allocate generic netlink cache.\n");
64                 err = -ENOMEM;
65                 goto out_handle_destroy;
66         }
67
68         state->nl80211 = genl_ctrl_search_by_name(state->nl_cache, "nl80211");
69         if (!state->nl80211) {
70                 fprintf(stderr, "nl80211 not found.\n");
71                 err = -ENOENT;
72                 goto out_cache_free;
73         }
74
75         return 0;
76
77  out_cache_free:
78         nl_cache_free(state->nl_cache);
79  out_handle_destroy:
80         nl_handle_destroy(state->nl_handle);
81         return err;
82 }
83
84 static void nl80211_cleanup(struct nl80211_state *state)
85 {
86         genl_family_put(state->nl80211);
87         nl_cache_free(state->nl_cache);
88         nl_handle_destroy(state->nl_handle);
89 }
90
91 static int reg_handler(struct nl_msg *msg, void *arg)
92 {
93         return NL_SKIP;
94 }
95
96 static int wait_handler(struct nl_msg *msg, void *arg)
97 {
98         int *finished = arg;
99         *finished = 1;
100         return NL_STOP;
101 }
102
103
104 static int error_handler(struct sockaddr_nl *nla, struct nlmsgerr *err, void *arg)
105 {
106         fprintf(stderr, "nl80211 error %d\n", err->error);
107         exit(err->error);
108 }
109
110 int isalpha_upper(char letter)
111 {
112         if (letter >= 'A' && letter <= 'Z')
113                 return 1;
114         return 0;
115 }
116
117 static int is_alpha2(char *alpha2)
118 {
119         if (isalpha_upper(alpha2[0]) && isalpha_upper(alpha2[1]))
120                 return 1;
121         return 0;
122 }
123
124 static int is_world_regdom(char *alpha2)
125 {
126         if (alpha2[0] == '0' && alpha2[1] == '0')
127                 return 1;
128         return 0;
129 }
130
131 static void *get_file_ptr(__u8 *db, int dblen, int structlen, __be32 ptr)
132 {
133         __u32 p = ntohl(ptr);
134
135         if (p > dblen - structlen) {
136                 fprintf(stderr, "Invalid database file, bad pointer!\n");
137                 exit(3);
138         }
139
140         return (void *)(db + p);
141 }
142
143 static int put_reg_rule(__u8 *db, int dblen, __be32 ruleptr, struct nl_msg *msg)
144 {
145         struct regdb_file_reg_rule *rule;
146         struct regdb_file_freq_range *freq;
147         struct regdb_file_power_rule *power;
148
149         rule    = get_file_ptr(db, dblen, sizeof(*rule), ruleptr);
150         freq    = get_file_ptr(db, dblen, sizeof(*freq), rule->freq_range_ptr);
151         power   = get_file_ptr(db, dblen, sizeof(*power), rule->power_rule_ptr);
152
153         NLA_PUT_U32(msg, NL80211_ATTR_REG_RULE_FLAGS,           ntohl(rule->flags));
154         NLA_PUT_U32(msg, NL80211_ATTR_FREQ_RANGE_START,         ntohl(freq->start_freq));
155         NLA_PUT_U32(msg, NL80211_ATTR_FREQ_RANGE_END,           ntohl(freq->end_freq));
156         NLA_PUT_U32(msg, NL80211_ATTR_FREQ_RANGE_MAX_BW,        ntohl(freq->max_bandwidth));
157         NLA_PUT_U32(msg, NL80211_ATTR_POWER_RULE_MAX_ANT_GAIN,  ntohl(power->max_antenna_gain));
158         NLA_PUT_U32(msg, NL80211_ATTR_POWER_RULE_MAX_EIRP,      ntohl(power->max_eirp));
159
160         return 0;
161
162 nla_put_failure:
163         return -1;
164 }
165
166 int main(int argc, char **argv)
167 {
168         int fd;
169         struct stat stat;
170         __u8 *db;
171         struct regdb_file_header *header;
172         struct regdb_file_reg_country *countries;
173         int dblen, siglen, num_countries, i, j, r;
174         char alpha2[2];
175         char *env_country;
176         struct nl80211_state nlstate;
177         struct nl_cb *cb = NULL;
178         struct nl_msg *msg;
179         int found_country = 0;
180         int finished = 0;
181
182         struct regdb_file_reg_rules_collection *rcoll;
183         struct regdb_file_reg_country *country;
184         struct nlattr *nl_reg_rules;
185         int num_rules;
186
187 #ifdef USE_OPENSSL
188         RSA *rsa;
189         __u8 hash[SHA_DIGEST_LENGTH];
190         int ok = 0;
191 #endif
192 #ifdef USE_GCRYPT
193         gcry_mpi_t mpi_e, mpi_n;
194         gcry_sexp_t rsa, signature, data;
195         __u8 hash[20];
196         int ok = 0;
197 #endif
198
199         char *regdb = "/usr/lib/crda/regulatory.bin";
200
201         if (argc != 1) {
202                 fprintf(stderr, "Usage: %s\n", argv[0]);
203                 return -EINVAL;
204         }
205
206         env_country = getenv("COUNTRY");
207         if (!env_country) {
208                 fprintf(stderr, "COUNTRY environment variable not set.\n");
209                 return -EINVAL;
210         }
211
212
213         if (!is_alpha2(env_country) && !is_world_regdom(env_country)) {
214                 fprintf(stderr, "Invalid alpha2 set in COUNTRY\n");
215                 return -EINVAL;
216         }
217
218         memcpy(alpha2, env_country, 2);
219
220         fd = open(regdb, O_RDONLY);
221         if (fd < 0) {
222                 perror("failed to open db file");
223                 return -ENOENT;
224         }
225
226         if (fstat(fd, &stat)) {
227                 perror("failed to fstat db file");
228                 return -EIO;
229         }
230
231         dblen = stat.st_size;
232
233         db = mmap(NULL, dblen, PROT_READ, MAP_PRIVATE, fd, 0);
234         if (db == MAP_FAILED) {
235                 perror("failed to mmap db file");
236                 return -EIO;
237         }
238
239         header = get_file_ptr(db, dblen, sizeof(*header), 0);
240
241         if (ntohl(header->magic) != REGDB_MAGIC) {
242                 fprintf(stderr, "Invalid database magic\n");
243                 return -EINVAL;
244         }
245
246         if (ntohl(header->version) != REGDB_VERSION) {
247                 fprintf(stderr, "Invalid database version\n");
248                 return -EINVAL;
249         }
250
251         siglen = ntohl(header->signature_length);
252         /* adjust dblen so later sanity checks don't run into the signature */
253         dblen -= siglen;
254
255         if (dblen <= sizeof(*header)) {
256                 fprintf(stderr, "Invalid signature length %d\n", siglen);
257                 return -EINVAL;
258         }
259
260         /* verify signature */
261 #ifdef USE_OPENSSL
262         rsa = RSA_new();
263         if (!rsa) {
264                 fprintf(stderr, "Failed to create RSA key\n");
265                 return -EINVAL;
266         }
267
268         if (SHA1(db, dblen, hash) != hash) {
269                 fprintf(stderr, "Failed to calculate SHA sum\n");
270                 RSA_free(rsa);
271                 return -EINVAL;
272         }
273
274         for (i = 0; i < sizeof(keys)/sizeof(keys[0]); i++) {
275                 rsa->e = &keys[i].e;
276                 rsa->n = &keys[i].n;
277
278                 if (RSA_size(rsa) != siglen)
279                         continue;
280
281                 ok = RSA_verify(NID_sha1, hash, SHA_DIGEST_LENGTH,
282                                 db + dblen, siglen, rsa) == 1;
283                 if (ok)
284                         break;
285         }
286
287         rsa->e = NULL;
288         rsa->n = NULL;
289         RSA_free(rsa);
290
291         if (!ok) {
292                 fprintf(stderr, "Database signature wrong\n");
293                 return -EINVAL;
294         }
295
296         BN_print_fp(stdout, &keys[0].n);
297 #endif
298
299 #ifdef USE_GCRYPT
300         /* initialise */
301         gcry_check_version(NULL);
302
303         /* hash the db */
304         gcry_md_hash_buffer(GCRY_MD_SHA1, hash, db, dblen);
305
306         if (gcry_sexp_build(&data, NULL, "(data (flags pkcs1) (hash sha1 %b))",
307                             20, hash)) {
308                 fprintf(stderr, "failed to build data expression\n");
309                 return 2;
310         }
311
312         if (gcry_sexp_build(&signature, NULL, "(sig-val (rsa (s %b)))",
313                             siglen, db + dblen)) {
314                 fprintf(stderr, "failed to build signature expression\n");
315                 return 2;
316         }
317
318         for (i = 0; i < sizeof(keys)/sizeof(keys[0]); i++) {
319                 if (gcry_mpi_scan(&mpi_e, GCRYMPI_FMT_USG,
320                                   keys[0].e, keys[0].len_e, NULL) ||
321                     gcry_mpi_scan(&mpi_n, GCRYMPI_FMT_USG,
322                                   keys[0].n, keys[0].len_n, NULL)) {
323                         fprintf(stderr, "failed to convert numbers\n");
324                         return 2;
325                 }
326
327                 if (gcry_sexp_build(&rsa, NULL,
328                                     "(public-key (rsa (n %m) (e %m)))",
329                                     mpi_n, mpi_e)) {
330                         fprintf(stderr, "failed to build rsa key\n");
331                         return 2;
332                 }
333
334                 if (!gcry_pk_verify(signature, data, rsa)) {
335                         ok = 1;
336                         break;
337                 }
338         }
339
340         if (!ok) {
341                 fprintf(stderr, "Database signature wrong\n");
342                 return 2;
343         }
344 #endif
345
346         num_countries = ntohl(header->reg_country_num);
347         countries = get_file_ptr(db, dblen,
348                                  sizeof(struct regdb_file_reg_country) * num_countries,
349                                  header->reg_country_ptr);
350
351         for (i = 0; i < num_countries; i++) {
352                 country = countries + i;
353                 if (memcmp(country->alpha2, alpha2, 2) == 0) {
354                         found_country = 1;
355                         break;
356                 }
357         }
358
359         if (!found_country) {
360                 fprintf(stderr, "failed to find a country match in regulatory database\n");
361                 return -1;
362         }
363
364         r = nl80211_init(&nlstate);
365         if (r)
366                 return -EIO;
367
368         msg = nlmsg_alloc();
369         if (!msg) {
370                 fprintf(stderr, "Failed to allocate netlink message.\n");
371                 r = -1;
372                 goto out;
373         }
374
375         genlmsg_put(msg, 0, 0, genl_family_get_id(nlstate.nl80211), 0,
376                 0, NL80211_CMD_SET_REG, 0);
377
378         rcoll = get_file_ptr(db, dblen, sizeof(*rcoll), country->reg_collection_ptr);
379         num_rules = ntohl(rcoll->reg_rule_num);
380         /* re-get pointer with sanity checking for num_rules */
381         rcoll = get_file_ptr(db, dblen,
382                              sizeof(*rcoll) + num_rules * sizeof(__be32),
383                              country->reg_collection_ptr);
384
385         NLA_PUT_STRING(msg, NL80211_ATTR_REG_ALPHA2, (char *) country->alpha2);
386
387         nl_reg_rules = nla_nest_start(msg, NL80211_ATTR_REG_RULES);
388         if (!nl_reg_rules) {
389                 r = -1;
390                 goto nla_put_failure;
391         }
392
393         for (j = 0; j < num_rules; j++) {
394                 struct nlattr *nl_reg_rule;
395                 nl_reg_rule = nla_nest_start(msg, i);
396                 if (!nl_reg_rule)
397                         goto nla_put_failure;
398
399                 r = put_reg_rule(db, dblen, rcoll->reg_rule_ptrs[j], msg);
400                 if (r)
401                         goto nla_put_failure;
402
403                 nla_nest_end(msg, nl_reg_rule);
404         }
405
406         nla_nest_end(msg, nl_reg_rules);
407
408         cb = nl_cb_alloc(NL_CB_CUSTOM);
409         if (!cb)
410                 goto cb_out;
411
412         r = nl_send_auto_complete(nlstate.nl_handle, msg);
413
414         if (r < 0) {
415                 fprintf(stderr, "failed to send regulatory request: %d\n", r);
416                 goto cb_out;
417         }
418
419         nl_cb_set(cb, NL_CB_VALID, NL_CB_CUSTOM, reg_handler, NULL);
420         nl_cb_set(cb, NL_CB_ACK, NL_CB_CUSTOM, wait_handler, &finished);
421         nl_cb_err(cb, NL_CB_CUSTOM, error_handler, NULL);
422
423         if (!finished) {
424                 r = nl_wait_for_ack(nlstate.nl_handle);
425                 if (r < 0) {
426                         fprintf(stderr, "failed to set regulatory domain: %d\n", r);
427                         goto cb_out;
428                 }
429         }
430
431 cb_out:
432         nl_cb_put(cb);
433 nla_put_failure:
434         nlmsg_free(msg);
435 out:
436         nl80211_cleanup(&nlstate);
437         return r;
438 }