Let the kernel use uevents to call CRDA.
[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         printf("=== reg_handler() called\n");
94         return NL_SKIP;
95 }
96
97 static int wait_handler(struct nl_msg *msg, void *arg)
98 {
99         int *finished = arg;
100         *finished = 1;
101         return NL_STOP;
102 }
103
104
105 static int error_handler(struct sockaddr_nl *nla, struct nlmsgerr *err, void *arg)
106 {
107         fprintf(stderr, "nl80211 error %d\n", err->error);
108         exit(err->error);
109 }
110
111 int isalpha_upper(char letter)
112 {
113         if (letter >= 65 && letter <= 90)
114                 return 1;
115         return 0;
116 }
117
118 static int is_alpha2(char *alpha2)
119 {
120         if (isalpha_upper(alpha2[0]) && isalpha_upper(alpha2[1]))
121                 return 1;
122         return 0;
123 }
124
125 static int is_world_regdom(char *alpha2)
126 {
127         /* ASCII 0 */
128         if (alpha2[0] == 48 && alpha2[1] == 48)
129                 return 1;
130         return 0;
131 }
132
133 static void *get_file_ptr(__u8 *db, int dblen, int structlen, __be32 ptr)
134 {
135         __u32 p = ntohl(ptr);
136
137         if (p > dblen - structlen) {
138                 fprintf(stderr, "Invalid database file, bad pointer!\n");
139                 exit(3);
140         }
141
142         return (void *)(db + p);
143 }
144
145 static int put_reg_rule(__u8 *db, int dblen, __be32 ruleptr, struct nl_msg *msg)
146 {
147         struct regdb_file_reg_rule *rule;
148         struct regdb_file_freq_range *freq;
149         struct regdb_file_power_rule *power;
150
151         rule    = get_file_ptr(db, dblen, sizeof(*rule), ruleptr);
152         freq    = get_file_ptr(db, dblen, sizeof(*freq), rule->freq_range_ptr);
153         power   = get_file_ptr(db, dblen, sizeof(*power), rule->power_rule_ptr);
154
155         NLA_PUT_U32(msg, NL80211_ATTR_REG_RULE_FLAGS,           ntohl(rule->flags));
156         NLA_PUT_U32(msg, NL80211_ATTR_FREQ_RANGE_START,         ntohl(freq->start_freq));
157         NLA_PUT_U32(msg, NL80211_ATTR_FREQ_RANGE_END,           ntohl(freq->end_freq));
158         NLA_PUT_U32(msg, NL80211_ATTR_FREQ_RANGE_MAX_BW,        ntohl(freq->max_bandwidth));
159         NLA_PUT_U32(msg, NL80211_ATTR_POWER_RULE_MAX_ANT_GAIN,  ntohl(power->max_antenna_gain));
160         NLA_PUT_U32(msg, NL80211_ATTR_POWER_RULE_MAX_EIRP,      ntohl(power->max_eirp));
161
162         return 0;
163
164 nla_put_failure:
165         return -1;
166 }
167
168 int main(int argc, char **argv)
169 {
170         int fd;
171         struct stat stat;
172         __u8 *db;
173         struct regdb_file_header *header;
174         struct regdb_file_reg_country *countries;
175         int dblen, siglen, num_countries, i, j, r;
176         char alpha2[2];
177         char *env_country;
178         struct nl80211_state nlstate;
179         struct nl_cb *cb = NULL;
180         struct nl_msg *msg;
181         int found_country = 0;
182         int finished = 0;
183
184         struct regdb_file_reg_rules_collection *rcoll;
185         struct regdb_file_reg_country *country;
186         struct nlattr *nl_reg_rules;
187         int num_rules;
188
189 #ifdef USE_OPENSSL
190         RSA *rsa;
191         __u8 hash[SHA_DIGEST_LENGTH];
192         int ok = 0;
193 #endif
194 #ifdef USE_GCRYPT
195         gcry_mpi_t mpi_e, mpi_n;
196         gcry_sexp_t rsa, signature, data;
197         __u8 hash[20];
198         int ok = 0;
199 #endif
200         char *regdb = "/usr/lib/crda/regulatory.bin";
201
202         if (argc != 1) {
203                 fprintf(stderr, "Usage: %s\n", argv[0]);
204                 return -EINVAL;
205         }
206
207         env_country = getenv("COUNTRY");
208         if (!env_country) {
209                 fprintf(stderr, "COUNTRY environment variable not set.\n");
210                 return -EINVAL;
211         }
212
213         
214         if (!is_alpha2(env_country) && !is_world_regdom(env_country)) {
215                 fprintf(stderr, "Invalid alpha2 set in COUNTRY\n");
216                 return -EINVAL;
217         }
218
219         memcpy(alpha2, env_country, 2);
220
221         r = nl80211_init(&nlstate);
222         if (r)
223                 return -EIO;
224
225         fd = open(regdb, O_RDONLY);
226         if (fd < 0) {
227                 perror("failed to open db file");
228                 r = -ENOENT;
229                 goto out;
230         }
231
232         if (fstat(fd, &stat)) {
233                 perror("failed to fstat db file");
234                 r = -EIO;
235                 goto out;
236         }
237
238         dblen = stat.st_size;
239
240         db = mmap(NULL, dblen, PROT_READ, MAP_PRIVATE, fd, 0);
241         if (db == MAP_FAILED) {
242                 perror("failed to mmap db file");
243                 r = -EIO;
244                 goto out;
245         }
246
247         header = get_file_ptr(db, dblen, sizeof(*header), 0);
248
249         if (ntohl(header->magic) != REGDB_MAGIC) {
250                 fprintf(stderr, "Invalid database magic\n");
251                 r = -EINVAL;
252                 goto out;
253         }
254
255         if (ntohl(header->version) != REGDB_VERSION) {
256                 fprintf(stderr, "Invalid database version\n");
257                 r = -EINVAL;
258                 goto out;
259         }
260
261         siglen = ntohl(header->signature_length);
262         /* adjust dblen so later sanity checks don't run into the signature */
263         dblen -= siglen;
264
265         if (dblen <= sizeof(*header)) {
266                 fprintf(stderr, "Invalid signature length %d\n", siglen);
267                 r = -EINVAL;
268                 goto out;
269         }
270
271         /* verify signature */
272 #ifdef USE_OPENSSL
273         rsa = RSA_new();
274         if (!rsa) {
275                 fprintf(stderr, "Failed to create RSA key\n");
276                 r = -EINVAL;
277                 goto out;
278         }
279
280         if (SHA1(db, dblen, hash) != hash) {
281                 fprintf(stderr, "Failed to calculate SHA sum\n");
282                 r = -EINVAL;
283                 goto out;
284         }
285
286         for (i = 0; i < sizeof(keys)/sizeof(keys[0]); i++) {
287                 rsa->e = &keys[i].e;
288                 rsa->n = &keys[i].n;
289
290                 if (RSA_size(rsa) != siglen)
291                         continue;
292
293                 ok = RSA_verify(NID_sha1, hash, SHA_DIGEST_LENGTH,
294                                 db + dblen, siglen, rsa) == 1;
295                 if (ok)
296                         break;
297         }
298
299         if (!ok) {
300                 fprintf(stderr, "Database signature wrong\n");
301                 r = -EINVAL;
302                 goto out;
303         }
304
305         rsa->e = NULL;
306         rsa->n = NULL;
307         RSA_free(rsa);
308
309         BN_print_fp(stdout, &keys[0].n);
310
311 #endif
312
313 #ifdef USE_GCRYPT
314         /* hash the db */
315         gcry_md_hash_buffer(GCRY_MD_SHA1, hash, db, dblen);
316
317         if (gcry_sexp_build(&data, NULL, "(data (flags pkcs1) (hash sha1 %b))",
318                             20, hash)) {
319                 fprintf(stderr, "failed to build data expression\n");
320                 return 2;
321         }
322
323         if (gcry_sexp_build(&signature, NULL, "(sig-val (rsa (s %b)))",
324                             siglen, db + dblen)) {
325                 fprintf(stderr, "failed to build signature expression\n");
326                 return 2;
327         }
328
329         for (i = 0; i < sizeof(keys)/sizeof(keys[0]); i++) {
330                 if (gcry_mpi_scan(&mpi_e, GCRYMPI_FMT_USG,
331                                   keys[0].e, keys[0].len_e, NULL) ||
332                     gcry_mpi_scan(&mpi_n, GCRYMPI_FMT_USG,
333                                   keys[0].n, keys[0].len_n, NULL)) {
334                         fprintf(stderr, "failed to convert numbers\n");
335                         return 2;
336                 }
337
338                 if (gcry_sexp_build(&rsa, NULL,
339                                     "(public-key (rsa (n %m) (e %m)))",
340                                     mpi_n, mpi_e)) {
341                         fprintf(stderr, "failed to build rsa key\n");
342                         return 2;
343                 }
344
345                 if (!gcry_pk_verify(signature, data, rsa)) {
346                         ok = 1;
347                         break;
348                 }
349         }
350
351         if (!ok) {
352                 fprintf(stderr, "Database signature wrong\n");
353                 return 2;
354         }
355
356 #endif
357
358         num_countries = ntohl(header->reg_country_num);
359         countries = get_file_ptr(db, dblen,
360                                  sizeof(struct regdb_file_reg_country) * num_countries,
361                                  header->reg_country_ptr);
362
363         for (i = 0; i < num_countries; i++) {
364                 country = countries + i;
365                 if (memcmp(country->alpha2, alpha2, 2) == 0) {
366                         found_country = 1;
367                         break;
368                 }
369         }
370
371         if (!found_country) {
372                 fprintf(stderr, "failed to find a country match in regulatory database\n");
373                 return -1;
374         }
375
376         msg = nlmsg_alloc();
377         if (!msg) {
378                 fprintf(stderr, "failed to allocate netlink msg\n");
379                 return -1;
380         }
381
382         genlmsg_put(msg, 0, 0, genl_family_get_id(nlstate.nl80211), 0,
383                 0, NL80211_CMD_SET_REG, 0);
384
385
386         rcoll = get_file_ptr(db, dblen, sizeof(*rcoll), country->reg_collection_ptr);
387         num_rules = ntohl(rcoll->reg_rule_num);
388         /* re-get pointer with sanity checking for num_rules */
389         rcoll = get_file_ptr(db, dblen,
390                              sizeof(*rcoll) + num_rules * sizeof(__be32),
391                              country->reg_collection_ptr);
392
393         NLA_PUT_STRING(msg, NL80211_ATTR_REG_ALPHA2, (char *) country->alpha2);
394
395         nl_reg_rules = nla_nest_start(msg, NL80211_ATTR_REG_RULES);
396         if (!nl_reg_rules) {
397                 r = -1;
398                 goto nla_put_failure;
399         }
400
401         for (j = 0; j < num_rules; j++) {
402                 struct nlattr *nl_reg_rule;
403                 nl_reg_rule = nla_nest_start(msg, i);
404                 if (!nl_reg_rule)
405                         goto nla_put_failure;
406
407                 r = put_reg_rule(db, dblen, rcoll->reg_rule_ptrs[j], msg);
408                 if (r)
409                         goto nla_put_failure;
410
411                 nla_nest_end(msg, nl_reg_rule);
412         }
413
414         nla_nest_end(msg, nl_reg_rules);
415
416         cb = nl_cb_alloc(NL_CB_CUSTOM);
417         if (!cb)
418                 goto cb_out;
419
420         r = nl_send_auto_complete(nlstate.nl_handle, msg);
421
422         if (r < 0) {
423                 fprintf(stderr, "failed to send regulatory request: %d\n", r);
424                 goto cb_out;
425         }
426
427         nl_cb_set(cb, NL_CB_VALID, NL_CB_CUSTOM, reg_handler, NULL);
428         nl_cb_set(cb, NL_CB_ACK, NL_CB_CUSTOM, wait_handler, &finished);
429         nl_cb_err(cb, NL_CB_CUSTOM, error_handler, NULL);
430
431         if (!finished) {
432                 r = nl_wait_for_ack(nlstate.nl_handle);
433                 if (r < 0) {
434                         fprintf(stderr, "failed to set regulatory domain: %d\n", r);
435                         goto cb_out;
436                 }
437         }
438
439 cb_out:
440         nl_cb_put(cb);
441 nla_put_failure:
442         nlmsg_free(msg);
443 out:
444         nl80211_cleanup(&nlstate);
445         return r;
446 }