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