GNU Linux-libre 4.9.283-gnu1
[releases.git] / net / ipv4 / cipso_ipv4.c
1 /*
2  * CIPSO - Commercial IP Security Option
3  *
4  * This is an implementation of the CIPSO 2.2 protocol as specified in
5  * draft-ietf-cipso-ipsecurity-01.txt with additional tag types as found in
6  * FIPS-188.  While CIPSO never became a full IETF RFC standard many vendors
7  * have chosen to adopt the protocol and over the years it has become a
8  * de-facto standard for labeled networking.
9  *
10  * The CIPSO draft specification can be found in the kernel's Documentation
11  * directory as well as the following URL:
12  *   http://tools.ietf.org/id/draft-ietf-cipso-ipsecurity-01.txt
13  * The FIPS-188 specification can be found at the following URL:
14  *   http://www.itl.nist.gov/fipspubs/fip188.htm
15  *
16  * Author: Paul Moore <paul.moore@hp.com>
17  *
18  */
19
20 /*
21  * (c) Copyright Hewlett-Packard Development Company, L.P., 2006, 2008
22  *
23  * This program is free software;  you can redistribute it and/or modify
24  * it under the terms of the GNU General Public License as published by
25  * the Free Software Foundation; either version 2 of the License, or
26  * (at your option) any later version.
27  *
28  * This program is distributed in the hope that it will be useful,
29  * but WITHOUT ANY WARRANTY;  without even the implied warranty of
30  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See
31  * the GNU General Public License for more details.
32  *
33  * You should have received a copy of the GNU General Public License
34  * along with this program;  if not, see <http://www.gnu.org/licenses/>.
35  *
36  */
37
38 #include <linux/init.h>
39 #include <linux/types.h>
40 #include <linux/rcupdate.h>
41 #include <linux/list.h>
42 #include <linux/spinlock.h>
43 #include <linux/string.h>
44 #include <linux/jhash.h>
45 #include <linux/audit.h>
46 #include <linux/slab.h>
47 #include <net/ip.h>
48 #include <net/icmp.h>
49 #include <net/tcp.h>
50 #include <net/netlabel.h>
51 #include <net/cipso_ipv4.h>
52 #include <linux/atomic.h>
53 #include <linux/bug.h>
54 #include <asm/unaligned.h>
55
56 /* List of available DOI definitions */
57 /* XXX - This currently assumes a minimal number of different DOIs in use,
58  * if in practice there are a lot of different DOIs this list should
59  * probably be turned into a hash table or something similar so we
60  * can do quick lookups. */
61 static DEFINE_SPINLOCK(cipso_v4_doi_list_lock);
62 static LIST_HEAD(cipso_v4_doi_list);
63
64 /* Label mapping cache */
65 int cipso_v4_cache_enabled = 1;
66 int cipso_v4_cache_bucketsize = 10;
67 #define CIPSO_V4_CACHE_BUCKETBITS     7
68 #define CIPSO_V4_CACHE_BUCKETS        (1 << CIPSO_V4_CACHE_BUCKETBITS)
69 #define CIPSO_V4_CACHE_REORDERLIMIT   10
70 struct cipso_v4_map_cache_bkt {
71         spinlock_t lock;
72         u32 size;
73         struct list_head list;
74 };
75
76 struct cipso_v4_map_cache_entry {
77         u32 hash;
78         unsigned char *key;
79         size_t key_len;
80
81         struct netlbl_lsm_cache *lsm_data;
82
83         u32 activity;
84         struct list_head list;
85 };
86
87 static struct cipso_v4_map_cache_bkt *cipso_v4_cache;
88
89 /* Restricted bitmap (tag #1) flags */
90 int cipso_v4_rbm_optfmt = 0;
91 int cipso_v4_rbm_strictvalid = 1;
92
93 /*
94  * Protocol Constants
95  */
96
97 /* Maximum size of the CIPSO IP option, derived from the fact that the maximum
98  * IPv4 header size is 60 bytes and the base IPv4 header is 20 bytes long. */
99 #define CIPSO_V4_OPT_LEN_MAX          40
100
101 /* Length of the base CIPSO option, this includes the option type (1 byte), the
102  * option length (1 byte), and the DOI (4 bytes). */
103 #define CIPSO_V4_HDR_LEN              6
104
105 /* Base length of the restrictive category bitmap tag (tag #1). */
106 #define CIPSO_V4_TAG_RBM_BLEN         4
107
108 /* Base length of the enumerated category tag (tag #2). */
109 #define CIPSO_V4_TAG_ENUM_BLEN        4
110
111 /* Base length of the ranged categories bitmap tag (tag #5). */
112 #define CIPSO_V4_TAG_RNG_BLEN         4
113 /* The maximum number of category ranges permitted in the ranged category tag
114  * (tag #5).  You may note that the IETF draft states that the maximum number
115  * of category ranges is 7, but if the low end of the last category range is
116  * zero then it is possible to fit 8 category ranges because the zero should
117  * be omitted. */
118 #define CIPSO_V4_TAG_RNG_CAT_MAX      8
119
120 /* Base length of the local tag (non-standard tag).
121  *  Tag definition (may change between kernel versions)
122  *
123  * 0          8          16         24         32
124  * +----------+----------+----------+----------+
125  * | 10000000 | 00000110 | 32-bit secid value  |
126  * +----------+----------+----------+----------+
127  * | in (host byte order)|
128  * +----------+----------+
129  *
130  */
131 #define CIPSO_V4_TAG_LOC_BLEN         6
132
133 /*
134  * Helper Functions
135  */
136
137 /**
138  * cipso_v4_cache_entry_free - Frees a cache entry
139  * @entry: the entry to free
140  *
141  * Description:
142  * This function frees the memory associated with a cache entry including the
143  * LSM cache data if there are no longer any users, i.e. reference count == 0.
144  *
145  */
146 static void cipso_v4_cache_entry_free(struct cipso_v4_map_cache_entry *entry)
147 {
148         if (entry->lsm_data)
149                 netlbl_secattr_cache_free(entry->lsm_data);
150         kfree(entry->key);
151         kfree(entry);
152 }
153
154 /**
155  * cipso_v4_map_cache_hash - Hashing function for the CIPSO cache
156  * @key: the hash key
157  * @key_len: the length of the key in bytes
158  *
159  * Description:
160  * The CIPSO tag hashing function.  Returns a 32-bit hash value.
161  *
162  */
163 static u32 cipso_v4_map_cache_hash(const unsigned char *key, u32 key_len)
164 {
165         return jhash(key, key_len, 0);
166 }
167
168 /*
169  * Label Mapping Cache Functions
170  */
171
172 /**
173  * cipso_v4_cache_init - Initialize the CIPSO cache
174  *
175  * Description:
176  * Initializes the CIPSO label mapping cache, this function should be called
177  * before any of the other functions defined in this file.  Returns zero on
178  * success, negative values on error.
179  *
180  */
181 static int __init cipso_v4_cache_init(void)
182 {
183         u32 iter;
184
185         cipso_v4_cache = kcalloc(CIPSO_V4_CACHE_BUCKETS,
186                                  sizeof(struct cipso_v4_map_cache_bkt),
187                                  GFP_KERNEL);
188         if (!cipso_v4_cache)
189                 return -ENOMEM;
190
191         for (iter = 0; iter < CIPSO_V4_CACHE_BUCKETS; iter++) {
192                 spin_lock_init(&cipso_v4_cache[iter].lock);
193                 cipso_v4_cache[iter].size = 0;
194                 INIT_LIST_HEAD(&cipso_v4_cache[iter].list);
195         }
196
197         return 0;
198 }
199
200 /**
201  * cipso_v4_cache_invalidate - Invalidates the current CIPSO cache
202  *
203  * Description:
204  * Invalidates and frees any entries in the CIPSO cache.  Returns zero on
205  * success and negative values on failure.
206  *
207  */
208 void cipso_v4_cache_invalidate(void)
209 {
210         struct cipso_v4_map_cache_entry *entry, *tmp_entry;
211         u32 iter;
212
213         for (iter = 0; iter < CIPSO_V4_CACHE_BUCKETS; iter++) {
214                 spin_lock_bh(&cipso_v4_cache[iter].lock);
215                 list_for_each_entry_safe(entry,
216                                          tmp_entry,
217                                          &cipso_v4_cache[iter].list, list) {
218                         list_del(&entry->list);
219                         cipso_v4_cache_entry_free(entry);
220                 }
221                 cipso_v4_cache[iter].size = 0;
222                 spin_unlock_bh(&cipso_v4_cache[iter].lock);
223         }
224 }
225
226 /**
227  * cipso_v4_cache_check - Check the CIPSO cache for a label mapping
228  * @key: the buffer to check
229  * @key_len: buffer length in bytes
230  * @secattr: the security attribute struct to use
231  *
232  * Description:
233  * This function checks the cache to see if a label mapping already exists for
234  * the given key.  If there is a match then the cache is adjusted and the
235  * @secattr struct is populated with the correct LSM security attributes.  The
236  * cache is adjusted in the following manner if the entry is not already the
237  * first in the cache bucket:
238  *
239  *  1. The cache entry's activity counter is incremented
240  *  2. The previous (higher ranking) entry's activity counter is decremented
241  *  3. If the difference between the two activity counters is geater than
242  *     CIPSO_V4_CACHE_REORDERLIMIT the two entries are swapped
243  *
244  * Returns zero on success, -ENOENT for a cache miss, and other negative values
245  * on error.
246  *
247  */
248 static int cipso_v4_cache_check(const unsigned char *key,
249                                 u32 key_len,
250                                 struct netlbl_lsm_secattr *secattr)
251 {
252         u32 bkt;
253         struct cipso_v4_map_cache_entry *entry;
254         struct cipso_v4_map_cache_entry *prev_entry = NULL;
255         u32 hash;
256
257         if (!cipso_v4_cache_enabled)
258                 return -ENOENT;
259
260         hash = cipso_v4_map_cache_hash(key, key_len);
261         bkt = hash & (CIPSO_V4_CACHE_BUCKETS - 1);
262         spin_lock_bh(&cipso_v4_cache[bkt].lock);
263         list_for_each_entry(entry, &cipso_v4_cache[bkt].list, list) {
264                 if (entry->hash == hash &&
265                     entry->key_len == key_len &&
266                     memcmp(entry->key, key, key_len) == 0) {
267                         entry->activity += 1;
268                         atomic_inc(&entry->lsm_data->refcount);
269                         secattr->cache = entry->lsm_data;
270                         secattr->flags |= NETLBL_SECATTR_CACHE;
271                         secattr->type = NETLBL_NLTYPE_CIPSOV4;
272                         if (!prev_entry) {
273                                 spin_unlock_bh(&cipso_v4_cache[bkt].lock);
274                                 return 0;
275                         }
276
277                         if (prev_entry->activity > 0)
278                                 prev_entry->activity -= 1;
279                         if (entry->activity > prev_entry->activity &&
280                             entry->activity - prev_entry->activity >
281                             CIPSO_V4_CACHE_REORDERLIMIT) {
282                                 __list_del(entry->list.prev, entry->list.next);
283                                 __list_add(&entry->list,
284                                            prev_entry->list.prev,
285                                            &prev_entry->list);
286                         }
287
288                         spin_unlock_bh(&cipso_v4_cache[bkt].lock);
289                         return 0;
290                 }
291                 prev_entry = entry;
292         }
293         spin_unlock_bh(&cipso_v4_cache[bkt].lock);
294
295         return -ENOENT;
296 }
297
298 /**
299  * cipso_v4_cache_add - Add an entry to the CIPSO cache
300  * @skb: the packet
301  * @secattr: the packet's security attributes
302  *
303  * Description:
304  * Add a new entry into the CIPSO label mapping cache.  Add the new entry to
305  * head of the cache bucket's list, if the cache bucket is out of room remove
306  * the last entry in the list first.  It is important to note that there is
307  * currently no checking for duplicate keys.  Returns zero on success,
308  * negative values on failure.
309  *
310  */
311 int cipso_v4_cache_add(const unsigned char *cipso_ptr,
312                        const struct netlbl_lsm_secattr *secattr)
313 {
314         int ret_val = -EPERM;
315         u32 bkt;
316         struct cipso_v4_map_cache_entry *entry = NULL;
317         struct cipso_v4_map_cache_entry *old_entry = NULL;
318         u32 cipso_ptr_len;
319
320         if (!cipso_v4_cache_enabled || cipso_v4_cache_bucketsize <= 0)
321                 return 0;
322
323         cipso_ptr_len = cipso_ptr[1];
324
325         entry = kzalloc(sizeof(*entry), GFP_ATOMIC);
326         if (!entry)
327                 return -ENOMEM;
328         entry->key = kmemdup(cipso_ptr, cipso_ptr_len, GFP_ATOMIC);
329         if (!entry->key) {
330                 ret_val = -ENOMEM;
331                 goto cache_add_failure;
332         }
333         entry->key_len = cipso_ptr_len;
334         entry->hash = cipso_v4_map_cache_hash(cipso_ptr, cipso_ptr_len);
335         atomic_inc(&secattr->cache->refcount);
336         entry->lsm_data = secattr->cache;
337
338         bkt = entry->hash & (CIPSO_V4_CACHE_BUCKETS - 1);
339         spin_lock_bh(&cipso_v4_cache[bkt].lock);
340         if (cipso_v4_cache[bkt].size < cipso_v4_cache_bucketsize) {
341                 list_add(&entry->list, &cipso_v4_cache[bkt].list);
342                 cipso_v4_cache[bkt].size += 1;
343         } else {
344                 old_entry = list_entry(cipso_v4_cache[bkt].list.prev,
345                                        struct cipso_v4_map_cache_entry, list);
346                 list_del(&old_entry->list);
347                 list_add(&entry->list, &cipso_v4_cache[bkt].list);
348                 cipso_v4_cache_entry_free(old_entry);
349         }
350         spin_unlock_bh(&cipso_v4_cache[bkt].lock);
351
352         return 0;
353
354 cache_add_failure:
355         if (entry)
356                 cipso_v4_cache_entry_free(entry);
357         return ret_val;
358 }
359
360 /*
361  * DOI List Functions
362  */
363
364 /**
365  * cipso_v4_doi_search - Searches for a DOI definition
366  * @doi: the DOI to search for
367  *
368  * Description:
369  * Search the DOI definition list for a DOI definition with a DOI value that
370  * matches @doi.  The caller is responsible for calling rcu_read_[un]lock().
371  * Returns a pointer to the DOI definition on success and NULL on failure.
372  */
373 static struct cipso_v4_doi *cipso_v4_doi_search(u32 doi)
374 {
375         struct cipso_v4_doi *iter;
376
377         list_for_each_entry_rcu(iter, &cipso_v4_doi_list, list)
378                 if (iter->doi == doi && atomic_read(&iter->refcount))
379                         return iter;
380         return NULL;
381 }
382
383 /**
384  * cipso_v4_doi_add - Add a new DOI to the CIPSO protocol engine
385  * @doi_def: the DOI structure
386  * @audit_info: NetLabel audit information
387  *
388  * Description:
389  * The caller defines a new DOI for use by the CIPSO engine and calls this
390  * function to add it to the list of acceptable domains.  The caller must
391  * ensure that the mapping table specified in @doi_def->map meets all of the
392  * requirements of the mapping type (see cipso_ipv4.h for details).  Returns
393  * zero on success and non-zero on failure.
394  *
395  */
396 int cipso_v4_doi_add(struct cipso_v4_doi *doi_def,
397                      struct netlbl_audit *audit_info)
398 {
399         int ret_val = -EINVAL;
400         u32 iter;
401         u32 doi;
402         u32 doi_type;
403         struct audit_buffer *audit_buf;
404
405         doi = doi_def->doi;
406         doi_type = doi_def->type;
407
408         if (doi_def->doi == CIPSO_V4_DOI_UNKNOWN)
409                 goto doi_add_return;
410         for (iter = 0; iter < CIPSO_V4_TAG_MAXCNT; iter++) {
411                 switch (doi_def->tags[iter]) {
412                 case CIPSO_V4_TAG_RBITMAP:
413                         break;
414                 case CIPSO_V4_TAG_RANGE:
415                 case CIPSO_V4_TAG_ENUM:
416                         if (doi_def->type != CIPSO_V4_MAP_PASS)
417                                 goto doi_add_return;
418                         break;
419                 case CIPSO_V4_TAG_LOCAL:
420                         if (doi_def->type != CIPSO_V4_MAP_LOCAL)
421                                 goto doi_add_return;
422                         break;
423                 case CIPSO_V4_TAG_INVALID:
424                         if (iter == 0)
425                                 goto doi_add_return;
426                         break;
427                 default:
428                         goto doi_add_return;
429                 }
430         }
431
432         atomic_set(&doi_def->refcount, 1);
433
434         spin_lock(&cipso_v4_doi_list_lock);
435         if (cipso_v4_doi_search(doi_def->doi)) {
436                 spin_unlock(&cipso_v4_doi_list_lock);
437                 ret_val = -EEXIST;
438                 goto doi_add_return;
439         }
440         list_add_tail_rcu(&doi_def->list, &cipso_v4_doi_list);
441         spin_unlock(&cipso_v4_doi_list_lock);
442         ret_val = 0;
443
444 doi_add_return:
445         audit_buf = netlbl_audit_start(AUDIT_MAC_CIPSOV4_ADD, audit_info);
446         if (audit_buf) {
447                 const char *type_str;
448                 switch (doi_type) {
449                 case CIPSO_V4_MAP_TRANS:
450                         type_str = "trans";
451                         break;
452                 case CIPSO_V4_MAP_PASS:
453                         type_str = "pass";
454                         break;
455                 case CIPSO_V4_MAP_LOCAL:
456                         type_str = "local";
457                         break;
458                 default:
459                         type_str = "(unknown)";
460                 }
461                 audit_log_format(audit_buf,
462                                  " cipso_doi=%u cipso_type=%s res=%u",
463                                  doi, type_str, ret_val == 0 ? 1 : 0);
464                 audit_log_end(audit_buf);
465         }
466
467         return ret_val;
468 }
469
470 /**
471  * cipso_v4_doi_free - Frees a DOI definition
472  * @doi_def: the DOI definition
473  *
474  * Description:
475  * This function frees all of the memory associated with a DOI definition.
476  *
477  */
478 void cipso_v4_doi_free(struct cipso_v4_doi *doi_def)
479 {
480         if (!doi_def)
481                 return;
482
483         switch (doi_def->type) {
484         case CIPSO_V4_MAP_TRANS:
485                 kfree(doi_def->map.std->lvl.cipso);
486                 kfree(doi_def->map.std->lvl.local);
487                 kfree(doi_def->map.std->cat.cipso);
488                 kfree(doi_def->map.std->cat.local);
489                 kfree(doi_def->map.std);
490                 break;
491         }
492         kfree(doi_def);
493 }
494
495 /**
496  * cipso_v4_doi_free_rcu - Frees a DOI definition via the RCU pointer
497  * @entry: the entry's RCU field
498  *
499  * Description:
500  * This function is designed to be used as a callback to the call_rcu()
501  * function so that the memory allocated to the DOI definition can be released
502  * safely.
503  *
504  */
505 static void cipso_v4_doi_free_rcu(struct rcu_head *entry)
506 {
507         struct cipso_v4_doi *doi_def;
508
509         doi_def = container_of(entry, struct cipso_v4_doi, rcu);
510         cipso_v4_doi_free(doi_def);
511 }
512
513 /**
514  * cipso_v4_doi_remove - Remove an existing DOI from the CIPSO protocol engine
515  * @doi: the DOI value
516  * @audit_secid: the LSM secid to use in the audit message
517  *
518  * Description:
519  * Removes a DOI definition from the CIPSO engine.  The NetLabel routines will
520  * be called to release their own LSM domain mappings as well as our own
521  * domain list.  Returns zero on success and negative values on failure.
522  *
523  */
524 int cipso_v4_doi_remove(u32 doi, struct netlbl_audit *audit_info)
525 {
526         int ret_val;
527         struct cipso_v4_doi *doi_def;
528         struct audit_buffer *audit_buf;
529
530         spin_lock(&cipso_v4_doi_list_lock);
531         doi_def = cipso_v4_doi_search(doi);
532         if (!doi_def) {
533                 spin_unlock(&cipso_v4_doi_list_lock);
534                 ret_val = -ENOENT;
535                 goto doi_remove_return;
536         }
537         if (!atomic_dec_and_test(&doi_def->refcount)) {
538                 spin_unlock(&cipso_v4_doi_list_lock);
539                 ret_val = -EBUSY;
540                 goto doi_remove_return;
541         }
542         list_del_rcu(&doi_def->list);
543         spin_unlock(&cipso_v4_doi_list_lock);
544
545         cipso_v4_cache_invalidate();
546         call_rcu(&doi_def->rcu, cipso_v4_doi_free_rcu);
547         ret_val = 0;
548
549 doi_remove_return:
550         audit_buf = netlbl_audit_start(AUDIT_MAC_CIPSOV4_DEL, audit_info);
551         if (audit_buf) {
552                 audit_log_format(audit_buf,
553                                  " cipso_doi=%u res=%u",
554                                  doi, ret_val == 0 ? 1 : 0);
555                 audit_log_end(audit_buf);
556         }
557
558         return ret_val;
559 }
560
561 /**
562  * cipso_v4_doi_getdef - Returns a reference to a valid DOI definition
563  * @doi: the DOI value
564  *
565  * Description:
566  * Searches for a valid DOI definition and if one is found it is returned to
567  * the caller.  Otherwise NULL is returned.  The caller must ensure that
568  * rcu_read_lock() is held while accessing the returned definition and the DOI
569  * definition reference count is decremented when the caller is done.
570  *
571  */
572 struct cipso_v4_doi *cipso_v4_doi_getdef(u32 doi)
573 {
574         struct cipso_v4_doi *doi_def;
575
576         rcu_read_lock();
577         doi_def = cipso_v4_doi_search(doi);
578         if (!doi_def)
579                 goto doi_getdef_return;
580         if (!atomic_inc_not_zero(&doi_def->refcount))
581                 doi_def = NULL;
582
583 doi_getdef_return:
584         rcu_read_unlock();
585         return doi_def;
586 }
587
588 /**
589  * cipso_v4_doi_putdef - Releases a reference for the given DOI definition
590  * @doi_def: the DOI definition
591  *
592  * Description:
593  * Releases a DOI definition reference obtained from cipso_v4_doi_getdef().
594  *
595  */
596 void cipso_v4_doi_putdef(struct cipso_v4_doi *doi_def)
597 {
598         if (!doi_def)
599                 return;
600
601         if (!atomic_dec_and_test(&doi_def->refcount))
602                 return;
603         spin_lock(&cipso_v4_doi_list_lock);
604         list_del_rcu(&doi_def->list);
605         spin_unlock(&cipso_v4_doi_list_lock);
606
607         cipso_v4_cache_invalidate();
608         call_rcu(&doi_def->rcu, cipso_v4_doi_free_rcu);
609 }
610
611 /**
612  * cipso_v4_doi_walk - Iterate through the DOI definitions
613  * @skip_cnt: skip past this number of DOI definitions, updated
614  * @callback: callback for each DOI definition
615  * @cb_arg: argument for the callback function
616  *
617  * Description:
618  * Iterate over the DOI definition list, skipping the first @skip_cnt entries.
619  * For each entry call @callback, if @callback returns a negative value stop
620  * 'walking' through the list and return.  Updates the value in @skip_cnt upon
621  * return.  Returns zero on success, negative values on failure.
622  *
623  */
624 int cipso_v4_doi_walk(u32 *skip_cnt,
625                      int (*callback) (struct cipso_v4_doi *doi_def, void *arg),
626                      void *cb_arg)
627 {
628         int ret_val = -ENOENT;
629         u32 doi_cnt = 0;
630         struct cipso_v4_doi *iter_doi;
631
632         rcu_read_lock();
633         list_for_each_entry_rcu(iter_doi, &cipso_v4_doi_list, list)
634                 if (atomic_read(&iter_doi->refcount) > 0) {
635                         if (doi_cnt++ < *skip_cnt)
636                                 continue;
637                         ret_val = callback(iter_doi, cb_arg);
638                         if (ret_val < 0) {
639                                 doi_cnt--;
640                                 goto doi_walk_return;
641                         }
642                 }
643
644 doi_walk_return:
645         rcu_read_unlock();
646         *skip_cnt = doi_cnt;
647         return ret_val;
648 }
649
650 /*
651  * Label Mapping Functions
652  */
653
654 /**
655  * cipso_v4_map_lvl_valid - Checks to see if the given level is understood
656  * @doi_def: the DOI definition
657  * @level: the level to check
658  *
659  * Description:
660  * Checks the given level against the given DOI definition and returns a
661  * negative value if the level does not have a valid mapping and a zero value
662  * if the level is defined by the DOI.
663  *
664  */
665 static int cipso_v4_map_lvl_valid(const struct cipso_v4_doi *doi_def, u8 level)
666 {
667         switch (doi_def->type) {
668         case CIPSO_V4_MAP_PASS:
669                 return 0;
670         case CIPSO_V4_MAP_TRANS:
671                 if ((level < doi_def->map.std->lvl.cipso_size) &&
672                     (doi_def->map.std->lvl.cipso[level] < CIPSO_V4_INV_LVL))
673                         return 0;
674                 break;
675         }
676
677         return -EFAULT;
678 }
679
680 /**
681  * cipso_v4_map_lvl_hton - Perform a level mapping from the host to the network
682  * @doi_def: the DOI definition
683  * @host_lvl: the host MLS level
684  * @net_lvl: the network/CIPSO MLS level
685  *
686  * Description:
687  * Perform a label mapping to translate a local MLS level to the correct
688  * CIPSO level using the given DOI definition.  Returns zero on success,
689  * negative values otherwise.
690  *
691  */
692 static int cipso_v4_map_lvl_hton(const struct cipso_v4_doi *doi_def,
693                                  u32 host_lvl,
694                                  u32 *net_lvl)
695 {
696         switch (doi_def->type) {
697         case CIPSO_V4_MAP_PASS:
698                 *net_lvl = host_lvl;
699                 return 0;
700         case CIPSO_V4_MAP_TRANS:
701                 if (host_lvl < doi_def->map.std->lvl.local_size &&
702                     doi_def->map.std->lvl.local[host_lvl] < CIPSO_V4_INV_LVL) {
703                         *net_lvl = doi_def->map.std->lvl.local[host_lvl];
704                         return 0;
705                 }
706                 return -EPERM;
707         }
708
709         return -EINVAL;
710 }
711
712 /**
713  * cipso_v4_map_lvl_ntoh - Perform a level mapping from the network to the host
714  * @doi_def: the DOI definition
715  * @net_lvl: the network/CIPSO MLS level
716  * @host_lvl: the host MLS level
717  *
718  * Description:
719  * Perform a label mapping to translate a CIPSO level to the correct local MLS
720  * level using the given DOI definition.  Returns zero on success, negative
721  * values otherwise.
722  *
723  */
724 static int cipso_v4_map_lvl_ntoh(const struct cipso_v4_doi *doi_def,
725                                  u32 net_lvl,
726                                  u32 *host_lvl)
727 {
728         struct cipso_v4_std_map_tbl *map_tbl;
729
730         switch (doi_def->type) {
731         case CIPSO_V4_MAP_PASS:
732                 *host_lvl = net_lvl;
733                 return 0;
734         case CIPSO_V4_MAP_TRANS:
735                 map_tbl = doi_def->map.std;
736                 if (net_lvl < map_tbl->lvl.cipso_size &&
737                     map_tbl->lvl.cipso[net_lvl] < CIPSO_V4_INV_LVL) {
738                         *host_lvl = doi_def->map.std->lvl.cipso[net_lvl];
739                         return 0;
740                 }
741                 return -EPERM;
742         }
743
744         return -EINVAL;
745 }
746
747 /**
748  * cipso_v4_map_cat_rbm_valid - Checks to see if the category bitmap is valid
749  * @doi_def: the DOI definition
750  * @bitmap: category bitmap
751  * @bitmap_len: bitmap length in bytes
752  *
753  * Description:
754  * Checks the given category bitmap against the given DOI definition and
755  * returns a negative value if any of the categories in the bitmap do not have
756  * a valid mapping and a zero value if all of the categories are valid.
757  *
758  */
759 static int cipso_v4_map_cat_rbm_valid(const struct cipso_v4_doi *doi_def,
760                                       const unsigned char *bitmap,
761                                       u32 bitmap_len)
762 {
763         int cat = -1;
764         u32 bitmap_len_bits = bitmap_len * 8;
765         u32 cipso_cat_size;
766         u32 *cipso_array;
767
768         switch (doi_def->type) {
769         case CIPSO_V4_MAP_PASS:
770                 return 0;
771         case CIPSO_V4_MAP_TRANS:
772                 cipso_cat_size = doi_def->map.std->cat.cipso_size;
773                 cipso_array = doi_def->map.std->cat.cipso;
774                 for (;;) {
775                         cat = netlbl_bitmap_walk(bitmap,
776                                                  bitmap_len_bits,
777                                                  cat + 1,
778                                                  1);
779                         if (cat < 0)
780                                 break;
781                         if (cat >= cipso_cat_size ||
782                             cipso_array[cat] >= CIPSO_V4_INV_CAT)
783                                 return -EFAULT;
784                 }
785
786                 if (cat == -1)
787                         return 0;
788                 break;
789         }
790
791         return -EFAULT;
792 }
793
794 /**
795  * cipso_v4_map_cat_rbm_hton - Perform a category mapping from host to network
796  * @doi_def: the DOI definition
797  * @secattr: the security attributes
798  * @net_cat: the zero'd out category bitmap in network/CIPSO format
799  * @net_cat_len: the length of the CIPSO bitmap in bytes
800  *
801  * Description:
802  * Perform a label mapping to translate a local MLS category bitmap to the
803  * correct CIPSO bitmap using the given DOI definition.  Returns the minimum
804  * size in bytes of the network bitmap on success, negative values otherwise.
805  *
806  */
807 static int cipso_v4_map_cat_rbm_hton(const struct cipso_v4_doi *doi_def,
808                                      const struct netlbl_lsm_secattr *secattr,
809                                      unsigned char *net_cat,
810                                      u32 net_cat_len)
811 {
812         int host_spot = -1;
813         u32 net_spot = CIPSO_V4_INV_CAT;
814         u32 net_spot_max = 0;
815         u32 net_clen_bits = net_cat_len * 8;
816         u32 host_cat_size = 0;
817         u32 *host_cat_array = NULL;
818
819         if (doi_def->type == CIPSO_V4_MAP_TRANS) {
820                 host_cat_size = doi_def->map.std->cat.local_size;
821                 host_cat_array = doi_def->map.std->cat.local;
822         }
823
824         for (;;) {
825                 host_spot = netlbl_catmap_walk(secattr->attr.mls.cat,
826                                                host_spot + 1);
827                 if (host_spot < 0)
828                         break;
829
830                 switch (doi_def->type) {
831                 case CIPSO_V4_MAP_PASS:
832                         net_spot = host_spot;
833                         break;
834                 case CIPSO_V4_MAP_TRANS:
835                         if (host_spot >= host_cat_size)
836                                 return -EPERM;
837                         net_spot = host_cat_array[host_spot];
838                         if (net_spot >= CIPSO_V4_INV_CAT)
839                                 return -EPERM;
840                         break;
841                 }
842                 if (net_spot >= net_clen_bits)
843                         return -ENOSPC;
844                 netlbl_bitmap_setbit(net_cat, net_spot, 1);
845
846                 if (net_spot > net_spot_max)
847                         net_spot_max = net_spot;
848         }
849
850         if (++net_spot_max % 8)
851                 return net_spot_max / 8 + 1;
852         return net_spot_max / 8;
853 }
854
855 /**
856  * cipso_v4_map_cat_rbm_ntoh - Perform a category mapping from network to host
857  * @doi_def: the DOI definition
858  * @net_cat: the category bitmap in network/CIPSO format
859  * @net_cat_len: the length of the CIPSO bitmap in bytes
860  * @secattr: the security attributes
861  *
862  * Description:
863  * Perform a label mapping to translate a CIPSO bitmap to the correct local
864  * MLS category bitmap using the given DOI definition.  Returns zero on
865  * success, negative values on failure.
866  *
867  */
868 static int cipso_v4_map_cat_rbm_ntoh(const struct cipso_v4_doi *doi_def,
869                                      const unsigned char *net_cat,
870                                      u32 net_cat_len,
871                                      struct netlbl_lsm_secattr *secattr)
872 {
873         int ret_val;
874         int net_spot = -1;
875         u32 host_spot = CIPSO_V4_INV_CAT;
876         u32 net_clen_bits = net_cat_len * 8;
877         u32 net_cat_size = 0;
878         u32 *net_cat_array = NULL;
879
880         if (doi_def->type == CIPSO_V4_MAP_TRANS) {
881                 net_cat_size = doi_def->map.std->cat.cipso_size;
882                 net_cat_array = doi_def->map.std->cat.cipso;
883         }
884
885         for (;;) {
886                 net_spot = netlbl_bitmap_walk(net_cat,
887                                               net_clen_bits,
888                                               net_spot + 1,
889                                               1);
890                 if (net_spot < 0) {
891                         if (net_spot == -2)
892                                 return -EFAULT;
893                         return 0;
894                 }
895
896                 switch (doi_def->type) {
897                 case CIPSO_V4_MAP_PASS:
898                         host_spot = net_spot;
899                         break;
900                 case CIPSO_V4_MAP_TRANS:
901                         if (net_spot >= net_cat_size)
902                                 return -EPERM;
903                         host_spot = net_cat_array[net_spot];
904                         if (host_spot >= CIPSO_V4_INV_CAT)
905                                 return -EPERM;
906                         break;
907                 }
908                 ret_val = netlbl_catmap_setbit(&secattr->attr.mls.cat,
909                                                        host_spot,
910                                                        GFP_ATOMIC);
911                 if (ret_val != 0)
912                         return ret_val;
913         }
914
915         return -EINVAL;
916 }
917
918 /**
919  * cipso_v4_map_cat_enum_valid - Checks to see if the categories are valid
920  * @doi_def: the DOI definition
921  * @enumcat: category list
922  * @enumcat_len: length of the category list in bytes
923  *
924  * Description:
925  * Checks the given categories against the given DOI definition and returns a
926  * negative value if any of the categories do not have a valid mapping and a
927  * zero value if all of the categories are valid.
928  *
929  */
930 static int cipso_v4_map_cat_enum_valid(const struct cipso_v4_doi *doi_def,
931                                        const unsigned char *enumcat,
932                                        u32 enumcat_len)
933 {
934         u16 cat;
935         int cat_prev = -1;
936         u32 iter;
937
938         if (doi_def->type != CIPSO_V4_MAP_PASS || enumcat_len & 0x01)
939                 return -EFAULT;
940
941         for (iter = 0; iter < enumcat_len; iter += 2) {
942                 cat = get_unaligned_be16(&enumcat[iter]);
943                 if (cat <= cat_prev)
944                         return -EFAULT;
945                 cat_prev = cat;
946         }
947
948         return 0;
949 }
950
951 /**
952  * cipso_v4_map_cat_enum_hton - Perform a category mapping from host to network
953  * @doi_def: the DOI definition
954  * @secattr: the security attributes
955  * @net_cat: the zero'd out category list in network/CIPSO format
956  * @net_cat_len: the length of the CIPSO category list in bytes
957  *
958  * Description:
959  * Perform a label mapping to translate a local MLS category bitmap to the
960  * correct CIPSO category list using the given DOI definition.   Returns the
961  * size in bytes of the network category bitmap on success, negative values
962  * otherwise.
963  *
964  */
965 static int cipso_v4_map_cat_enum_hton(const struct cipso_v4_doi *doi_def,
966                                       const struct netlbl_lsm_secattr *secattr,
967                                       unsigned char *net_cat,
968                                       u32 net_cat_len)
969 {
970         int cat = -1;
971         u32 cat_iter = 0;
972
973         for (;;) {
974                 cat = netlbl_catmap_walk(secattr->attr.mls.cat, cat + 1);
975                 if (cat < 0)
976                         break;
977                 if ((cat_iter + 2) > net_cat_len)
978                         return -ENOSPC;
979
980                 *((__be16 *)&net_cat[cat_iter]) = htons(cat);
981                 cat_iter += 2;
982         }
983
984         return cat_iter;
985 }
986
987 /**
988  * cipso_v4_map_cat_enum_ntoh - Perform a category mapping from network to host
989  * @doi_def: the DOI definition
990  * @net_cat: the category list in network/CIPSO format
991  * @net_cat_len: the length of the CIPSO bitmap in bytes
992  * @secattr: the security attributes
993  *
994  * Description:
995  * Perform a label mapping to translate a CIPSO category list to the correct
996  * local MLS category bitmap using the given DOI definition.  Returns zero on
997  * success, negative values on failure.
998  *
999  */
1000 static int cipso_v4_map_cat_enum_ntoh(const struct cipso_v4_doi *doi_def,
1001                                       const unsigned char *net_cat,
1002                                       u32 net_cat_len,
1003                                       struct netlbl_lsm_secattr *secattr)
1004 {
1005         int ret_val;
1006         u32 iter;
1007
1008         for (iter = 0; iter < net_cat_len; iter += 2) {
1009                 ret_val = netlbl_catmap_setbit(&secattr->attr.mls.cat,
1010                                              get_unaligned_be16(&net_cat[iter]),
1011                                              GFP_ATOMIC);
1012                 if (ret_val != 0)
1013                         return ret_val;
1014         }
1015
1016         return 0;
1017 }
1018
1019 /**
1020  * cipso_v4_map_cat_rng_valid - Checks to see if the categories are valid
1021  * @doi_def: the DOI definition
1022  * @rngcat: category list
1023  * @rngcat_len: length of the category list in bytes
1024  *
1025  * Description:
1026  * Checks the given categories against the given DOI definition and returns a
1027  * negative value if any of the categories do not have a valid mapping and a
1028  * zero value if all of the categories are valid.
1029  *
1030  */
1031 static int cipso_v4_map_cat_rng_valid(const struct cipso_v4_doi *doi_def,
1032                                       const unsigned char *rngcat,
1033                                       u32 rngcat_len)
1034 {
1035         u16 cat_high;
1036         u16 cat_low;
1037         u32 cat_prev = CIPSO_V4_MAX_REM_CATS + 1;
1038         u32 iter;
1039
1040         if (doi_def->type != CIPSO_V4_MAP_PASS || rngcat_len & 0x01)
1041                 return -EFAULT;
1042
1043         for (iter = 0; iter < rngcat_len; iter += 4) {
1044                 cat_high = get_unaligned_be16(&rngcat[iter]);
1045                 if ((iter + 4) <= rngcat_len)
1046                         cat_low = get_unaligned_be16(&rngcat[iter + 2]);
1047                 else
1048                         cat_low = 0;
1049
1050                 if (cat_high > cat_prev)
1051                         return -EFAULT;
1052
1053                 cat_prev = cat_low;
1054         }
1055
1056         return 0;
1057 }
1058
1059 /**
1060  * cipso_v4_map_cat_rng_hton - Perform a category mapping from host to network
1061  * @doi_def: the DOI definition
1062  * @secattr: the security attributes
1063  * @net_cat: the zero'd out category list in network/CIPSO format
1064  * @net_cat_len: the length of the CIPSO category list in bytes
1065  *
1066  * Description:
1067  * Perform a label mapping to translate a local MLS category bitmap to the
1068  * correct CIPSO category list using the given DOI definition.   Returns the
1069  * size in bytes of the network category bitmap on success, negative values
1070  * otherwise.
1071  *
1072  */
1073 static int cipso_v4_map_cat_rng_hton(const struct cipso_v4_doi *doi_def,
1074                                      const struct netlbl_lsm_secattr *secattr,
1075                                      unsigned char *net_cat,
1076                                      u32 net_cat_len)
1077 {
1078         int iter = -1;
1079         u16 array[CIPSO_V4_TAG_RNG_CAT_MAX * 2];
1080         u32 array_cnt = 0;
1081         u32 cat_size = 0;
1082
1083         /* make sure we don't overflow the 'array[]' variable */
1084         if (net_cat_len >
1085             (CIPSO_V4_OPT_LEN_MAX - CIPSO_V4_HDR_LEN - CIPSO_V4_TAG_RNG_BLEN))
1086                 return -ENOSPC;
1087
1088         for (;;) {
1089                 iter = netlbl_catmap_walk(secattr->attr.mls.cat, iter + 1);
1090                 if (iter < 0)
1091                         break;
1092                 cat_size += (iter == 0 ? 0 : sizeof(u16));
1093                 if (cat_size > net_cat_len)
1094                         return -ENOSPC;
1095                 array[array_cnt++] = iter;
1096
1097                 iter = netlbl_catmap_walkrng(secattr->attr.mls.cat, iter);
1098                 if (iter < 0)
1099                         return -EFAULT;
1100                 cat_size += sizeof(u16);
1101                 if (cat_size > net_cat_len)
1102                         return -ENOSPC;
1103                 array[array_cnt++] = iter;
1104         }
1105
1106         for (iter = 0; array_cnt > 0;) {
1107                 *((__be16 *)&net_cat[iter]) = htons(array[--array_cnt]);
1108                 iter += 2;
1109                 array_cnt--;
1110                 if (array[array_cnt] != 0) {
1111                         *((__be16 *)&net_cat[iter]) = htons(array[array_cnt]);
1112                         iter += 2;
1113                 }
1114         }
1115
1116         return cat_size;
1117 }
1118
1119 /**
1120  * cipso_v4_map_cat_rng_ntoh - Perform a category mapping from network to host
1121  * @doi_def: the DOI definition
1122  * @net_cat: the category list in network/CIPSO format
1123  * @net_cat_len: the length of the CIPSO bitmap in bytes
1124  * @secattr: the security attributes
1125  *
1126  * Description:
1127  * Perform a label mapping to translate a CIPSO category list to the correct
1128  * local MLS category bitmap using the given DOI definition.  Returns zero on
1129  * success, negative values on failure.
1130  *
1131  */
1132 static int cipso_v4_map_cat_rng_ntoh(const struct cipso_v4_doi *doi_def,
1133                                      const unsigned char *net_cat,
1134                                      u32 net_cat_len,
1135                                      struct netlbl_lsm_secattr *secattr)
1136 {
1137         int ret_val;
1138         u32 net_iter;
1139         u16 cat_low;
1140         u16 cat_high;
1141
1142         for (net_iter = 0; net_iter < net_cat_len; net_iter += 4) {
1143                 cat_high = get_unaligned_be16(&net_cat[net_iter]);
1144                 if ((net_iter + 4) <= net_cat_len)
1145                         cat_low = get_unaligned_be16(&net_cat[net_iter + 2]);
1146                 else
1147                         cat_low = 0;
1148
1149                 ret_val = netlbl_catmap_setrng(&secattr->attr.mls.cat,
1150                                                cat_low,
1151                                                cat_high,
1152                                                GFP_ATOMIC);
1153                 if (ret_val != 0)
1154                         return ret_val;
1155         }
1156
1157         return 0;
1158 }
1159
1160 /*
1161  * Protocol Handling Functions
1162  */
1163
1164 /**
1165  * cipso_v4_gentag_hdr - Generate a CIPSO option header
1166  * @doi_def: the DOI definition
1167  * @len: the total tag length in bytes, not including this header
1168  * @buf: the CIPSO option buffer
1169  *
1170  * Description:
1171  * Write a CIPSO header into the beginning of @buffer.
1172  *
1173  */
1174 static void cipso_v4_gentag_hdr(const struct cipso_v4_doi *doi_def,
1175                                 unsigned char *buf,
1176                                 u32 len)
1177 {
1178         buf[0] = IPOPT_CIPSO;
1179         buf[1] = CIPSO_V4_HDR_LEN + len;
1180         *(__be32 *)&buf[2] = htonl(doi_def->doi);
1181 }
1182
1183 /**
1184  * cipso_v4_gentag_rbm - Generate a CIPSO restricted bitmap tag (type #1)
1185  * @doi_def: the DOI definition
1186  * @secattr: the security attributes
1187  * @buffer: the option buffer
1188  * @buffer_len: length of buffer in bytes
1189  *
1190  * Description:
1191  * Generate a CIPSO option using the restricted bitmap tag, tag type #1.  The
1192  * actual buffer length may be larger than the indicated size due to
1193  * translation between host and network category bitmaps.  Returns the size of
1194  * the tag on success, negative values on failure.
1195  *
1196  */
1197 static int cipso_v4_gentag_rbm(const struct cipso_v4_doi *doi_def,
1198                                const struct netlbl_lsm_secattr *secattr,
1199                                unsigned char *buffer,
1200                                u32 buffer_len)
1201 {
1202         int ret_val;
1203         u32 tag_len;
1204         u32 level;
1205
1206         if ((secattr->flags & NETLBL_SECATTR_MLS_LVL) == 0)
1207                 return -EPERM;
1208
1209         ret_val = cipso_v4_map_lvl_hton(doi_def,
1210                                         secattr->attr.mls.lvl,
1211                                         &level);
1212         if (ret_val != 0)
1213                 return ret_val;
1214
1215         if (secattr->flags & NETLBL_SECATTR_MLS_CAT) {
1216                 ret_val = cipso_v4_map_cat_rbm_hton(doi_def,
1217                                                     secattr,
1218                                                     &buffer[4],
1219                                                     buffer_len - 4);
1220                 if (ret_val < 0)
1221                         return ret_val;
1222
1223                 /* This will send packets using the "optimized" format when
1224                  * possible as specified in  section 3.4.2.6 of the
1225                  * CIPSO draft. */
1226                 if (cipso_v4_rbm_optfmt && ret_val > 0 && ret_val <= 10)
1227                         tag_len = 14;
1228                 else
1229                         tag_len = 4 + ret_val;
1230         } else
1231                 tag_len = 4;
1232
1233         buffer[0] = CIPSO_V4_TAG_RBITMAP;
1234         buffer[1] = tag_len;
1235         buffer[3] = level;
1236
1237         return tag_len;
1238 }
1239
1240 /**
1241  * cipso_v4_parsetag_rbm - Parse a CIPSO restricted bitmap tag
1242  * @doi_def: the DOI definition
1243  * @tag: the CIPSO tag
1244  * @secattr: the security attributes
1245  *
1246  * Description:
1247  * Parse a CIPSO restricted bitmap tag (tag type #1) and return the security
1248  * attributes in @secattr.  Return zero on success, negatives values on
1249  * failure.
1250  *
1251  */
1252 static int cipso_v4_parsetag_rbm(const struct cipso_v4_doi *doi_def,
1253                                  const unsigned char *tag,
1254                                  struct netlbl_lsm_secattr *secattr)
1255 {
1256         int ret_val;
1257         u8 tag_len = tag[1];
1258         u32 level;
1259
1260         ret_val = cipso_v4_map_lvl_ntoh(doi_def, tag[3], &level);
1261         if (ret_val != 0)
1262                 return ret_val;
1263         secattr->attr.mls.lvl = level;
1264         secattr->flags |= NETLBL_SECATTR_MLS_LVL;
1265
1266         if (tag_len > 4) {
1267                 ret_val = cipso_v4_map_cat_rbm_ntoh(doi_def,
1268                                                     &tag[4],
1269                                                     tag_len - 4,
1270                                                     secattr);
1271                 if (ret_val != 0) {
1272                         netlbl_catmap_free(secattr->attr.mls.cat);
1273                         return ret_val;
1274                 }
1275
1276                 if (secattr->attr.mls.cat)
1277                         secattr->flags |= NETLBL_SECATTR_MLS_CAT;
1278         }
1279
1280         return 0;
1281 }
1282
1283 /**
1284  * cipso_v4_gentag_enum - Generate a CIPSO enumerated tag (type #2)
1285  * @doi_def: the DOI definition
1286  * @secattr: the security attributes
1287  * @buffer: the option buffer
1288  * @buffer_len: length of buffer in bytes
1289  *
1290  * Description:
1291  * Generate a CIPSO option using the enumerated tag, tag type #2.  Returns the
1292  * size of the tag on success, negative values on failure.
1293  *
1294  */
1295 static int cipso_v4_gentag_enum(const struct cipso_v4_doi *doi_def,
1296                                 const struct netlbl_lsm_secattr *secattr,
1297                                 unsigned char *buffer,
1298                                 u32 buffer_len)
1299 {
1300         int ret_val;
1301         u32 tag_len;
1302         u32 level;
1303
1304         if (!(secattr->flags & NETLBL_SECATTR_MLS_LVL))
1305                 return -EPERM;
1306
1307         ret_val = cipso_v4_map_lvl_hton(doi_def,
1308                                         secattr->attr.mls.lvl,
1309                                         &level);
1310         if (ret_val != 0)
1311                 return ret_val;
1312
1313         if (secattr->flags & NETLBL_SECATTR_MLS_CAT) {
1314                 ret_val = cipso_v4_map_cat_enum_hton(doi_def,
1315                                                      secattr,
1316                                                      &buffer[4],
1317                                                      buffer_len - 4);
1318                 if (ret_val < 0)
1319                         return ret_val;
1320
1321                 tag_len = 4 + ret_val;
1322         } else
1323                 tag_len = 4;
1324
1325         buffer[0] = CIPSO_V4_TAG_ENUM;
1326         buffer[1] = tag_len;
1327         buffer[3] = level;
1328
1329         return tag_len;
1330 }
1331
1332 /**
1333  * cipso_v4_parsetag_enum - Parse a CIPSO enumerated tag
1334  * @doi_def: the DOI definition
1335  * @tag: the CIPSO tag
1336  * @secattr: the security attributes
1337  *
1338  * Description:
1339  * Parse a CIPSO enumerated tag (tag type #2) and return the security
1340  * attributes in @secattr.  Return zero on success, negatives values on
1341  * failure.
1342  *
1343  */
1344 static int cipso_v4_parsetag_enum(const struct cipso_v4_doi *doi_def,
1345                                   const unsigned char *tag,
1346                                   struct netlbl_lsm_secattr *secattr)
1347 {
1348         int ret_val;
1349         u8 tag_len = tag[1];
1350         u32 level;
1351
1352         ret_val = cipso_v4_map_lvl_ntoh(doi_def, tag[3], &level);
1353         if (ret_val != 0)
1354                 return ret_val;
1355         secattr->attr.mls.lvl = level;
1356         secattr->flags |= NETLBL_SECATTR_MLS_LVL;
1357
1358         if (tag_len > 4) {
1359                 ret_val = cipso_v4_map_cat_enum_ntoh(doi_def,
1360                                                      &tag[4],
1361                                                      tag_len - 4,
1362                                                      secattr);
1363                 if (ret_val != 0) {
1364                         netlbl_catmap_free(secattr->attr.mls.cat);
1365                         return ret_val;
1366                 }
1367
1368                 secattr->flags |= NETLBL_SECATTR_MLS_CAT;
1369         }
1370
1371         return 0;
1372 }
1373
1374 /**
1375  * cipso_v4_gentag_rng - Generate a CIPSO ranged tag (type #5)
1376  * @doi_def: the DOI definition
1377  * @secattr: the security attributes
1378  * @buffer: the option buffer
1379  * @buffer_len: length of buffer in bytes
1380  *
1381  * Description:
1382  * Generate a CIPSO option using the ranged tag, tag type #5.  Returns the
1383  * size of the tag on success, negative values on failure.
1384  *
1385  */
1386 static int cipso_v4_gentag_rng(const struct cipso_v4_doi *doi_def,
1387                                const struct netlbl_lsm_secattr *secattr,
1388                                unsigned char *buffer,
1389                                u32 buffer_len)
1390 {
1391         int ret_val;
1392         u32 tag_len;
1393         u32 level;
1394
1395         if (!(secattr->flags & NETLBL_SECATTR_MLS_LVL))
1396                 return -EPERM;
1397
1398         ret_val = cipso_v4_map_lvl_hton(doi_def,
1399                                         secattr->attr.mls.lvl,
1400                                         &level);
1401         if (ret_val != 0)
1402                 return ret_val;
1403
1404         if (secattr->flags & NETLBL_SECATTR_MLS_CAT) {
1405                 ret_val = cipso_v4_map_cat_rng_hton(doi_def,
1406                                                     secattr,
1407                                                     &buffer[4],
1408                                                     buffer_len - 4);
1409                 if (ret_val < 0)
1410                         return ret_val;
1411
1412                 tag_len = 4 + ret_val;
1413         } else
1414                 tag_len = 4;
1415
1416         buffer[0] = CIPSO_V4_TAG_RANGE;
1417         buffer[1] = tag_len;
1418         buffer[3] = level;
1419
1420         return tag_len;
1421 }
1422
1423 /**
1424  * cipso_v4_parsetag_rng - Parse a CIPSO ranged tag
1425  * @doi_def: the DOI definition
1426  * @tag: the CIPSO tag
1427  * @secattr: the security attributes
1428  *
1429  * Description:
1430  * Parse a CIPSO ranged tag (tag type #5) and return the security attributes
1431  * in @secattr.  Return zero on success, negatives values on failure.
1432  *
1433  */
1434 static int cipso_v4_parsetag_rng(const struct cipso_v4_doi *doi_def,
1435                                  const unsigned char *tag,
1436                                  struct netlbl_lsm_secattr *secattr)
1437 {
1438         int ret_val;
1439         u8 tag_len = tag[1];
1440         u32 level;
1441
1442         ret_val = cipso_v4_map_lvl_ntoh(doi_def, tag[3], &level);
1443         if (ret_val != 0)
1444                 return ret_val;
1445         secattr->attr.mls.lvl = level;
1446         secattr->flags |= NETLBL_SECATTR_MLS_LVL;
1447
1448         if (tag_len > 4) {
1449                 ret_val = cipso_v4_map_cat_rng_ntoh(doi_def,
1450                                                     &tag[4],
1451                                                     tag_len - 4,
1452                                                     secattr);
1453                 if (ret_val != 0) {
1454                         netlbl_catmap_free(secattr->attr.mls.cat);
1455                         return ret_val;
1456                 }
1457
1458                 if (secattr->attr.mls.cat)
1459                         secattr->flags |= NETLBL_SECATTR_MLS_CAT;
1460         }
1461
1462         return 0;
1463 }
1464
1465 /**
1466  * cipso_v4_gentag_loc - Generate a CIPSO local tag (non-standard)
1467  * @doi_def: the DOI definition
1468  * @secattr: the security attributes
1469  * @buffer: the option buffer
1470  * @buffer_len: length of buffer in bytes
1471  *
1472  * Description:
1473  * Generate a CIPSO option using the local tag.  Returns the size of the tag
1474  * on success, negative values on failure.
1475  *
1476  */
1477 static int cipso_v4_gentag_loc(const struct cipso_v4_doi *doi_def,
1478                                const struct netlbl_lsm_secattr *secattr,
1479                                unsigned char *buffer,
1480                                u32 buffer_len)
1481 {
1482         if (!(secattr->flags & NETLBL_SECATTR_SECID))
1483                 return -EPERM;
1484
1485         buffer[0] = CIPSO_V4_TAG_LOCAL;
1486         buffer[1] = CIPSO_V4_TAG_LOC_BLEN;
1487         *(u32 *)&buffer[2] = secattr->attr.secid;
1488
1489         return CIPSO_V4_TAG_LOC_BLEN;
1490 }
1491
1492 /**
1493  * cipso_v4_parsetag_loc - Parse a CIPSO local tag
1494  * @doi_def: the DOI definition
1495  * @tag: the CIPSO tag
1496  * @secattr: the security attributes
1497  *
1498  * Description:
1499  * Parse a CIPSO local tag and return the security attributes in @secattr.
1500  * Return zero on success, negatives values on failure.
1501  *
1502  */
1503 static int cipso_v4_parsetag_loc(const struct cipso_v4_doi *doi_def,
1504                                  const unsigned char *tag,
1505                                  struct netlbl_lsm_secattr *secattr)
1506 {
1507         secattr->attr.secid = *(u32 *)&tag[2];
1508         secattr->flags |= NETLBL_SECATTR_SECID;
1509
1510         return 0;
1511 }
1512
1513 /**
1514  * cipso_v4_optptr - Find the CIPSO option in the packet
1515  * @skb: the packet
1516  *
1517  * Description:
1518  * Parse the packet's IP header looking for a CIPSO option.  Returns a pointer
1519  * to the start of the CIPSO option on success, NULL if one is not found.
1520  *
1521  */
1522 unsigned char *cipso_v4_optptr(const struct sk_buff *skb)
1523 {
1524         const struct iphdr *iph = ip_hdr(skb);
1525         unsigned char *optptr = (unsigned char *)&(ip_hdr(skb)[1]);
1526         int optlen;
1527         int taglen;
1528
1529         for (optlen = iph->ihl*4 - sizeof(struct iphdr); optlen > 1; ) {
1530                 switch (optptr[0]) {
1531                 case IPOPT_END:
1532                         return NULL;
1533                 case IPOPT_NOOP:
1534                         taglen = 1;
1535                         break;
1536                 default:
1537                         taglen = optptr[1];
1538                 }
1539                 if (!taglen || taglen > optlen)
1540                         return NULL;
1541                 if (optptr[0] == IPOPT_CIPSO)
1542                         return optptr;
1543
1544                 optlen -= taglen;
1545                 optptr += taglen;
1546         }
1547
1548         return NULL;
1549 }
1550
1551 /**
1552  * cipso_v4_validate - Validate a CIPSO option
1553  * @option: the start of the option, on error it is set to point to the error
1554  *
1555  * Description:
1556  * This routine is called to validate a CIPSO option, it checks all of the
1557  * fields to ensure that they are at least valid, see the draft snippet below
1558  * for details.  If the option is valid then a zero value is returned and
1559  * the value of @option is unchanged.  If the option is invalid then a
1560  * non-zero value is returned and @option is adjusted to point to the
1561  * offending portion of the option.  From the IETF draft ...
1562  *
1563  *  "If any field within the CIPSO options, such as the DOI identifier, is not
1564  *   recognized the IP datagram is discarded and an ICMP 'parameter problem'
1565  *   (type 12) is generated and returned.  The ICMP code field is set to 'bad
1566  *   parameter' (code 0) and the pointer is set to the start of the CIPSO field
1567  *   that is unrecognized."
1568  *
1569  */
1570 int cipso_v4_validate(const struct sk_buff *skb, unsigned char **option)
1571 {
1572         unsigned char *opt = *option;
1573         unsigned char *tag;
1574         unsigned char opt_iter;
1575         unsigned char err_offset = 0;
1576         u8 opt_len;
1577         u8 tag_len;
1578         struct cipso_v4_doi *doi_def = NULL;
1579         u32 tag_iter;
1580
1581         /* caller already checks for length values that are too large */
1582         opt_len = opt[1];
1583         if (opt_len < 8) {
1584                 err_offset = 1;
1585                 goto validate_return;
1586         }
1587
1588         rcu_read_lock();
1589         doi_def = cipso_v4_doi_search(get_unaligned_be32(&opt[2]));
1590         if (!doi_def) {
1591                 err_offset = 2;
1592                 goto validate_return_locked;
1593         }
1594
1595         opt_iter = CIPSO_V4_HDR_LEN;
1596         tag = opt + opt_iter;
1597         while (opt_iter < opt_len) {
1598                 for (tag_iter = 0; doi_def->tags[tag_iter] != tag[0];)
1599                         if (doi_def->tags[tag_iter] == CIPSO_V4_TAG_INVALID ||
1600                             ++tag_iter == CIPSO_V4_TAG_MAXCNT) {
1601                                 err_offset = opt_iter;
1602                                 goto validate_return_locked;
1603                         }
1604
1605                 if (opt_iter + 1 == opt_len) {
1606                         err_offset = opt_iter;
1607                         goto validate_return_locked;
1608                 }
1609                 tag_len = tag[1];
1610                 if (tag_len > (opt_len - opt_iter)) {
1611                         err_offset = opt_iter + 1;
1612                         goto validate_return_locked;
1613                 }
1614
1615                 switch (tag[0]) {
1616                 case CIPSO_V4_TAG_RBITMAP:
1617                         if (tag_len < CIPSO_V4_TAG_RBM_BLEN) {
1618                                 err_offset = opt_iter + 1;
1619                                 goto validate_return_locked;
1620                         }
1621
1622                         /* We are already going to do all the verification
1623                          * necessary at the socket layer so from our point of
1624                          * view it is safe to turn these checks off (and less
1625                          * work), however, the CIPSO draft says we should do
1626                          * all the CIPSO validations here but it doesn't
1627                          * really specify _exactly_ what we need to validate
1628                          * ... so, just make it a sysctl tunable. */
1629                         if (cipso_v4_rbm_strictvalid) {
1630                                 if (cipso_v4_map_lvl_valid(doi_def,
1631                                                            tag[3]) < 0) {
1632                                         err_offset = opt_iter + 3;
1633                                         goto validate_return_locked;
1634                                 }
1635                                 if (tag_len > CIPSO_V4_TAG_RBM_BLEN &&
1636                                     cipso_v4_map_cat_rbm_valid(doi_def,
1637                                                             &tag[4],
1638                                                             tag_len - 4) < 0) {
1639                                         err_offset = opt_iter + 4;
1640                                         goto validate_return_locked;
1641                                 }
1642                         }
1643                         break;
1644                 case CIPSO_V4_TAG_ENUM:
1645                         if (tag_len < CIPSO_V4_TAG_ENUM_BLEN) {
1646                                 err_offset = opt_iter + 1;
1647                                 goto validate_return_locked;
1648                         }
1649
1650                         if (cipso_v4_map_lvl_valid(doi_def,
1651                                                    tag[3]) < 0) {
1652                                 err_offset = opt_iter + 3;
1653                                 goto validate_return_locked;
1654                         }
1655                         if (tag_len > CIPSO_V4_TAG_ENUM_BLEN &&
1656                             cipso_v4_map_cat_enum_valid(doi_def,
1657                                                         &tag[4],
1658                                                         tag_len - 4) < 0) {
1659                                 err_offset = opt_iter + 4;
1660                                 goto validate_return_locked;
1661                         }
1662                         break;
1663                 case CIPSO_V4_TAG_RANGE:
1664                         if (tag_len < CIPSO_V4_TAG_RNG_BLEN) {
1665                                 err_offset = opt_iter + 1;
1666                                 goto validate_return_locked;
1667                         }
1668
1669                         if (cipso_v4_map_lvl_valid(doi_def,
1670                                                    tag[3]) < 0) {
1671                                 err_offset = opt_iter + 3;
1672                                 goto validate_return_locked;
1673                         }
1674                         if (tag_len > CIPSO_V4_TAG_RNG_BLEN &&
1675                             cipso_v4_map_cat_rng_valid(doi_def,
1676                                                        &tag[4],
1677                                                        tag_len - 4) < 0) {
1678                                 err_offset = opt_iter + 4;
1679                                 goto validate_return_locked;
1680                         }
1681                         break;
1682                 case CIPSO_V4_TAG_LOCAL:
1683                         /* This is a non-standard tag that we only allow for
1684                          * local connections, so if the incoming interface is
1685                          * not the loopback device drop the packet. Further,
1686                          * there is no legitimate reason for setting this from
1687                          * userspace so reject it if skb is NULL. */
1688                         if (!skb || !(skb->dev->flags & IFF_LOOPBACK)) {
1689                                 err_offset = opt_iter;
1690                                 goto validate_return_locked;
1691                         }
1692                         if (tag_len != CIPSO_V4_TAG_LOC_BLEN) {
1693                                 err_offset = opt_iter + 1;
1694                                 goto validate_return_locked;
1695                         }
1696                         break;
1697                 default:
1698                         err_offset = opt_iter;
1699                         goto validate_return_locked;
1700                 }
1701
1702                 tag += tag_len;
1703                 opt_iter += tag_len;
1704         }
1705
1706 validate_return_locked:
1707         rcu_read_unlock();
1708 validate_return:
1709         *option = opt + err_offset;
1710         return err_offset;
1711 }
1712
1713 /**
1714  * cipso_v4_error - Send the correct response for a bad packet
1715  * @skb: the packet
1716  * @error: the error code
1717  * @gateway: CIPSO gateway flag
1718  *
1719  * Description:
1720  * Based on the error code given in @error, send an ICMP error message back to
1721  * the originating host.  From the IETF draft ...
1722  *
1723  *  "If the contents of the CIPSO [option] are valid but the security label is
1724  *   outside of the configured host or port label range, the datagram is
1725  *   discarded and an ICMP 'destination unreachable' (type 3) is generated and
1726  *   returned.  The code field of the ICMP is set to 'communication with
1727  *   destination network administratively prohibited' (code 9) or to
1728  *   'communication with destination host administratively prohibited'
1729  *   (code 10).  The value of the code is dependent on whether the originator
1730  *   of the ICMP message is acting as a CIPSO host or a CIPSO gateway.  The
1731  *   recipient of the ICMP message MUST be able to handle either value.  The
1732  *   same procedure is performed if a CIPSO [option] can not be added to an
1733  *   IP packet because it is too large to fit in the IP options area."
1734  *
1735  *  "If the error is triggered by receipt of an ICMP message, the message is
1736  *   discarded and no response is permitted (consistent with general ICMP
1737  *   processing rules)."
1738  *
1739  */
1740 void cipso_v4_error(struct sk_buff *skb, int error, u32 gateway)
1741 {
1742         unsigned char optbuf[sizeof(struct ip_options) + 40];
1743         struct ip_options *opt = (struct ip_options *)optbuf;
1744         int res;
1745
1746         if (ip_hdr(skb)->protocol == IPPROTO_ICMP || error != -EACCES)
1747                 return;
1748
1749         /*
1750          * We might be called above the IP layer,
1751          * so we can not use icmp_send and IPCB here.
1752          */
1753
1754         memset(opt, 0, sizeof(struct ip_options));
1755         opt->optlen = ip_hdr(skb)->ihl*4 - sizeof(struct iphdr);
1756         rcu_read_lock();
1757         res = __ip_options_compile(dev_net(skb->dev), opt, skb, NULL);
1758         rcu_read_unlock();
1759
1760         if (res)
1761                 return;
1762
1763         if (gateway)
1764                 __icmp_send(skb, ICMP_DEST_UNREACH, ICMP_NET_ANO, 0, opt);
1765         else
1766                 __icmp_send(skb, ICMP_DEST_UNREACH, ICMP_HOST_ANO, 0, opt);
1767 }
1768
1769 /**
1770  * cipso_v4_genopt - Generate a CIPSO option
1771  * @buf: the option buffer
1772  * @buf_len: the size of opt_buf
1773  * @doi_def: the CIPSO DOI to use
1774  * @secattr: the security attributes
1775  *
1776  * Description:
1777  * Generate a CIPSO option using the DOI definition and security attributes
1778  * passed to the function.  Returns the length of the option on success and
1779  * negative values on failure.
1780  *
1781  */
1782 static int cipso_v4_genopt(unsigned char *buf, u32 buf_len,
1783                            const struct cipso_v4_doi *doi_def,
1784                            const struct netlbl_lsm_secattr *secattr)
1785 {
1786         int ret_val;
1787         u32 iter;
1788
1789         if (buf_len <= CIPSO_V4_HDR_LEN)
1790                 return -ENOSPC;
1791
1792         /* XXX - This code assumes only one tag per CIPSO option which isn't
1793          * really a good assumption to make but since we only support the MAC
1794          * tags right now it is a safe assumption. */
1795         iter = 0;
1796         do {
1797                 memset(buf, 0, buf_len);
1798                 switch (doi_def->tags[iter]) {
1799                 case CIPSO_V4_TAG_RBITMAP:
1800                         ret_val = cipso_v4_gentag_rbm(doi_def,
1801                                                    secattr,
1802                                                    &buf[CIPSO_V4_HDR_LEN],
1803                                                    buf_len - CIPSO_V4_HDR_LEN);
1804                         break;
1805                 case CIPSO_V4_TAG_ENUM:
1806                         ret_val = cipso_v4_gentag_enum(doi_def,
1807                                                    secattr,
1808                                                    &buf[CIPSO_V4_HDR_LEN],
1809                                                    buf_len - CIPSO_V4_HDR_LEN);
1810                         break;
1811                 case CIPSO_V4_TAG_RANGE:
1812                         ret_val = cipso_v4_gentag_rng(doi_def,
1813                                                    secattr,
1814                                                    &buf[CIPSO_V4_HDR_LEN],
1815                                                    buf_len - CIPSO_V4_HDR_LEN);
1816                         break;
1817                 case CIPSO_V4_TAG_LOCAL:
1818                         ret_val = cipso_v4_gentag_loc(doi_def,
1819                                                    secattr,
1820                                                    &buf[CIPSO_V4_HDR_LEN],
1821                                                    buf_len - CIPSO_V4_HDR_LEN);
1822                         break;
1823                 default:
1824                         return -EPERM;
1825                 }
1826
1827                 iter++;
1828         } while (ret_val < 0 &&
1829                  iter < CIPSO_V4_TAG_MAXCNT &&
1830                  doi_def->tags[iter] != CIPSO_V4_TAG_INVALID);
1831         if (ret_val < 0)
1832                 return ret_val;
1833         cipso_v4_gentag_hdr(doi_def, buf, ret_val);
1834         return CIPSO_V4_HDR_LEN + ret_val;
1835 }
1836
1837 /**
1838  * cipso_v4_sock_setattr - Add a CIPSO option to a socket
1839  * @sk: the socket
1840  * @doi_def: the CIPSO DOI to use
1841  * @secattr: the specific security attributes of the socket
1842  *
1843  * Description:
1844  * Set the CIPSO option on the given socket using the DOI definition and
1845  * security attributes passed to the function.  This function requires
1846  * exclusive access to @sk, which means it either needs to be in the
1847  * process of being created or locked.  Returns zero on success and negative
1848  * values on failure.
1849  *
1850  */
1851 int cipso_v4_sock_setattr(struct sock *sk,
1852                           const struct cipso_v4_doi *doi_def,
1853                           const struct netlbl_lsm_secattr *secattr)
1854 {
1855         int ret_val = -EPERM;
1856         unsigned char *buf = NULL;
1857         u32 buf_len;
1858         u32 opt_len;
1859         struct ip_options_rcu *old, *opt = NULL;
1860         struct inet_sock *sk_inet;
1861         struct inet_connection_sock *sk_conn;
1862
1863         /* In the case of sock_create_lite(), the sock->sk field is not
1864          * defined yet but it is not a problem as the only users of these
1865          * "lite" PF_INET sockets are functions which do an accept() call
1866          * afterwards so we will label the socket as part of the accept(). */
1867         if (!sk)
1868                 return 0;
1869
1870         /* We allocate the maximum CIPSO option size here so we are probably
1871          * being a little wasteful, but it makes our life _much_ easier later
1872          * on and after all we are only talking about 40 bytes. */
1873         buf_len = CIPSO_V4_OPT_LEN_MAX;
1874         buf = kmalloc(buf_len, GFP_ATOMIC);
1875         if (!buf) {
1876                 ret_val = -ENOMEM;
1877                 goto socket_setattr_failure;
1878         }
1879
1880         ret_val = cipso_v4_genopt(buf, buf_len, doi_def, secattr);
1881         if (ret_val < 0)
1882                 goto socket_setattr_failure;
1883         buf_len = ret_val;
1884
1885         /* We can't use ip_options_get() directly because it makes a call to
1886          * ip_options_get_alloc() which allocates memory with GFP_KERNEL and
1887          * we won't always have CAP_NET_RAW even though we _always_ want to
1888          * set the IPOPT_CIPSO option. */
1889         opt_len = (buf_len + 3) & ~3;
1890         opt = kzalloc(sizeof(*opt) + opt_len, GFP_ATOMIC);
1891         if (!opt) {
1892                 ret_val = -ENOMEM;
1893                 goto socket_setattr_failure;
1894         }
1895         memcpy(opt->opt.__data, buf, buf_len);
1896         opt->opt.optlen = opt_len;
1897         opt->opt.cipso = sizeof(struct iphdr);
1898         kfree(buf);
1899         buf = NULL;
1900
1901         sk_inet = inet_sk(sk);
1902
1903         old = rcu_dereference_protected(sk_inet->inet_opt,
1904                                         lockdep_sock_is_held(sk));
1905         if (sk_inet->is_icsk) {
1906                 sk_conn = inet_csk(sk);
1907                 if (old)
1908                         sk_conn->icsk_ext_hdr_len -= old->opt.optlen;
1909                 sk_conn->icsk_ext_hdr_len += opt->opt.optlen;
1910                 sk_conn->icsk_sync_mss(sk, sk_conn->icsk_pmtu_cookie);
1911         }
1912         rcu_assign_pointer(sk_inet->inet_opt, opt);
1913         if (old)
1914                 kfree_rcu(old, rcu);
1915
1916         return 0;
1917
1918 socket_setattr_failure:
1919         kfree(buf);
1920         kfree(opt);
1921         return ret_val;
1922 }
1923
1924 /**
1925  * cipso_v4_req_setattr - Add a CIPSO option to a connection request socket
1926  * @req: the connection request socket
1927  * @doi_def: the CIPSO DOI to use
1928  * @secattr: the specific security attributes of the socket
1929  *
1930  * Description:
1931  * Set the CIPSO option on the given socket using the DOI definition and
1932  * security attributes passed to the function.  Returns zero on success and
1933  * negative values on failure.
1934  *
1935  */
1936 int cipso_v4_req_setattr(struct request_sock *req,
1937                          const struct cipso_v4_doi *doi_def,
1938                          const struct netlbl_lsm_secattr *secattr)
1939 {
1940         int ret_val = -EPERM;
1941         unsigned char *buf = NULL;
1942         u32 buf_len;
1943         u32 opt_len;
1944         struct ip_options_rcu *opt = NULL;
1945         struct inet_request_sock *req_inet;
1946
1947         /* We allocate the maximum CIPSO option size here so we are probably
1948          * being a little wasteful, but it makes our life _much_ easier later
1949          * on and after all we are only talking about 40 bytes. */
1950         buf_len = CIPSO_V4_OPT_LEN_MAX;
1951         buf = kmalloc(buf_len, GFP_ATOMIC);
1952         if (!buf) {
1953                 ret_val = -ENOMEM;
1954                 goto req_setattr_failure;
1955         }
1956
1957         ret_val = cipso_v4_genopt(buf, buf_len, doi_def, secattr);
1958         if (ret_val < 0)
1959                 goto req_setattr_failure;
1960         buf_len = ret_val;
1961
1962         /* We can't use ip_options_get() directly because it makes a call to
1963          * ip_options_get_alloc() which allocates memory with GFP_KERNEL and
1964          * we won't always have CAP_NET_RAW even though we _always_ want to
1965          * set the IPOPT_CIPSO option. */
1966         opt_len = (buf_len + 3) & ~3;
1967         opt = kzalloc(sizeof(*opt) + opt_len, GFP_ATOMIC);
1968         if (!opt) {
1969                 ret_val = -ENOMEM;
1970                 goto req_setattr_failure;
1971         }
1972         memcpy(opt->opt.__data, buf, buf_len);
1973         opt->opt.optlen = opt_len;
1974         opt->opt.cipso = sizeof(struct iphdr);
1975         kfree(buf);
1976         buf = NULL;
1977
1978         req_inet = inet_rsk(req);
1979         opt = xchg((__force struct ip_options_rcu **)&req_inet->ireq_opt, opt);
1980         if (opt)
1981                 kfree_rcu(opt, rcu);
1982
1983         return 0;
1984
1985 req_setattr_failure:
1986         kfree(buf);
1987         kfree(opt);
1988         return ret_val;
1989 }
1990
1991 /**
1992  * cipso_v4_delopt - Delete the CIPSO option from a set of IP options
1993  * @opt_ptr: IP option pointer
1994  *
1995  * Description:
1996  * Deletes the CIPSO IP option from a set of IP options and makes the necessary
1997  * adjustments to the IP option structure.  Returns zero on success, negative
1998  * values on failure.
1999  *
2000  */
2001 static int cipso_v4_delopt(struct ip_options_rcu __rcu **opt_ptr)
2002 {
2003         struct ip_options_rcu *opt = rcu_dereference_protected(*opt_ptr, 1);
2004         int hdr_delta = 0;
2005
2006         if (!opt || opt->opt.cipso == 0)
2007                 return 0;
2008         if (opt->opt.srr || opt->opt.rr || opt->opt.ts || opt->opt.router_alert) {
2009                 u8 cipso_len;
2010                 u8 cipso_off;
2011                 unsigned char *cipso_ptr;
2012                 int iter;
2013                 int optlen_new;
2014
2015                 cipso_off = opt->opt.cipso - sizeof(struct iphdr);
2016                 cipso_ptr = &opt->opt.__data[cipso_off];
2017                 cipso_len = cipso_ptr[1];
2018
2019                 if (opt->opt.srr > opt->opt.cipso)
2020                         opt->opt.srr -= cipso_len;
2021                 if (opt->opt.rr > opt->opt.cipso)
2022                         opt->opt.rr -= cipso_len;
2023                 if (opt->opt.ts > opt->opt.cipso)
2024                         opt->opt.ts -= cipso_len;
2025                 if (opt->opt.router_alert > opt->opt.cipso)
2026                         opt->opt.router_alert -= cipso_len;
2027                 opt->opt.cipso = 0;
2028
2029                 memmove(cipso_ptr, cipso_ptr + cipso_len,
2030                         opt->opt.optlen - cipso_off - cipso_len);
2031
2032                 /* determining the new total option length is tricky because of
2033                  * the padding necessary, the only thing i can think to do at
2034                  * this point is walk the options one-by-one, skipping the
2035                  * padding at the end to determine the actual option size and
2036                  * from there we can determine the new total option length */
2037                 iter = 0;
2038                 optlen_new = 0;
2039                 while (iter < opt->opt.optlen)
2040                         if (opt->opt.__data[iter] != IPOPT_NOP) {
2041                                 iter += opt->opt.__data[iter + 1];
2042                                 optlen_new = iter;
2043                         } else
2044                                 iter++;
2045                 hdr_delta = opt->opt.optlen;
2046                 opt->opt.optlen = (optlen_new + 3) & ~3;
2047                 hdr_delta -= opt->opt.optlen;
2048         } else {
2049                 /* only the cipso option was present on the socket so we can
2050                  * remove the entire option struct */
2051                 *opt_ptr = NULL;
2052                 hdr_delta = opt->opt.optlen;
2053                 kfree_rcu(opt, rcu);
2054         }
2055
2056         return hdr_delta;
2057 }
2058
2059 /**
2060  * cipso_v4_sock_delattr - Delete the CIPSO option from a socket
2061  * @sk: the socket
2062  *
2063  * Description:
2064  * Removes the CIPSO option from a socket, if present.
2065  *
2066  */
2067 void cipso_v4_sock_delattr(struct sock *sk)
2068 {
2069         struct inet_sock *sk_inet;
2070         int hdr_delta;
2071
2072         sk_inet = inet_sk(sk);
2073
2074         hdr_delta = cipso_v4_delopt(&sk_inet->inet_opt);
2075         if (sk_inet->is_icsk && hdr_delta > 0) {
2076                 struct inet_connection_sock *sk_conn = inet_csk(sk);
2077                 sk_conn->icsk_ext_hdr_len -= hdr_delta;
2078                 sk_conn->icsk_sync_mss(sk, sk_conn->icsk_pmtu_cookie);
2079         }
2080 }
2081
2082 /**
2083  * cipso_v4_req_delattr - Delete the CIPSO option from a request socket
2084  * @reg: the request socket
2085  *
2086  * Description:
2087  * Removes the CIPSO option from a request socket, if present.
2088  *
2089  */
2090 void cipso_v4_req_delattr(struct request_sock *req)
2091 {
2092         cipso_v4_delopt(&inet_rsk(req)->ireq_opt);
2093 }
2094
2095 /**
2096  * cipso_v4_getattr - Helper function for the cipso_v4_*_getattr functions
2097  * @cipso: the CIPSO v4 option
2098  * @secattr: the security attributes
2099  *
2100  * Description:
2101  * Inspect @cipso and return the security attributes in @secattr.  Returns zero
2102  * on success and negative values on failure.
2103  *
2104  */
2105 int cipso_v4_getattr(const unsigned char *cipso,
2106                      struct netlbl_lsm_secattr *secattr)
2107 {
2108         int ret_val = -ENOMSG;
2109         u32 doi;
2110         struct cipso_v4_doi *doi_def;
2111
2112         if (cipso_v4_cache_check(cipso, cipso[1], secattr) == 0)
2113                 return 0;
2114
2115         doi = get_unaligned_be32(&cipso[2]);
2116         rcu_read_lock();
2117         doi_def = cipso_v4_doi_search(doi);
2118         if (!doi_def)
2119                 goto getattr_return;
2120         /* XXX - This code assumes only one tag per CIPSO option which isn't
2121          * really a good assumption to make but since we only support the MAC
2122          * tags right now it is a safe assumption. */
2123         switch (cipso[6]) {
2124         case CIPSO_V4_TAG_RBITMAP:
2125                 ret_val = cipso_v4_parsetag_rbm(doi_def, &cipso[6], secattr);
2126                 break;
2127         case CIPSO_V4_TAG_ENUM:
2128                 ret_val = cipso_v4_parsetag_enum(doi_def, &cipso[6], secattr);
2129                 break;
2130         case CIPSO_V4_TAG_RANGE:
2131                 ret_val = cipso_v4_parsetag_rng(doi_def, &cipso[6], secattr);
2132                 break;
2133         case CIPSO_V4_TAG_LOCAL:
2134                 ret_val = cipso_v4_parsetag_loc(doi_def, &cipso[6], secattr);
2135                 break;
2136         }
2137         if (ret_val == 0)
2138                 secattr->type = NETLBL_NLTYPE_CIPSOV4;
2139
2140 getattr_return:
2141         rcu_read_unlock();
2142         return ret_val;
2143 }
2144
2145 /**
2146  * cipso_v4_sock_getattr - Get the security attributes from a sock
2147  * @sk: the sock
2148  * @secattr: the security attributes
2149  *
2150  * Description:
2151  * Query @sk to see if there is a CIPSO option attached to the sock and if
2152  * there is return the CIPSO security attributes in @secattr.  This function
2153  * requires that @sk be locked, or privately held, but it does not do any
2154  * locking itself.  Returns zero on success and negative values on failure.
2155  *
2156  */
2157 int cipso_v4_sock_getattr(struct sock *sk, struct netlbl_lsm_secattr *secattr)
2158 {
2159         struct ip_options_rcu *opt;
2160         int res = -ENOMSG;
2161
2162         rcu_read_lock();
2163         opt = rcu_dereference(inet_sk(sk)->inet_opt);
2164         if (opt && opt->opt.cipso)
2165                 res = cipso_v4_getattr(opt->opt.__data +
2166                                                 opt->opt.cipso -
2167                                                 sizeof(struct iphdr),
2168                                        secattr);
2169         rcu_read_unlock();
2170         return res;
2171 }
2172
2173 /**
2174  * cipso_v4_skbuff_setattr - Set the CIPSO option on a packet
2175  * @skb: the packet
2176  * @secattr: the security attributes
2177  *
2178  * Description:
2179  * Set the CIPSO option on the given packet based on the security attributes.
2180  * Returns a pointer to the IP header on success and NULL on failure.
2181  *
2182  */
2183 int cipso_v4_skbuff_setattr(struct sk_buff *skb,
2184                             const struct cipso_v4_doi *doi_def,
2185                             const struct netlbl_lsm_secattr *secattr)
2186 {
2187         int ret_val;
2188         struct iphdr *iph;
2189         struct ip_options *opt = &IPCB(skb)->opt;
2190         unsigned char buf[CIPSO_V4_OPT_LEN_MAX];
2191         u32 buf_len = CIPSO_V4_OPT_LEN_MAX;
2192         u32 opt_len;
2193         int len_delta;
2194
2195         ret_val = cipso_v4_genopt(buf, buf_len, doi_def, secattr);
2196         if (ret_val < 0)
2197                 return ret_val;
2198         buf_len = ret_val;
2199         opt_len = (buf_len + 3) & ~3;
2200
2201         /* we overwrite any existing options to ensure that we have enough
2202          * room for the CIPSO option, the reason is that we _need_ to guarantee
2203          * that the security label is applied to the packet - we do the same
2204          * thing when using the socket options and it hasn't caused a problem,
2205          * if we need to we can always revisit this choice later */
2206
2207         len_delta = opt_len - opt->optlen;
2208         /* if we don't ensure enough headroom we could panic on the skb_push()
2209          * call below so make sure we have enough, we are also "mangling" the
2210          * packet so we should probably do a copy-on-write call anyway */
2211         ret_val = skb_cow(skb, skb_headroom(skb) + len_delta);
2212         if (ret_val < 0)
2213                 return ret_val;
2214
2215         if (len_delta > 0) {
2216                 /* we assume that the header + opt->optlen have already been
2217                  * "pushed" in ip_options_build() or similar */
2218                 iph = ip_hdr(skb);
2219                 skb_push(skb, len_delta);
2220                 memmove((char *)iph - len_delta, iph, iph->ihl << 2);
2221                 skb_reset_network_header(skb);
2222                 iph = ip_hdr(skb);
2223         } else if (len_delta < 0) {
2224                 iph = ip_hdr(skb);
2225                 memset(iph + 1, IPOPT_NOP, opt->optlen);
2226         } else
2227                 iph = ip_hdr(skb);
2228
2229         if (opt->optlen > 0)
2230                 memset(opt, 0, sizeof(*opt));
2231         opt->optlen = opt_len;
2232         opt->cipso = sizeof(struct iphdr);
2233         opt->is_changed = 1;
2234
2235         /* we have to do the following because we are being called from a
2236          * netfilter hook which means the packet already has had the header
2237          * fields populated and the checksum calculated - yes this means we
2238          * are doing more work than needed but we do it to keep the core
2239          * stack clean and tidy */
2240         memcpy(iph + 1, buf, buf_len);
2241         if (opt_len > buf_len)
2242                 memset((char *)(iph + 1) + buf_len, 0, opt_len - buf_len);
2243         if (len_delta != 0) {
2244                 iph->ihl = 5 + (opt_len >> 2);
2245                 iph->tot_len = htons(skb->len);
2246         }
2247         ip_send_check(iph);
2248
2249         return 0;
2250 }
2251
2252 /**
2253  * cipso_v4_skbuff_delattr - Delete any CIPSO options from a packet
2254  * @skb: the packet
2255  *
2256  * Description:
2257  * Removes any and all CIPSO options from the given packet.  Returns zero on
2258  * success, negative values on failure.
2259  *
2260  */
2261 int cipso_v4_skbuff_delattr(struct sk_buff *skb)
2262 {
2263         int ret_val;
2264         struct iphdr *iph;
2265         struct ip_options *opt = &IPCB(skb)->opt;
2266         unsigned char *cipso_ptr;
2267
2268         if (opt->cipso == 0)
2269                 return 0;
2270
2271         /* since we are changing the packet we should make a copy */
2272         ret_val = skb_cow(skb, skb_headroom(skb));
2273         if (ret_val < 0)
2274                 return ret_val;
2275
2276         /* the easiest thing to do is just replace the cipso option with noop
2277          * options since we don't change the size of the packet, although we
2278          * still need to recalculate the checksum */
2279
2280         iph = ip_hdr(skb);
2281         cipso_ptr = (unsigned char *)iph + opt->cipso;
2282         memset(cipso_ptr, IPOPT_NOOP, cipso_ptr[1]);
2283         opt->cipso = 0;
2284         opt->is_changed = 1;
2285
2286         ip_send_check(iph);
2287
2288         return 0;
2289 }
2290
2291 /*
2292  * Setup Functions
2293  */
2294
2295 /**
2296  * cipso_v4_init - Initialize the CIPSO module
2297  *
2298  * Description:
2299  * Initialize the CIPSO module and prepare it for use.  Returns zero on success
2300  * and negative values on failure.
2301  *
2302  */
2303 static int __init cipso_v4_init(void)
2304 {
2305         int ret_val;
2306
2307         ret_val = cipso_v4_cache_init();
2308         if (ret_val != 0)
2309                 panic("Failed to initialize the CIPSO/IPv4 cache (%d)\n",
2310                       ret_val);
2311
2312         return 0;
2313 }
2314
2315 subsys_initcall(cipso_v4_init);