Linux kernel mirror (for testing) git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
kernel os linux

Merge branch 'for-linus2' of git://git.kernel.org/pub/scm/linux/kernel/git/jmorris/linux-security

Pull security subsystem updates from James Morris:
"In this patchset, we finally get an SELinux update, with Paul Moore
taking over as maintainer of that code.

Also a significant update for the Keys subsystem, as well as
maintenance updates to Smack, IMA, TPM, and Apparmor"

and since I wanted to know more about the updates to key handling,
here's the explanation from David Howells on that:

"Okay. There are a number of separate bits. I'll go over the big bits
and the odd important other bit, most of the smaller bits are just
fixes and cleanups. If you want the small bits accounting for, I can
do that too.

(1) Keyring capacity expansion.

KEYS: Consolidate the concept of an 'index key' for key access
KEYS: Introduce a search context structure
KEYS: Search for auth-key by name rather than target key ID
Add a generic associative array implementation.
KEYS: Expand the capacity of a keyring

Several of the patches are providing an expansion of the capacity of a
keyring. Currently, the maximum size of a keyring payload is one page.
Subtract a small header and then divide up into pointers, that only gives
you ~500 pointers on an x86_64 box. However, since the NFS idmapper uses
a keyring to store ID mapping data, that has proven to be insufficient to
the cause.

Whatever data structure I use to handle the keyring payload, it can only
store pointers to keys, not the keys themselves because several keyrings
may point to a single key. This precludes inserting, say, and rb_node
struct into the key struct for this purpose.

I could make an rbtree of records such that each record has an rb_node
and a key pointer, but that would use four words of space per key stored
in the keyring. It would, however, be able to use much existing code.

I selected instead a non-rebalancing radix-tree type approach as that
could have a better space-used/key-pointer ratio. I could have used the
radix tree implementation that we already have and insert keys into it by
their serial numbers, but that means any sort of search must iterate over
the whole radix tree. Further, its nodes are a bit on the capacious side
for what I want - especially given that key serial numbers are randomly
allocated, thus leaving a lot of empty space in the tree.

So what I have is an associative array that internally is a radix-tree
with 16 pointers per node where the index key is constructed from the key
type pointer and the key description. This means that an exact lookup by
type+description is very fast as this tells us how to navigate directly to
the target key.

I made the data structure general in lib/assoc_array.c as far as it is
concerned, its index key is just a sequence of bits that leads to a
pointer. It's possible that someone else will be able to make use of it
also. FS-Cache might, for example.

(2) Mark keys as 'trusted' and keyrings as 'trusted only'.

KEYS: verify a certificate is signed by a 'trusted' key
KEYS: Make the system 'trusted' keyring viewable by userspace
KEYS: Add a 'trusted' flag and a 'trusted only' flag
KEYS: Separate the kernel signature checking keyring from module signing

These patches allow keys carrying asymmetric public keys to be marked as
being 'trusted' and allow keyrings to be marked as only permitting the
addition or linkage of trusted keys.

Keys loaded from hardware during kernel boot or compiled into the kernel
during build are marked as being trusted automatically. New keys can be
loaded at runtime with add_key(). They are checked against the system
keyring contents and if their signatures can be validated with keys that
are already marked trusted, then they are marked trusted also and can
thus be added into the master keyring.

Patches from Mimi Zohar make this usable with the IMA keyrings also.

(3) Remove the date checks on the key used to validate a module signature.

X.509: Remove certificate date checks

It's not reasonable to reject a signature just because the key that it was
generated with is no longer valid datewise - especially if the kernel
hasn't yet managed to set the system clock when the first module is
loaded - so just remove those checks.

(4) Make it simpler to deal with additional X.509 being loaded into the kernel.

KEYS: Load *.x509 files into kernel keyring
KEYS: Have make canonicalise the paths of the X.509 certs better to deduplicate

The builder of the kernel now just places files with the extension ".x509"
into the kernel source or build trees and they're concatenated by the
kernel build and stuffed into the appropriate section.

(5) Add support for userspace kerberos to use keyrings.

KEYS: Add per-user_namespace registers for persistent per-UID kerberos caches
KEYS: Implement a big key type that can save to tmpfs

Fedora went to, by default, storing kerberos tickets and tokens in tmpfs.
We looked at storing it in keyrings instead as that confers certain
advantages such as tickets being automatically deleted after a certain
amount of time and the ability for the kernel to get at these tokens more
easily.

To make this work, two things were needed:

(a) A way for the tickets to persist beyond the lifetime of all a user's
sessions so that cron-driven processes can still use them.

The problem is that a user's session keyrings are deleted when the
session that spawned them logs out and the user's user keyring is
deleted when the UID is deleted (typically when the last log out
happens), so neither of these places is suitable.

I've added a system keyring into which a 'persistent' keyring is
created for each UID on request. Each time a user requests their
persistent keyring, the expiry time on it is set anew. If the user
doesn't ask for it for, say, three days, the keyring is automatically
expired and garbage collected using the existing gc. All the kerberos
tokens it held are then also gc'd.

(b) A key type that can hold really big tickets (up to 1MB in size).

The problem is that Active Directory can return huge tickets with lots
of auxiliary data attached. We don't, however, want to eat up huge
tracts of unswappable kernel space for this, so if the ticket is
greater than a certain size, we create a swappable shmem file and dump
the contents in there and just live with the fact we then have an
inode and a dentry overhead. If the ticket is smaller than that, we
slap it in a kmalloc()'d buffer"

* 'for-linus2' of git://git.kernel.org/pub/scm/linux/kernel/git/jmorris/linux-security: (121 commits)
KEYS: Fix keyring content gc scanner
KEYS: Fix error handling in big_key instantiation
KEYS: Fix UID check in keyctl_get_persistent()
KEYS: The RSA public key algorithm needs to select MPILIB
ima: define '_ima' as a builtin 'trusted' keyring
ima: extend the measurement list to include the file signature
kernel/system_certificate.S: use real contents instead of macro GLOBAL()
KEYS: fix error return code in big_key_instantiate()
KEYS: Fix keyring quota misaccounting on key replacement and unlink
KEYS: Fix a race between negating a key and reading the error set
KEYS: Make BIG_KEYS boolean
apparmor: remove the "task" arg from may_change_ptraced_domain()
apparmor: remove parent task info from audit logging
apparmor: remove tsk field from the apparmor_audit_struct
apparmor: fix capability to not use the current task, during reporting
Smack: Ptrace access check mode
ima: provide hash algo info in the xattr
ima: enable support for larger default filedata hash algorithms
ima: define kernel parameter 'ima_template=' to change configured default
ima: add Kconfig default measurement list template
...

+7729 -2075
+574
Documentation/assoc_array.txt
··· 1 + ======================================== 2 + GENERIC ASSOCIATIVE ARRAY IMPLEMENTATION 3 + ======================================== 4 + 5 + Contents: 6 + 7 + - Overview. 8 + 9 + - The public API. 10 + - Edit script. 11 + - Operations table. 12 + - Manipulation functions. 13 + - Access functions. 14 + - Index key form. 15 + 16 + - Internal workings. 17 + - Basic internal tree layout. 18 + - Shortcuts. 19 + - Splitting and collapsing nodes. 20 + - Non-recursive iteration. 21 + - Simultaneous alteration and iteration. 22 + 23 + 24 + ======== 25 + OVERVIEW 26 + ======== 27 + 28 + This associative array implementation is an object container with the following 29 + properties: 30 + 31 + (1) Objects are opaque pointers. The implementation does not care where they 32 + point (if anywhere) or what they point to (if anything). 33 + 34 + [!] NOTE: Pointers to objects _must_ be zero in the least significant bit. 35 + 36 + (2) Objects do not need to contain linkage blocks for use by the array. This 37 + permits an object to be located in multiple arrays simultaneously. 38 + Rather, the array is made up of metadata blocks that point to objects. 39 + 40 + (3) Objects require index keys to locate them within the array. 41 + 42 + (4) Index keys must be unique. Inserting an object with the same key as one 43 + already in the array will replace the old object. 44 + 45 + (5) Index keys can be of any length and can be of different lengths. 46 + 47 + (6) Index keys should encode the length early on, before any variation due to 48 + length is seen. 49 + 50 + (7) Index keys can include a hash to scatter objects throughout the array. 51 + 52 + (8) The array can iterated over. The objects will not necessarily come out in 53 + key order. 54 + 55 + (9) The array can be iterated over whilst it is being modified, provided the 56 + RCU readlock is being held by the iterator. Note, however, under these 57 + circumstances, some objects may be seen more than once. If this is a 58 + problem, the iterator should lock against modification. Objects will not 59 + be missed, however, unless deleted. 60 + 61 + (10) Objects in the array can be looked up by means of their index key. 62 + 63 + (11) Objects can be looked up whilst the array is being modified, provided the 64 + RCU readlock is being held by the thread doing the look up. 65 + 66 + The implementation uses a tree of 16-pointer nodes internally that are indexed 67 + on each level by nibbles from the index key in the same manner as in a radix 68 + tree. To improve memory efficiency, shortcuts can be emplaced to skip over 69 + what would otherwise be a series of single-occupancy nodes. Further, nodes 70 + pack leaf object pointers into spare space in the node rather than making an 71 + extra branch until as such time an object needs to be added to a full node. 72 + 73 + 74 + ============== 75 + THE PUBLIC API 76 + ============== 77 + 78 + The public API can be found in <linux/assoc_array.h>. The associative array is 79 + rooted on the following structure: 80 + 81 + struct assoc_array { 82 + ... 83 + }; 84 + 85 + The code is selected by enabling CONFIG_ASSOCIATIVE_ARRAY. 86 + 87 + 88 + EDIT SCRIPT 89 + ----------- 90 + 91 + The insertion and deletion functions produce an 'edit script' that can later be 92 + applied to effect the changes without risking ENOMEM. This retains the 93 + preallocated metadata blocks that will be installed in the internal tree and 94 + keeps track of the metadata blocks that will be removed from the tree when the 95 + script is applied. 96 + 97 + This is also used to keep track of dead blocks and dead objects after the 98 + script has been applied so that they can be freed later. The freeing is done 99 + after an RCU grace period has passed - thus allowing access functions to 100 + proceed under the RCU read lock. 101 + 102 + The script appears as outside of the API as a pointer of the type: 103 + 104 + struct assoc_array_edit; 105 + 106 + There are two functions for dealing with the script: 107 + 108 + (1) Apply an edit script. 109 + 110 + void assoc_array_apply_edit(struct assoc_array_edit *edit); 111 + 112 + This will perform the edit functions, interpolating various write barriers 113 + to permit accesses under the RCU read lock to continue. The edit script 114 + will then be passed to call_rcu() to free it and any dead stuff it points 115 + to. 116 + 117 + (2) Cancel an edit script. 118 + 119 + void assoc_array_cancel_edit(struct assoc_array_edit *edit); 120 + 121 + This frees the edit script and all preallocated memory immediately. If 122 + this was for insertion, the new object is _not_ released by this function, 123 + but must rather be released by the caller. 124 + 125 + These functions are guaranteed not to fail. 126 + 127 + 128 + OPERATIONS TABLE 129 + ---------------- 130 + 131 + Various functions take a table of operations: 132 + 133 + struct assoc_array_ops { 134 + ... 135 + }; 136 + 137 + This points to a number of methods, all of which need to be provided: 138 + 139 + (1) Get a chunk of index key from caller data: 140 + 141 + unsigned long (*get_key_chunk)(const void *index_key, int level); 142 + 143 + This should return a chunk of caller-supplied index key starting at the 144 + *bit* position given by the level argument. The level argument will be a 145 + multiple of ASSOC_ARRAY_KEY_CHUNK_SIZE and the function should return 146 + ASSOC_ARRAY_KEY_CHUNK_SIZE bits. No error is possible. 147 + 148 + 149 + (2) Get a chunk of an object's index key. 150 + 151 + unsigned long (*get_object_key_chunk)(const void *object, int level); 152 + 153 + As the previous function, but gets its data from an object in the array 154 + rather than from a caller-supplied index key. 155 + 156 + 157 + (3) See if this is the object we're looking for. 158 + 159 + bool (*compare_object)(const void *object, const void *index_key); 160 + 161 + Compare the object against an index key and return true if it matches and 162 + false if it doesn't. 163 + 164 + 165 + (4) Diff the index keys of two objects. 166 + 167 + int (*diff_objects)(const void *a, const void *b); 168 + 169 + Return the bit position at which the index keys of two objects differ or 170 + -1 if they are the same. 171 + 172 + 173 + (5) Free an object. 174 + 175 + void (*free_object)(void *object); 176 + 177 + Free the specified object. Note that this may be called an RCU grace 178 + period after assoc_array_apply_edit() was called, so synchronize_rcu() may 179 + be necessary on module unloading. 180 + 181 + 182 + MANIPULATION FUNCTIONS 183 + ---------------------- 184 + 185 + There are a number of functions for manipulating an associative array: 186 + 187 + (1) Initialise an associative array. 188 + 189 + void assoc_array_init(struct assoc_array *array); 190 + 191 + This initialises the base structure for an associative array. It can't 192 + fail. 193 + 194 + 195 + (2) Insert/replace an object in an associative array. 196 + 197 + struct assoc_array_edit * 198 + assoc_array_insert(struct assoc_array *array, 199 + const struct assoc_array_ops *ops, 200 + const void *index_key, 201 + void *object); 202 + 203 + This inserts the given object into the array. Note that the least 204 + significant bit of the pointer must be zero as it's used to type-mark 205 + pointers internally. 206 + 207 + If an object already exists for that key then it will be replaced with the 208 + new object and the old one will be freed automatically. 209 + 210 + The index_key argument should hold index key information and is 211 + passed to the methods in the ops table when they are called. 212 + 213 + This function makes no alteration to the array itself, but rather returns 214 + an edit script that must be applied. -ENOMEM is returned in the case of 215 + an out-of-memory error. 216 + 217 + The caller should lock exclusively against other modifiers of the array. 218 + 219 + 220 + (3) Delete an object from an associative array. 221 + 222 + struct assoc_array_edit * 223 + assoc_array_delete(struct assoc_array *array, 224 + const struct assoc_array_ops *ops, 225 + const void *index_key); 226 + 227 + This deletes an object that matches the specified data from the array. 228 + 229 + The index_key argument should hold index key information and is 230 + passed to the methods in the ops table when they are called. 231 + 232 + This function makes no alteration to the array itself, but rather returns 233 + an edit script that must be applied. -ENOMEM is returned in the case of 234 + an out-of-memory error. NULL will be returned if the specified object is 235 + not found within the array. 236 + 237 + The caller should lock exclusively against other modifiers of the array. 238 + 239 + 240 + (4) Delete all objects from an associative array. 241 + 242 + struct assoc_array_edit * 243 + assoc_array_clear(struct assoc_array *array, 244 + const struct assoc_array_ops *ops); 245 + 246 + This deletes all the objects from an associative array and leaves it 247 + completely empty. 248 + 249 + This function makes no alteration to the array itself, but rather returns 250 + an edit script that must be applied. -ENOMEM is returned in the case of 251 + an out-of-memory error. 252 + 253 + The caller should lock exclusively against other modifiers of the array. 254 + 255 + 256 + (5) Destroy an associative array, deleting all objects. 257 + 258 + void assoc_array_destroy(struct assoc_array *array, 259 + const struct assoc_array_ops *ops); 260 + 261 + This destroys the contents of the associative array and leaves it 262 + completely empty. It is not permitted for another thread to be traversing 263 + the array under the RCU read lock at the same time as this function is 264 + destroying it as no RCU deferral is performed on memory release - 265 + something that would require memory to be allocated. 266 + 267 + The caller should lock exclusively against other modifiers and accessors 268 + of the array. 269 + 270 + 271 + (6) Garbage collect an associative array. 272 + 273 + int assoc_array_gc(struct assoc_array *array, 274 + const struct assoc_array_ops *ops, 275 + bool (*iterator)(void *object, void *iterator_data), 276 + void *iterator_data); 277 + 278 + This iterates over the objects in an associative array and passes each one 279 + to iterator(). If iterator() returns true, the object is kept. If it 280 + returns false, the object will be freed. If the iterator() function 281 + returns true, it must perform any appropriate refcount incrementing on the 282 + object before returning. 283 + 284 + The internal tree will be packed down if possible as part of the iteration 285 + to reduce the number of nodes in it. 286 + 287 + The iterator_data is passed directly to iterator() and is otherwise 288 + ignored by the function. 289 + 290 + The function will return 0 if successful and -ENOMEM if there wasn't 291 + enough memory. 292 + 293 + It is possible for other threads to iterate over or search the array under 294 + the RCU read lock whilst this function is in progress. The caller should 295 + lock exclusively against other modifiers of the array. 296 + 297 + 298 + ACCESS FUNCTIONS 299 + ---------------- 300 + 301 + There are two functions for accessing an associative array: 302 + 303 + (1) Iterate over all the objects in an associative array. 304 + 305 + int assoc_array_iterate(const struct assoc_array *array, 306 + int (*iterator)(const void *object, 307 + void *iterator_data), 308 + void *iterator_data); 309 + 310 + This passes each object in the array to the iterator callback function. 311 + iterator_data is private data for that function. 312 + 313 + This may be used on an array at the same time as the array is being 314 + modified, provided the RCU read lock is held. Under such circumstances, 315 + it is possible for the iteration function to see some objects twice. If 316 + this is a problem, then modification should be locked against. The 317 + iteration algorithm should not, however, miss any objects. 318 + 319 + The function will return 0 if no objects were in the array or else it will 320 + return the result of the last iterator function called. Iteration stops 321 + immediately if any call to the iteration function results in a non-zero 322 + return. 323 + 324 + 325 + (2) Find an object in an associative array. 326 + 327 + void *assoc_array_find(const struct assoc_array *array, 328 + const struct assoc_array_ops *ops, 329 + const void *index_key); 330 + 331 + This walks through the array's internal tree directly to the object 332 + specified by the index key.. 333 + 334 + This may be used on an array at the same time as the array is being 335 + modified, provided the RCU read lock is held. 336 + 337 + The function will return the object if found (and set *_type to the object 338 + type) or will return NULL if the object was not found. 339 + 340 + 341 + INDEX KEY FORM 342 + -------------- 343 + 344 + The index key can be of any form, but since the algorithms aren't told how long 345 + the key is, it is strongly recommended that the index key includes its length 346 + very early on before any variation due to the length would have an effect on 347 + comparisons. 348 + 349 + This will cause leaves with different length keys to scatter away from each 350 + other - and those with the same length keys to cluster together. 351 + 352 + It is also recommended that the index key begin with a hash of the rest of the 353 + key to maximise scattering throughout keyspace. 354 + 355 + The better the scattering, the wider and lower the internal tree will be. 356 + 357 + Poor scattering isn't too much of a problem as there are shortcuts and nodes 358 + can contain mixtures of leaves and metadata pointers. 359 + 360 + The index key is read in chunks of machine word. Each chunk is subdivided into 361 + one nibble (4 bits) per level, so on a 32-bit CPU this is good for 8 levels and 362 + on a 64-bit CPU, 16 levels. Unless the scattering is really poor, it is 363 + unlikely that more than one word of any particular index key will have to be 364 + used. 365 + 366 + 367 + ================= 368 + INTERNAL WORKINGS 369 + ================= 370 + 371 + The associative array data structure has an internal tree. This tree is 372 + constructed of two types of metadata blocks: nodes and shortcuts. 373 + 374 + A node is an array of slots. Each slot can contain one of four things: 375 + 376 + (*) A NULL pointer, indicating that the slot is empty. 377 + 378 + (*) A pointer to an object (a leaf). 379 + 380 + (*) A pointer to a node at the next level. 381 + 382 + (*) A pointer to a shortcut. 383 + 384 + 385 + BASIC INTERNAL TREE LAYOUT 386 + -------------------------- 387 + 388 + Ignoring shortcuts for the moment, the nodes form a multilevel tree. The index 389 + key space is strictly subdivided by the nodes in the tree and nodes occur on 390 + fixed levels. For example: 391 + 392 + Level: 0 1 2 3 393 + =============== =============== =============== =============== 394 + NODE D 395 + NODE B NODE C +------>+---+ 396 + +------>+---+ +------>+---+ | | 0 | 397 + NODE A | | 0 | | | 0 | | +---+ 398 + +---+ | +---+ | +---+ | : : 399 + | 0 | | : : | : : | +---+ 400 + +---+ | +---+ | +---+ | | f | 401 + | 1 |---+ | 3 |---+ | 7 |---+ +---+ 402 + +---+ +---+ +---+ 403 + : : : : | 8 |---+ 404 + +---+ +---+ +---+ | NODE E 405 + | e |---+ | f | : : +------>+---+ 406 + +---+ | +---+ +---+ | 0 | 407 + | f | | | f | +---+ 408 + +---+ | +---+ : : 409 + | NODE F +---+ 410 + +------>+---+ | f | 411 + | 0 | NODE G +---+ 412 + +---+ +------>+---+ 413 + : : | | 0 | 414 + +---+ | +---+ 415 + | 6 |---+ : : 416 + +---+ +---+ 417 + : : | f | 418 + +---+ +---+ 419 + | f | 420 + +---+ 421 + 422 + In the above example, there are 7 nodes (A-G), each with 16 slots (0-f). 423 + Assuming no other meta data nodes in the tree, the key space is divided thusly: 424 + 425 + KEY PREFIX NODE 426 + ========== ==== 427 + 137* D 428 + 138* E 429 + 13[0-69-f]* C 430 + 1[0-24-f]* B 431 + e6* G 432 + e[0-57-f]* F 433 + [02-df]* A 434 + 435 + So, for instance, keys with the following example index keys will be found in 436 + the appropriate nodes: 437 + 438 + INDEX KEY PREFIX NODE 439 + =============== ======= ==== 440 + 13694892892489 13 C 441 + 13795289025897 137 D 442 + 13889dde88793 138 E 443 + 138bbb89003093 138 E 444 + 1394879524789 12 C 445 + 1458952489 1 B 446 + 9431809de993ba - A 447 + b4542910809cd - A 448 + e5284310def98 e F 449 + e68428974237 e6 G 450 + e7fffcbd443 e F 451 + f3842239082 - A 452 + 453 + To save memory, if a node can hold all the leaves in its portion of keyspace, 454 + then the node will have all those leaves in it and will not have any metadata 455 + pointers - even if some of those leaves would like to be in the same slot. 456 + 457 + A node can contain a heterogeneous mix of leaves and metadata pointers. 458 + Metadata pointers must be in the slots that match their subdivisions of key 459 + space. The leaves can be in any slot not occupied by a metadata pointer. It 460 + is guaranteed that none of the leaves in a node will match a slot occupied by a 461 + metadata pointer. If the metadata pointer is there, any leaf whose key matches 462 + the metadata key prefix must be in the subtree that the metadata pointer points 463 + to. 464 + 465 + In the above example list of index keys, node A will contain: 466 + 467 + SLOT CONTENT INDEX KEY (PREFIX) 468 + ==== =============== ================== 469 + 1 PTR TO NODE B 1* 470 + any LEAF 9431809de993ba 471 + any LEAF b4542910809cd 472 + e PTR TO NODE F e* 473 + any LEAF f3842239082 474 + 475 + and node B: 476 + 477 + 3 PTR TO NODE C 13* 478 + any LEAF 1458952489 479 + 480 + 481 + SHORTCUTS 482 + --------- 483 + 484 + Shortcuts are metadata records that jump over a piece of keyspace. A shortcut 485 + is a replacement for a series of single-occupancy nodes ascending through the 486 + levels. Shortcuts exist to save memory and to speed up traversal. 487 + 488 + It is possible for the root of the tree to be a shortcut - say, for example, 489 + the tree contains at least 17 nodes all with key prefix '1111'. The insertion 490 + algorithm will insert a shortcut to skip over the '1111' keyspace in a single 491 + bound and get to the fourth level where these actually become different. 492 + 493 + 494 + SPLITTING AND COLLAPSING NODES 495 + ------------------------------ 496 + 497 + Each node has a maximum capacity of 16 leaves and metadata pointers. If the 498 + insertion algorithm finds that it is trying to insert a 17th object into a 499 + node, that node will be split such that at least two leaves that have a common 500 + key segment at that level end up in a separate node rooted on that slot for 501 + that common key segment. 502 + 503 + If the leaves in a full node and the leaf that is being inserted are 504 + sufficiently similar, then a shortcut will be inserted into the tree. 505 + 506 + When the number of objects in the subtree rooted at a node falls to 16 or 507 + fewer, then the subtree will be collapsed down to a single node - and this will 508 + ripple towards the root if possible. 509 + 510 + 511 + NON-RECURSIVE ITERATION 512 + ----------------------- 513 + 514 + Each node and shortcut contains a back pointer to its parent and the number of 515 + slot in that parent that points to it. None-recursive iteration uses these to 516 + proceed rootwards through the tree, going to the parent node, slot N + 1 to 517 + make sure progress is made without the need for a stack. 518 + 519 + The backpointers, however, make simultaneous alteration and iteration tricky. 520 + 521 + 522 + SIMULTANEOUS ALTERATION AND ITERATION 523 + ------------------------------------- 524 + 525 + There are a number of cases to consider: 526 + 527 + (1) Simple insert/replace. This involves simply replacing a NULL or old 528 + matching leaf pointer with the pointer to the new leaf after a barrier. 529 + The metadata blocks don't change otherwise. An old leaf won't be freed 530 + until after the RCU grace period. 531 + 532 + (2) Simple delete. This involves just clearing an old matching leaf. The 533 + metadata blocks don't change otherwise. The old leaf won't be freed until 534 + after the RCU grace period. 535 + 536 + (3) Insertion replacing part of a subtree that we haven't yet entered. This 537 + may involve replacement of part of that subtree - but that won't affect 538 + the iteration as we won't have reached the pointer to it yet and the 539 + ancestry blocks are not replaced (the layout of those does not change). 540 + 541 + (4) Insertion replacing nodes that we're actively processing. This isn't a 542 + problem as we've passed the anchoring pointer and won't switch onto the 543 + new layout until we follow the back pointers - at which point we've 544 + already examined the leaves in the replaced node (we iterate over all the 545 + leaves in a node before following any of its metadata pointers). 546 + 547 + We might, however, re-see some leaves that have been split out into a new 548 + branch that's in a slot further along than we were at. 549 + 550 + (5) Insertion replacing nodes that we're processing a dependent branch of. 551 + This won't affect us until we follow the back pointers. Similar to (4). 552 + 553 + (6) Deletion collapsing a branch under us. This doesn't affect us because the 554 + back pointers will get us back to the parent of the new node before we 555 + could see the new node. The entire collapsed subtree is thrown away 556 + unchanged - and will still be rooted on the same slot, so we shouldn't 557 + process it a second time as we'll go back to slot + 1. 558 + 559 + Note: 560 + 561 + (*) Under some circumstances, we need to simultaneously change the parent 562 + pointer and the parent slot pointer on a node (say, for example, we 563 + inserted another node before it and moved it up a level). We cannot do 564 + this without locking against a read - so we have to replace that node too. 565 + 566 + However, when we're changing a shortcut into a node this isn't a problem 567 + as shortcuts only have one slot and so the parent slot number isn't used 568 + when traversing backwards over one. This means that it's okay to change 569 + the slot number first - provided suitable barriers are used to make sure 570 + the parent slot number is read after the back pointer. 571 + 572 + Obsolete blocks and leaves are freed up after an RCU grace period has passed, 573 + so as long as anyone doing walking or iteration holds the RCU read lock, the 574 + old superstructure should not go away on them.
+3
Documentation/devicetree/bindings/i2c/trivial-devices.txt
··· 15 15 adt7461 +/-1C TDM Extended Temp Range I.C 16 16 at,24c08 i2c serial eeprom (24cxx) 17 17 atmel,24c02 i2c serial eeprom (24cxx) 18 + atmel,at97sc3204t i2c trusted platform module (TPM) 18 19 catalyst,24c32 i2c serial eeprom 19 20 dallas,ds1307 64 x 8, Serial, I2C Real-Time Clock 20 21 dallas,ds1338 I2C RTC with 56-Byte NV RAM ··· 45 44 national,lm75 I2C TEMP SENSOR 46 45 national,lm80 Serial Interface ACPI-Compatible Microprocessor System Hardware Monitor 47 46 national,lm92 ±0.33°C Accurate, 12-Bit + Sign Temperature Sensor and Thermal Window Comparator with Two-Wire Interface 47 + nuvoton,npct501 i2c trusted platform module (TPM) 48 48 nxp,pca9556 Octal SMBus and I2C registered interface 49 49 nxp,pca9557 8-bit I2C-bus and SMBus I/O port with reset 50 50 nxp,pcf8563 Real-time clock/calendar ··· 63 61 ti,tsc2003 I2C Touch-Screen Controller 64 62 ti,tmp102 Low Power Digital Temperature Sensor with SMBUS/Two Wire Serial Interface 65 63 ti,tmp275 Digital Temperature Sensor 64 + winbond,wpct301 i2c trusted platform module (TPM)
+10 -1
Documentation/kernel-parameters.txt
··· 1190 1190 owned by uid=0. 1191 1191 1192 1192 ima_hash= [IMA] 1193 - Format: { "sha1" | "md5" } 1193 + Format: { md5 | sha1 | rmd160 | sha256 | sha384 1194 + | sha512 | ... } 1194 1195 default: "sha1" 1196 + 1197 + The list of supported hash algorithms is defined 1198 + in crypto/hash_info.h. 1195 1199 1196 1200 ima_tcb [IMA] 1197 1201 Load a policy which meets the needs of the Trusted 1198 1202 Computing Base. This means IMA will measure all 1199 1203 programs exec'd, files mmap'd for exec, and all files 1200 1204 opened for read by uid=0. 1205 + 1206 + ima_template= [IMA] 1207 + Select one of defined IMA measurements template formats. 1208 + Formats: { "ima" | "ima-ng" } 1209 + Default: "ima-ng" 1201 1210 1202 1211 init= [KNL] 1203 1212 Format: <full_path>
+2
Documentation/security/00-INDEX
··· 22 22 - description of the kernel key retention service. 23 23 tomoyo.txt 24 24 - documentation on the TOMOYO Linux Security Module. 25 + IMA-templates.txt 26 + - documentation on the template management mechanism for IMA.
+87
Documentation/security/IMA-templates.txt
··· 1 + IMA Template Management Mechanism 2 + 3 + 4 + ==== INTRODUCTION ==== 5 + 6 + The original 'ima' template is fixed length, containing the filedata hash 7 + and pathname. The filedata hash is limited to 20 bytes (md5/sha1). 8 + The pathname is a null terminated string, limited to 255 characters. 9 + To overcome these limitations and to add additional file metadata, it is 10 + necessary to extend the current version of IMA by defining additional 11 + templates. For example, information that could be possibly reported are 12 + the inode UID/GID or the LSM labels either of the inode and of the process 13 + that is accessing it. 14 + 15 + However, the main problem to introduce this feature is that, each time 16 + a new template is defined, the functions that generate and display 17 + the measurements list would include the code for handling a new format 18 + and, thus, would significantly grow over the time. 19 + 20 + The proposed solution solves this problem by separating the template 21 + management from the remaining IMA code. The core of this solution is the 22 + definition of two new data structures: a template descriptor, to determine 23 + which information should be included in the measurement list; a template 24 + field, to generate and display data of a given type. 25 + 26 + Managing templates with these structures is very simple. To support 27 + a new data type, developers define the field identifier and implement 28 + two functions, init() and show(), respectively to generate and display 29 + measurement entries. Defining a new template descriptor requires 30 + specifying the template format, a string of field identifiers separated 31 + by the '|' character. While in the current implementation it is possible 32 + to define new template descriptors only by adding their definition in the 33 + template specific code (ima_template.c), in a future version it will be 34 + possible to register a new template on a running kernel by supplying to IMA 35 + the desired format string. In this version, IMA initializes at boot time 36 + all defined template descriptors by translating the format into an array 37 + of template fields structures taken from the set of the supported ones. 38 + 39 + After the initialization step, IMA will call ima_alloc_init_template() 40 + (new function defined within the patches for the new template management 41 + mechanism) to generate a new measurement entry by using the template 42 + descriptor chosen through the kernel configuration or through the newly 43 + introduced 'ima_template=' kernel command line parameter. It is during this 44 + phase that the advantages of the new architecture are clearly shown: 45 + the latter function will not contain specific code to handle a given template 46 + but, instead, it simply calls the init() method of the template fields 47 + associated to the chosen template descriptor and store the result (pointer 48 + to allocated data and data length) in the measurement entry structure. 49 + 50 + The same mechanism is employed to display measurements entries. 51 + The functions ima[_ascii]_measurements_show() retrieve, for each entry, 52 + the template descriptor used to produce that entry and call the show() 53 + method for each item of the array of template fields structures. 54 + 55 + 56 + 57 + ==== SUPPORTED TEMPLATE FIELDS AND DESCRIPTORS ==== 58 + 59 + In the following, there is the list of supported template fields 60 + ('<identifier>': description), that can be used to define new template 61 + descriptors by adding their identifier to the format string 62 + (support for more data types will be added later): 63 + 64 + - 'd': the digest of the event (i.e. the digest of a measured file), 65 + calculated with the SHA1 or MD5 hash algorithm; 66 + - 'n': the name of the event (i.e. the file name), with size up to 255 bytes; 67 + - 'd-ng': the digest of the event, calculated with an arbitrary hash 68 + algorithm (field format: [<hash algo>:]digest, where the digest 69 + prefix is shown only if the hash algorithm is not SHA1 or MD5); 70 + - 'n-ng': the name of the event, without size limitations. 71 + 72 + 73 + Below, there is the list of defined template descriptors: 74 + - "ima": its format is 'd|n'; 75 + - "ima-ng" (default): its format is 'd-ng|n-ng'. 76 + 77 + 78 + 79 + ==== USE ==== 80 + 81 + To specify the template descriptor to be used to generate measurement entries, 82 + currently the following methods are supported: 83 + 84 + - select a template descriptor among those supported in the kernel 85 + configuration ('ima-ng' is the default choice); 86 + - specify a template descriptor name from the kernel command line through 87 + the 'ima_template=' parameter.
+11 -9
Documentation/security/keys.txt
··· 865 865 calling processes has a searchable link to the key from one of its 866 866 keyrings. There are three functions for dealing with these: 867 867 868 - key_ref_t make_key_ref(const struct key *key, 869 - unsigned long possession); 868 + key_ref_t make_key_ref(const struct key *key, bool possession); 870 869 871 870 struct key *key_ref_to_ptr(const key_ref_t key_ref); 872 871 873 - unsigned long is_key_possessed(const key_ref_t key_ref); 872 + bool is_key_possessed(const key_ref_t key_ref); 874 873 875 874 The first function constructs a key reference from a key pointer and 876 - possession information (which must be 0 or 1 and not any other value). 875 + possession information (which must be true or false). 877 876 878 877 The second function retrieves the key pointer from a reference and the 879 878 third retrieves the possession flag. ··· 960 961 the argument will not be parsed. 961 962 962 963 963 - (*) Extra references can be made to a key by calling the following function: 964 + (*) Extra references can be made to a key by calling one of the following 965 + functions: 964 966 967 + struct key *__key_get(struct key *key); 965 968 struct key *key_get(struct key *key); 966 969 967 - These need to be disposed of by calling key_put() when they've been 968 - finished with. The key pointer passed in will be returned. If the pointer 969 - is NULL or CONFIG_KEYS is not set then the key will not be dereferenced and 970 - no increment will take place. 970 + Keys so references will need to be disposed of by calling key_put() when 971 + they've been finished with. The key pointer passed in will be returned. 972 + 973 + In the case of key_get(), if the pointer is NULL or CONFIG_KEYS is not set 974 + then the key will not be dereferenced and no increment will take place. 971 975 972 976 973 977 (*) A key's serial number can be obtained by calling:
+3 -1
MAINTAINERS
··· 7515 7515 M: Stephen Smalley <sds@tycho.nsa.gov> 7516 7516 M: James Morris <james.l.morris@oracle.com> 7517 7517 M: Eric Paris <eparis@parisplace.org> 7518 + M: Paul Moore <paul@paul-moore.com> 7518 7519 L: selinux@tycho.nsa.gov (subscribers-only, general discussion) 7519 7520 W: http://selinuxproject.org 7520 - T: git git://git.infradead.org/users/eparis/selinux.git 7521 + T: git git://git.infradead.org/users/pcmoore/selinux 7521 7522 S: Supported 7522 7523 F: include/linux/selinux* 7523 7524 F: security/selinux/ ··· 8665 8664 TPM DEVICE DRIVER 8666 8665 M: Leonidas Da Silva Barbosa <leosilva@linux.vnet.ibm.com> 8667 8666 M: Ashley Lai <ashley@ashleylai.com> 8667 + M: Peter Huewe <peterhuewe@gmx.de> 8668 8668 M: Rajiv Andrade <mail@srajiv.net> 8669 8669 W: http://tpmdd.sourceforge.net 8670 8670 M: Marcel Selhorst <tpmdd@selhorst.net>
+3
crypto/Kconfig
··· 1402 1402 This option enables the user-spaces interface for symmetric 1403 1403 key cipher algorithms. 1404 1404 1405 + config CRYPTO_HASH_INFO 1406 + bool 1407 + 1405 1408 source "drivers/crypto/Kconfig" 1406 1409 source crypto/asymmetric_keys/Kconfig 1407 1410
+1
crypto/Makefile
··· 104 104 obj-$(CONFIG_XOR_BLOCKS) += xor.o 105 105 obj-$(CONFIG_ASYNC_CORE) += async_tx/ 106 106 obj-$(CONFIG_ASYMMETRIC_KEY_TYPE) += asymmetric_keys/ 107 + obj-$(CONFIG_CRYPTO_HASH_INFO) += hash_info.o
+3 -1
crypto/asymmetric_keys/Kconfig
··· 12 12 config ASYMMETRIC_PUBLIC_KEY_SUBTYPE 13 13 tristate "Asymmetric public-key crypto algorithm subtype" 14 14 select MPILIB 15 + select PUBLIC_KEY_ALGO_RSA 16 + select CRYPTO_HASH_INFO 15 17 help 16 18 This option provides support for asymmetric public key type handling. 17 19 If signature generation and/or verification are to be used, ··· 22 20 23 21 config PUBLIC_KEY_ALGO_RSA 24 22 tristate "RSA public-key algorithm" 25 - depends on ASYMMETRIC_PUBLIC_KEY_SUBTYPE 26 23 select MPILIB_EXTRA 24 + select MPILIB 27 25 help 28 26 This option enables support for the RSA algorithm (PKCS#1, RFC3447). 29 27
+1
crypto/asymmetric_keys/asymmetric_type.c
··· 209 209 .match = asymmetric_key_match, 210 210 .destroy = asymmetric_key_destroy, 211 211 .describe = asymmetric_key_describe, 212 + .def_lookup_type = KEYRING_SEARCH_LOOKUP_ITERATE, 212 213 }; 213 214 EXPORT_SYMBOL_GPL(key_type_asymmetric); 214 215
+44 -24
crypto/asymmetric_keys/public_key.c
··· 22 22 23 23 MODULE_LICENSE("GPL"); 24 24 25 - const char *const pkey_algo[PKEY_ALGO__LAST] = { 25 + const char *const pkey_algo_name[PKEY_ALGO__LAST] = { 26 26 [PKEY_ALGO_DSA] = "DSA", 27 27 [PKEY_ALGO_RSA] = "RSA", 28 28 }; 29 + EXPORT_SYMBOL_GPL(pkey_algo_name); 30 + 31 + const struct public_key_algorithm *pkey_algo[PKEY_ALGO__LAST] = { 32 + #if defined(CONFIG_PUBLIC_KEY_ALGO_RSA) || \ 33 + defined(CONFIG_PUBLIC_KEY_ALGO_RSA_MODULE) 34 + [PKEY_ALGO_RSA] = &RSA_public_key_algorithm, 35 + #endif 36 + }; 29 37 EXPORT_SYMBOL_GPL(pkey_algo); 30 38 31 - const char *const pkey_hash_algo[PKEY_HASH__LAST] = { 32 - [PKEY_HASH_MD4] = "md4", 33 - [PKEY_HASH_MD5] = "md5", 34 - [PKEY_HASH_SHA1] = "sha1", 35 - [PKEY_HASH_RIPE_MD_160] = "rmd160", 36 - [PKEY_HASH_SHA256] = "sha256", 37 - [PKEY_HASH_SHA384] = "sha384", 38 - [PKEY_HASH_SHA512] = "sha512", 39 - [PKEY_HASH_SHA224] = "sha224", 40 - }; 41 - EXPORT_SYMBOL_GPL(pkey_hash_algo); 42 - 43 - const char *const pkey_id_type[PKEY_ID_TYPE__LAST] = { 39 + const char *const pkey_id_type_name[PKEY_ID_TYPE__LAST] = { 44 40 [PKEY_ID_PGP] = "PGP", 45 41 [PKEY_ID_X509] = "X509", 46 42 }; 47 - EXPORT_SYMBOL_GPL(pkey_id_type); 43 + EXPORT_SYMBOL_GPL(pkey_id_type_name); 48 44 49 45 /* 50 46 * Provide a part of a description of the key for /proc/keys. ··· 52 56 53 57 if (key) 54 58 seq_printf(m, "%s.%s", 55 - pkey_id_type[key->id_type], key->algo->name); 59 + pkey_id_type_name[key->id_type], key->algo->name); 56 60 } 57 61 58 62 /* ··· 74 78 /* 75 79 * Verify a signature using a public key. 76 80 */ 77 - static int public_key_verify_signature(const struct key *key, 78 - const struct public_key_signature *sig) 81 + int public_key_verify_signature(const struct public_key *pk, 82 + const struct public_key_signature *sig) 79 83 { 80 - const struct public_key *pk = key->payload.data; 84 + const struct public_key_algorithm *algo; 81 85 82 - if (!pk->algo->verify_signature) 86 + BUG_ON(!pk); 87 + BUG_ON(!pk->mpi[0]); 88 + BUG_ON(!pk->mpi[1]); 89 + BUG_ON(!sig); 90 + BUG_ON(!sig->digest); 91 + BUG_ON(!sig->mpi[0]); 92 + 93 + algo = pk->algo; 94 + if (!algo) { 95 + if (pk->pkey_algo >= PKEY_ALGO__LAST) 96 + return -ENOPKG; 97 + algo = pkey_algo[pk->pkey_algo]; 98 + if (!algo) 99 + return -ENOPKG; 100 + } 101 + 102 + if (!algo->verify_signature) 83 103 return -ENOTSUPP; 84 104 85 - if (sig->nr_mpi != pk->algo->n_sig_mpi) { 105 + if (sig->nr_mpi != algo->n_sig_mpi) { 86 106 pr_debug("Signature has %u MPI not %u\n", 87 - sig->nr_mpi, pk->algo->n_sig_mpi); 107 + sig->nr_mpi, algo->n_sig_mpi); 88 108 return -EINVAL; 89 109 } 90 110 91 - return pk->algo->verify_signature(pk, sig); 111 + return algo->verify_signature(pk, sig); 112 + } 113 + EXPORT_SYMBOL_GPL(public_key_verify_signature); 114 + 115 + static int public_key_verify_signature_2(const struct key *key, 116 + const struct public_key_signature *sig) 117 + { 118 + const struct public_key *pk = key->payload.data; 119 + return public_key_verify_signature(pk, sig); 92 120 } 93 121 94 122 /* ··· 123 103 .name = "public_key", 124 104 .describe = public_key_describe, 125 105 .destroy = public_key_destroy, 126 - .verify_signature = public_key_verify_signature, 106 + .verify_signature = public_key_verify_signature_2, 127 107 }; 128 108 EXPORT_SYMBOL_GPL(public_key_subtype);
+6
crypto/asymmetric_keys/public_key.h
··· 28 28 }; 29 29 30 30 extern const struct public_key_algorithm RSA_public_key_algorithm; 31 + 32 + /* 33 + * public_key.c 34 + */ 35 + extern int public_key_verify_signature(const struct public_key *pk, 36 + const struct public_key_signature *sig);
+7 -7
crypto/asymmetric_keys/rsa.c
··· 73 73 size_t size; 74 74 } RSA_ASN1_templates[PKEY_HASH__LAST] = { 75 75 #define _(X) { RSA_digest_info_##X, sizeof(RSA_digest_info_##X) } 76 - [PKEY_HASH_MD5] = _(MD5), 77 - [PKEY_HASH_SHA1] = _(SHA1), 78 - [PKEY_HASH_RIPE_MD_160] = _(RIPE_MD_160), 79 - [PKEY_HASH_SHA256] = _(SHA256), 80 - [PKEY_HASH_SHA384] = _(SHA384), 81 - [PKEY_HASH_SHA512] = _(SHA512), 82 - [PKEY_HASH_SHA224] = _(SHA224), 76 + [HASH_ALGO_MD5] = _(MD5), 77 + [HASH_ALGO_SHA1] = _(SHA1), 78 + [HASH_ALGO_RIPE_MD_160] = _(RIPE_MD_160), 79 + [HASH_ALGO_SHA256] = _(SHA256), 80 + [HASH_ALGO_SHA384] = _(SHA384), 81 + [HASH_ALGO_SHA512] = _(SHA512), 82 + [HASH_ALGO_SHA224] = _(SHA224), 83 83 #undef _ 84 84 }; 85 85
+19 -16
crypto/asymmetric_keys/x509_cert_parser.c
··· 47 47 kfree(cert->subject); 48 48 kfree(cert->fingerprint); 49 49 kfree(cert->authority); 50 + kfree(cert->sig.digest); 51 + mpi_free(cert->sig.rsa.s); 50 52 kfree(cert); 51 53 } 52 54 } ··· 154 152 return -ENOPKG; /* Unsupported combination */ 155 153 156 154 case OID_md4WithRSAEncryption: 157 - ctx->cert->sig_hash_algo = PKEY_HASH_MD5; 158 - ctx->cert->sig_pkey_algo = PKEY_ALGO_RSA; 155 + ctx->cert->sig.pkey_hash_algo = HASH_ALGO_MD5; 156 + ctx->cert->sig.pkey_algo = PKEY_ALGO_RSA; 159 157 break; 160 158 161 159 case OID_sha1WithRSAEncryption: 162 - ctx->cert->sig_hash_algo = PKEY_HASH_SHA1; 163 - ctx->cert->sig_pkey_algo = PKEY_ALGO_RSA; 160 + ctx->cert->sig.pkey_hash_algo = HASH_ALGO_SHA1; 161 + ctx->cert->sig.pkey_algo = PKEY_ALGO_RSA; 164 162 break; 165 163 166 164 case OID_sha256WithRSAEncryption: 167 - ctx->cert->sig_hash_algo = PKEY_HASH_SHA256; 168 - ctx->cert->sig_pkey_algo = PKEY_ALGO_RSA; 165 + ctx->cert->sig.pkey_hash_algo = HASH_ALGO_SHA256; 166 + ctx->cert->sig.pkey_algo = PKEY_ALGO_RSA; 169 167 break; 170 168 171 169 case OID_sha384WithRSAEncryption: 172 - ctx->cert->sig_hash_algo = PKEY_HASH_SHA384; 173 - ctx->cert->sig_pkey_algo = PKEY_ALGO_RSA; 170 + ctx->cert->sig.pkey_hash_algo = HASH_ALGO_SHA384; 171 + ctx->cert->sig.pkey_algo = PKEY_ALGO_RSA; 174 172 break; 175 173 176 174 case OID_sha512WithRSAEncryption: 177 - ctx->cert->sig_hash_algo = PKEY_HASH_SHA512; 178 - ctx->cert->sig_pkey_algo = PKEY_ALGO_RSA; 175 + ctx->cert->sig.pkey_hash_algo = HASH_ALGO_SHA512; 176 + ctx->cert->sig.pkey_algo = PKEY_ALGO_RSA; 179 177 break; 180 178 181 179 case OID_sha224WithRSAEncryption: 182 - ctx->cert->sig_hash_algo = PKEY_HASH_SHA224; 183 - ctx->cert->sig_pkey_algo = PKEY_ALGO_RSA; 180 + ctx->cert->sig.pkey_hash_algo = HASH_ALGO_SHA224; 181 + ctx->cert->sig.pkey_algo = PKEY_ALGO_RSA; 184 182 break; 185 183 } 186 184 ··· 205 203 return -EINVAL; 206 204 } 207 205 208 - ctx->cert->sig = value; 209 - ctx->cert->sig_size = vlen; 206 + ctx->cert->raw_sig = value; 207 + ctx->cert->raw_sig_size = vlen; 210 208 return 0; 211 209 } 212 210 ··· 345 343 if (ctx->last_oid != OID_rsaEncryption) 346 344 return -ENOPKG; 347 345 348 - /* There seems to be an extraneous 0 byte on the front of the data */ 349 - ctx->cert->pkey_algo = PKEY_ALGO_RSA; 346 + ctx->cert->pub->pkey_algo = PKEY_ALGO_RSA; 347 + 348 + /* Discard the BIT STRING metadata */ 350 349 ctx->key = value + 1; 351 350 ctx->key_size = vlen - 1; 352 351 return 0;
+12 -6
crypto/asymmetric_keys/x509_parser.h
··· 9 9 * 2 of the Licence, or (at your option) any later version. 10 10 */ 11 11 12 + #include <linux/time.h> 12 13 #include <crypto/public_key.h> 13 14 14 15 struct x509_certificate { ··· 21 20 char *authority; /* Authority key fingerprint as hex */ 22 21 struct tm valid_from; 23 22 struct tm valid_to; 24 - enum pkey_algo pkey_algo : 8; /* Public key algorithm */ 25 - enum pkey_algo sig_pkey_algo : 8; /* Signature public key algorithm */ 26 - enum pkey_hash_algo sig_hash_algo : 8; /* Signature hash algorithm */ 27 23 const void *tbs; /* Signed data */ 28 - size_t tbs_size; /* Size of signed data */ 29 - const void *sig; /* Signature data */ 30 - size_t sig_size; /* Size of sigature */ 24 + unsigned tbs_size; /* Size of signed data */ 25 + unsigned raw_sig_size; /* Size of sigature */ 26 + const void *raw_sig; /* Signature data */ 27 + struct public_key_signature sig; /* Signature parameters */ 31 28 }; 32 29 33 30 /* ··· 33 34 */ 34 35 extern void x509_free_certificate(struct x509_certificate *cert); 35 36 extern struct x509_certificate *x509_cert_parse(const void *data, size_t datalen); 37 + 38 + /* 39 + * x509_public_key.c 40 + */ 41 + extern int x509_get_sig_params(struct x509_certificate *cert); 42 + extern int x509_check_signature(const struct public_key *pub, 43 + struct x509_certificate *cert);
+149 -91
crypto/asymmetric_keys/x509_public_key.c
··· 18 18 #include <linux/asn1_decoder.h> 19 19 #include <keys/asymmetric-subtype.h> 20 20 #include <keys/asymmetric-parser.h> 21 + #include <keys/system_keyring.h> 21 22 #include <crypto/hash.h> 22 23 #include "asymmetric_keys.h" 23 24 #include "public_key.h" 24 25 #include "x509_parser.h" 25 26 26 - static const 27 - struct public_key_algorithm *x509_public_key_algorithms[PKEY_ALGO__LAST] = { 28 - [PKEY_ALGO_DSA] = NULL, 29 - #if defined(CONFIG_PUBLIC_KEY_ALGO_RSA) || \ 30 - defined(CONFIG_PUBLIC_KEY_ALGO_RSA_MODULE) 31 - [PKEY_ALGO_RSA] = &RSA_public_key_algorithm, 32 - #endif 33 - }; 27 + /* 28 + * Find a key in the given keyring by issuer and authority. 29 + */ 30 + static struct key *x509_request_asymmetric_key( 31 + struct key *keyring, 32 + const char *signer, size_t signer_len, 33 + const char *authority, size_t auth_len) 34 + { 35 + key_ref_t key; 36 + char *id; 37 + 38 + /* Construct an identifier. */ 39 + id = kmalloc(signer_len + 2 + auth_len + 1, GFP_KERNEL); 40 + if (!id) 41 + return ERR_PTR(-ENOMEM); 42 + 43 + memcpy(id, signer, signer_len); 44 + id[signer_len + 0] = ':'; 45 + id[signer_len + 1] = ' '; 46 + memcpy(id + signer_len + 2, authority, auth_len); 47 + id[signer_len + 2 + auth_len] = 0; 48 + 49 + pr_debug("Look up: \"%s\"\n", id); 50 + 51 + key = keyring_search(make_key_ref(keyring, 1), 52 + &key_type_asymmetric, id); 53 + if (IS_ERR(key)) 54 + pr_debug("Request for module key '%s' err %ld\n", 55 + id, PTR_ERR(key)); 56 + kfree(id); 57 + 58 + if (IS_ERR(key)) { 59 + switch (PTR_ERR(key)) { 60 + /* Hide some search errors */ 61 + case -EACCES: 62 + case -ENOTDIR: 63 + case -EAGAIN: 64 + return ERR_PTR(-ENOKEY); 65 + default: 66 + return ERR_CAST(key); 67 + } 68 + } 69 + 70 + pr_devel("<==%s() = 0 [%x]\n", __func__, key_serial(key_ref_to_ptr(key))); 71 + return key_ref_to_ptr(key); 72 + } 34 73 35 74 /* 36 - * Check the signature on a certificate using the provided public key 75 + * Set up the signature parameters in an X.509 certificate. This involves 76 + * digesting the signed data and extracting the signature. 37 77 */ 38 - static int x509_check_signature(const struct public_key *pub, 39 - const struct x509_certificate *cert) 78 + int x509_get_sig_params(struct x509_certificate *cert) 40 79 { 41 - struct public_key_signature *sig; 42 80 struct crypto_shash *tfm; 43 81 struct shash_desc *desc; 44 82 size_t digest_size, desc_size; 83 + void *digest; 45 84 int ret; 46 85 47 86 pr_devel("==>%s()\n", __func__); 48 - 87 + 88 + if (cert->sig.rsa.s) 89 + return 0; 90 + 91 + cert->sig.rsa.s = mpi_read_raw_data(cert->raw_sig, cert->raw_sig_size); 92 + if (!cert->sig.rsa.s) 93 + return -ENOMEM; 94 + cert->sig.nr_mpi = 1; 95 + 49 96 /* Allocate the hashing algorithm we're going to need and find out how 50 97 * big the hash operational data will be. 51 98 */ 52 - tfm = crypto_alloc_shash(pkey_hash_algo[cert->sig_hash_algo], 0, 0); 99 + tfm = crypto_alloc_shash(hash_algo_name[cert->sig.pkey_hash_algo], 0, 0); 53 100 if (IS_ERR(tfm)) 54 101 return (PTR_ERR(tfm) == -ENOENT) ? -ENOPKG : PTR_ERR(tfm); 55 102 56 103 desc_size = crypto_shash_descsize(tfm) + sizeof(*desc); 57 104 digest_size = crypto_shash_digestsize(tfm); 58 105 59 - /* We allocate the hash operational data storage on the end of our 60 - * context data. 106 + /* We allocate the hash operational data storage on the end of the 107 + * digest storage space. 61 108 */ 62 109 ret = -ENOMEM; 63 - sig = kzalloc(sizeof(*sig) + desc_size + digest_size, GFP_KERNEL); 64 - if (!sig) 65 - goto error_no_sig; 110 + digest = kzalloc(digest_size + desc_size, GFP_KERNEL); 111 + if (!digest) 112 + goto error; 66 113 67 - sig->pkey_hash_algo = cert->sig_hash_algo; 68 - sig->digest = (u8 *)sig + sizeof(*sig) + desc_size; 69 - sig->digest_size = digest_size; 114 + cert->sig.digest = digest; 115 + cert->sig.digest_size = digest_size; 70 116 71 - desc = (void *)sig + sizeof(*sig); 72 - desc->tfm = tfm; 73 - desc->flags = CRYPTO_TFM_REQ_MAY_SLEEP; 117 + desc = digest + digest_size; 118 + desc->tfm = tfm; 119 + desc->flags = CRYPTO_TFM_REQ_MAY_SLEEP; 74 120 75 121 ret = crypto_shash_init(desc); 76 122 if (ret < 0) 77 123 goto error; 78 - 79 - ret = -ENOMEM; 80 - sig->rsa.s = mpi_read_raw_data(cert->sig, cert->sig_size); 81 - if (!sig->rsa.s) 82 - goto error; 83 - 84 - ret = crypto_shash_finup(desc, cert->tbs, cert->tbs_size, sig->digest); 85 - if (ret < 0) 86 - goto error_mpi; 87 - 88 - ret = pub->algo->verify_signature(pub, sig); 89 - 90 - pr_debug("Cert Verification: %d\n", ret); 91 - 92 - error_mpi: 93 - mpi_free(sig->rsa.s); 124 + might_sleep(); 125 + ret = crypto_shash_finup(desc, cert->tbs, cert->tbs_size, digest); 94 126 error: 95 - kfree(sig); 96 - error_no_sig: 97 127 crypto_free_shash(tfm); 98 - 99 128 pr_devel("<==%s() = %d\n", __func__, ret); 129 + return ret; 130 + } 131 + EXPORT_SYMBOL_GPL(x509_get_sig_params); 132 + 133 + /* 134 + * Check the signature on a certificate using the provided public key 135 + */ 136 + int x509_check_signature(const struct public_key *pub, 137 + struct x509_certificate *cert) 138 + { 139 + int ret; 140 + 141 + pr_devel("==>%s()\n", __func__); 142 + 143 + ret = x509_get_sig_params(cert); 144 + if (ret < 0) 145 + return ret; 146 + 147 + ret = public_key_verify_signature(pub, &cert->sig); 148 + pr_debug("Cert Verification: %d\n", ret); 149 + return ret; 150 + } 151 + EXPORT_SYMBOL_GPL(x509_check_signature); 152 + 153 + /* 154 + * Check the new certificate against the ones in the trust keyring. If one of 155 + * those is the signing key and validates the new certificate, then mark the 156 + * new certificate as being trusted. 157 + * 158 + * Return 0 if the new certificate was successfully validated, 1 if we couldn't 159 + * find a matching parent certificate in the trusted list and an error if there 160 + * is a matching certificate but the signature check fails. 161 + */ 162 + static int x509_validate_trust(struct x509_certificate *cert, 163 + struct key *trust_keyring) 164 + { 165 + const struct public_key *pk; 166 + struct key *key; 167 + int ret = 1; 168 + 169 + key = x509_request_asymmetric_key(trust_keyring, 170 + cert->issuer, strlen(cert->issuer), 171 + cert->authority, 172 + strlen(cert->authority)); 173 + if (!IS_ERR(key)) { 174 + pk = key->payload.data; 175 + ret = x509_check_signature(pk, cert); 176 + } 100 177 return ret; 101 178 } 102 179 ··· 183 106 static int x509_key_preparse(struct key_preparsed_payload *prep) 184 107 { 185 108 struct x509_certificate *cert; 186 - struct tm now; 187 109 size_t srlen, sulen; 188 110 char *desc = NULL; 189 111 int ret; ··· 193 117 194 118 pr_devel("Cert Issuer: %s\n", cert->issuer); 195 119 pr_devel("Cert Subject: %s\n", cert->subject); 196 - pr_devel("Cert Key Algo: %s\n", pkey_algo[cert->pkey_algo]); 120 + 121 + if (cert->pub->pkey_algo >= PKEY_ALGO__LAST || 122 + cert->sig.pkey_algo >= PKEY_ALGO__LAST || 123 + cert->sig.pkey_hash_algo >= PKEY_HASH__LAST || 124 + !pkey_algo[cert->pub->pkey_algo] || 125 + !pkey_algo[cert->sig.pkey_algo] || 126 + !hash_algo_name[cert->sig.pkey_hash_algo]) { 127 + ret = -ENOPKG; 128 + goto error_free_cert; 129 + } 130 + 131 + pr_devel("Cert Key Algo: %s\n", pkey_algo_name[cert->pub->pkey_algo]); 197 132 pr_devel("Cert Valid From: %04ld-%02d-%02d %02d:%02d:%02d\n", 198 133 cert->valid_from.tm_year + 1900, cert->valid_from.tm_mon + 1, 199 134 cert->valid_from.tm_mday, cert->valid_from.tm_hour, ··· 214 127 cert->valid_to.tm_mday, cert->valid_to.tm_hour, 215 128 cert->valid_to.tm_min, cert->valid_to.tm_sec); 216 129 pr_devel("Cert Signature: %s + %s\n", 217 - pkey_algo[cert->sig_pkey_algo], 218 - pkey_hash_algo[cert->sig_hash_algo]); 130 + pkey_algo_name[cert->sig.pkey_algo], 131 + hash_algo_name[cert->sig.pkey_hash_algo]); 219 132 220 - if (!cert->fingerprint || !cert->authority) { 221 - pr_warn("Cert for '%s' must have SubjKeyId and AuthKeyId extensions\n", 133 + if (!cert->fingerprint) { 134 + pr_warn("Cert for '%s' must have a SubjKeyId extension\n", 222 135 cert->subject); 223 136 ret = -EKEYREJECTED; 224 137 goto error_free_cert; 225 138 } 226 139 227 - time_to_tm(CURRENT_TIME.tv_sec, 0, &now); 228 - pr_devel("Now: %04ld-%02d-%02d %02d:%02d:%02d\n", 229 - now.tm_year + 1900, now.tm_mon + 1, now.tm_mday, 230 - now.tm_hour, now.tm_min, now.tm_sec); 231 - if (now.tm_year < cert->valid_from.tm_year || 232 - (now.tm_year == cert->valid_from.tm_year && 233 - (now.tm_mon < cert->valid_from.tm_mon || 234 - (now.tm_mon == cert->valid_from.tm_mon && 235 - (now.tm_mday < cert->valid_from.tm_mday || 236 - (now.tm_mday == cert->valid_from.tm_mday && 237 - (now.tm_hour < cert->valid_from.tm_hour || 238 - (now.tm_hour == cert->valid_from.tm_hour && 239 - (now.tm_min < cert->valid_from.tm_min || 240 - (now.tm_min == cert->valid_from.tm_min && 241 - (now.tm_sec < cert->valid_from.tm_sec 242 - ))))))))))) { 243 - pr_warn("Cert %s is not yet valid\n", cert->fingerprint); 244 - ret = -EKEYREJECTED; 245 - goto error_free_cert; 246 - } 247 - if (now.tm_year > cert->valid_to.tm_year || 248 - (now.tm_year == cert->valid_to.tm_year && 249 - (now.tm_mon > cert->valid_to.tm_mon || 250 - (now.tm_mon == cert->valid_to.tm_mon && 251 - (now.tm_mday > cert->valid_to.tm_mday || 252 - (now.tm_mday == cert->valid_to.tm_mday && 253 - (now.tm_hour > cert->valid_to.tm_hour || 254 - (now.tm_hour == cert->valid_to.tm_hour && 255 - (now.tm_min > cert->valid_to.tm_min || 256 - (now.tm_min == cert->valid_to.tm_min && 257 - (now.tm_sec > cert->valid_to.tm_sec 258 - ))))))))))) { 259 - pr_warn("Cert %s has expired\n", cert->fingerprint); 260 - ret = -EKEYEXPIRED; 261 - goto error_free_cert; 262 - } 263 - 264 - cert->pub->algo = x509_public_key_algorithms[cert->pkey_algo]; 140 + cert->pub->algo = pkey_algo[cert->pub->pkey_algo]; 265 141 cert->pub->id_type = PKEY_ID_X509; 266 142 267 - /* Check the signature on the key */ 268 - if (strcmp(cert->fingerprint, cert->authority) == 0) { 269 - ret = x509_check_signature(cert->pub, cert); 143 + /* Check the signature on the key if it appears to be self-signed */ 144 + if (!cert->authority || 145 + strcmp(cert->fingerprint, cert->authority) == 0) { 146 + ret = x509_check_signature(cert->pub, cert); /* self-signed */ 270 147 if (ret < 0) 271 148 goto error_free_cert; 149 + } else { 150 + ret = x509_validate_trust(cert, system_trusted_keyring); 151 + if (!ret) 152 + prep->trusted = 1; 272 153 } 273 154 274 155 /* Propose a description */ ··· 292 237 293 238 module_init(x509_key_init); 294 239 module_exit(x509_key_exit); 240 + 241 + MODULE_DESCRIPTION("X.509 certificate parser"); 242 + MODULE_LICENSE("GPL");
+56
crypto/hash_info.c
··· 1 + /* 2 + * Hash Info: Hash algorithms information 3 + * 4 + * Copyright (c) 2013 Dmitry Kasatkin <d.kasatkin@samsung.com> 5 + * 6 + * This program is free software; you can redistribute it and/or modify it 7 + * under the terms of the GNU General Public License as published by the Free 8 + * Software Foundation; either version 2 of the License, or (at your option) 9 + * any later version. 10 + * 11 + */ 12 + 13 + #include <linux/export.h> 14 + #include <crypto/hash_info.h> 15 + 16 + const char *const hash_algo_name[HASH_ALGO__LAST] = { 17 + [HASH_ALGO_MD4] = "md4", 18 + [HASH_ALGO_MD5] = "md5", 19 + [HASH_ALGO_SHA1] = "sha1", 20 + [HASH_ALGO_RIPE_MD_160] = "rmd160", 21 + [HASH_ALGO_SHA256] = "sha256", 22 + [HASH_ALGO_SHA384] = "sha384", 23 + [HASH_ALGO_SHA512] = "sha512", 24 + [HASH_ALGO_SHA224] = "sha224", 25 + [HASH_ALGO_RIPE_MD_128] = "rmd128", 26 + [HASH_ALGO_RIPE_MD_256] = "rmd256", 27 + [HASH_ALGO_RIPE_MD_320] = "rmd320", 28 + [HASH_ALGO_WP_256] = "wp256", 29 + [HASH_ALGO_WP_384] = "wp384", 30 + [HASH_ALGO_WP_512] = "wp512", 31 + [HASH_ALGO_TGR_128] = "tgr128", 32 + [HASH_ALGO_TGR_160] = "tgr160", 33 + [HASH_ALGO_TGR_192] = "tgr192", 34 + }; 35 + EXPORT_SYMBOL_GPL(hash_algo_name); 36 + 37 + const int hash_digest_size[HASH_ALGO__LAST] = { 38 + [HASH_ALGO_MD4] = MD5_DIGEST_SIZE, 39 + [HASH_ALGO_MD5] = MD5_DIGEST_SIZE, 40 + [HASH_ALGO_SHA1] = SHA1_DIGEST_SIZE, 41 + [HASH_ALGO_RIPE_MD_160] = RMD160_DIGEST_SIZE, 42 + [HASH_ALGO_SHA256] = SHA256_DIGEST_SIZE, 43 + [HASH_ALGO_SHA384] = SHA384_DIGEST_SIZE, 44 + [HASH_ALGO_SHA512] = SHA512_DIGEST_SIZE, 45 + [HASH_ALGO_SHA224] = SHA224_DIGEST_SIZE, 46 + [HASH_ALGO_RIPE_MD_128] = RMD128_DIGEST_SIZE, 47 + [HASH_ALGO_RIPE_MD_256] = RMD256_DIGEST_SIZE, 48 + [HASH_ALGO_RIPE_MD_320] = RMD320_DIGEST_SIZE, 49 + [HASH_ALGO_WP_256] = WP256_DIGEST_SIZE, 50 + [HASH_ALGO_WP_384] = WP384_DIGEST_SIZE, 51 + [HASH_ALGO_WP_512] = WP512_DIGEST_SIZE, 52 + [HASH_ALGO_TGR_128] = TGR128_DIGEST_SIZE, 53 + [HASH_ALGO_TGR_160] = TGR160_DIGEST_SIZE, 54 + [HASH_ALGO_TGR_192] = TGR192_DIGEST_SIZE, 55 + }; 56 + EXPORT_SYMBOL_GPL(hash_digest_size);
+28 -9
drivers/char/tpm/Kconfig
··· 33 33 from within Linux. To compile this driver as a module, choose 34 34 M here; the module will be called tpm_tis. 35 35 36 + config TCG_TIS_I2C_ATMEL 37 + tristate "TPM Interface Specification 1.2 Interface (I2C - Atmel)" 38 + depends on I2C 39 + ---help--- 40 + If you have an Atmel I2C TPM security chip say Yes and it will be 41 + accessible from within Linux. 42 + To compile this driver as a module, choose M here; the module will 43 + be called tpm_tis_i2c_atmel. 44 + 36 45 config TCG_TIS_I2C_INFINEON 37 46 tristate "TPM Interface Specification 1.2 Interface (I2C - Infineon)" 38 47 depends on I2C ··· 51 42 Specification 0.20 say Yes and it will be accessible from within 52 43 Linux. 53 44 To compile this driver as a module, choose M here; the module 54 - will be called tpm_tis_i2c_infineon. 45 + will be called tpm_i2c_infineon. 46 + 47 + config TCG_TIS_I2C_NUVOTON 48 + tristate "TPM Interface Specification 1.2 Interface (I2C - Nuvoton)" 49 + depends on I2C 50 + ---help--- 51 + If you have a TPM security chip with an I2C interface from 52 + Nuvoton Technology Corp. say Yes and it will be accessible 53 + from within Linux. 54 + To compile this driver as a module, choose M here; the module 55 + will be called tpm_i2c_nuvoton. 55 56 56 57 config TCG_NSC 57 58 tristate "National Semiconductor TPM Interface" ··· 101 82 as a module, choose M here; the module will be called tpm_ibmvtpm. 102 83 103 84 config TCG_ST33_I2C 104 - tristate "STMicroelectronics ST33 I2C TPM" 105 - depends on I2C 106 - depends on GPIOLIB 107 - ---help--- 108 - If you have a TPM security chip from STMicroelectronics working with 109 - an I2C bus say Yes and it will be accessible from within Linux. 110 - To compile this driver as a module, choose M here; the module will be 111 - called tpm_stm_st33_i2c. 85 + tristate "STMicroelectronics ST33 I2C TPM" 86 + depends on I2C 87 + depends on GPIOLIB 88 + ---help--- 89 + If you have a TPM security chip from STMicroelectronics working with 90 + an I2C bus say Yes and it will be accessible from within Linux. 91 + To compile this driver as a module, choose M here; the module will be 92 + called tpm_stm_st33_i2c. 112 93 113 94 config TCG_XEN 114 95 tristate "XEN TPM Interface"
+7 -4
drivers/char/tpm/Makefile
··· 2 2 # Makefile for the kernel tpm device drivers. 3 3 # 4 4 obj-$(CONFIG_TCG_TPM) += tpm.o 5 + tpm-y := tpm-interface.o 6 + tpm-$(CONFIG_ACPI) += tpm_ppi.o 7 + 5 8 ifdef CONFIG_ACPI 6 - obj-$(CONFIG_TCG_TPM) += tpm_bios.o 7 - tpm_bios-objs += tpm_eventlog.o tpm_acpi.o tpm_ppi.o 9 + tpm-y += tpm_eventlog.o tpm_acpi.o 8 10 else 9 11 ifdef CONFIG_TCG_IBMVTPM 10 - obj-$(CONFIG_TCG_TPM) += tpm_bios.o 11 - tpm_bios-objs += tpm_eventlog.o tpm_of.o 12 + tpm-y += tpm_eventlog.o tpm_of.o 12 13 endif 13 14 endif 14 15 obj-$(CONFIG_TCG_TIS) += tpm_tis.o 16 + obj-$(CONFIG_TCG_TIS_I2C_ATMEL) += tpm_i2c_atmel.o 15 17 obj-$(CONFIG_TCG_TIS_I2C_INFINEON) += tpm_i2c_infineon.o 18 + obj-$(CONFIG_TCG_TIS_I2C_NUVOTON) += tpm_i2c_nuvoton.o 16 19 obj-$(CONFIG_TCG_NSC) += tpm_nsc.o 17 20 obj-$(CONFIG_TCG_ATMEL) += tpm_atmel.o 18 21 obj-$(CONFIG_TCG_INFINEON) += tpm_infineon.o
+56 -84
drivers/char/tpm/tpm.c drivers/char/tpm/tpm-interface.c
··· 10 10 * Maintained by: <tpmdd-devel@lists.sourceforge.net> 11 11 * 12 12 * Device driver for TCG/TCPA TPM (trusted platform module). 13 - * Specifications at www.trustedcomputinggroup.org 13 + * Specifications at www.trustedcomputinggroup.org 14 14 * 15 15 * This program is free software; you can redistribute it and/or 16 16 * modify it under the terms of the GNU General Public License as 17 17 * published by the Free Software Foundation, version 2 of the 18 18 * License. 19 - * 19 + * 20 20 * Note, the TPM chip is not interrupt driven (only polling) 21 21 * and can have very long timeouts (minutes!). Hence the unusual 22 22 * calls to msleep. ··· 371 371 return -ENODATA; 372 372 if (count > bufsiz) { 373 373 dev_err(chip->dev, 374 - "invalid count value %x %zx \n", count, bufsiz); 374 + "invalid count value %x %zx\n", count, bufsiz); 375 375 return -E2BIG; 376 376 } 377 377 378 378 mutex_lock(&chip->tpm_mutex); 379 379 380 - if ((rc = chip->vendor.send(chip, (u8 *) buf, count)) < 0) { 380 + rc = chip->vendor.send(chip, (u8 *) buf, count); 381 + if (rc < 0) { 381 382 dev_err(chip->dev, 382 383 "tpm_transmit: tpm_send: error %zd\n", rc); 383 384 goto out; ··· 445 444 { 446 445 int err; 447 446 448 - len = tpm_transmit(chip,(u8 *) cmd, len); 447 + len = tpm_transmit(chip, (u8 *) cmd, len); 449 448 if (len < 0) 450 449 return len; 451 450 else if (len < TPM_HEADER_SIZE) ··· 659 658 return rc; 660 659 } 661 660 662 - ssize_t tpm_show_enabled(struct device * dev, struct device_attribute * attr, 661 + ssize_t tpm_show_enabled(struct device *dev, struct device_attribute *attr, 663 662 char *buf) 664 663 { 665 664 cap_t cap; ··· 675 674 } 676 675 EXPORT_SYMBOL_GPL(tpm_show_enabled); 677 676 678 - ssize_t tpm_show_active(struct device * dev, struct device_attribute * attr, 677 + ssize_t tpm_show_active(struct device *dev, struct device_attribute *attr, 679 678 char *buf) 680 679 { 681 680 cap_t cap; ··· 691 690 } 692 691 EXPORT_SYMBOL_GPL(tpm_show_active); 693 692 694 - ssize_t tpm_show_owned(struct device * dev, struct device_attribute * attr, 693 + ssize_t tpm_show_owned(struct device *dev, struct device_attribute *attr, 695 694 char *buf) 696 695 { 697 696 cap_t cap; ··· 707 706 } 708 707 EXPORT_SYMBOL_GPL(tpm_show_owned); 709 708 710 - ssize_t tpm_show_temp_deactivated(struct device * dev, 711 - struct device_attribute * attr, char *buf) 709 + ssize_t tpm_show_temp_deactivated(struct device *dev, 710 + struct device_attribute *attr, char *buf) 712 711 { 713 712 cap_t cap; 714 713 ssize_t rc; ··· 770 769 771 770 /** 772 771 * tpm_pcr_read - read a pcr value 773 - * @chip_num: tpm idx # or ANY 772 + * @chip_num: tpm idx # or ANY 774 773 * @pcr_idx: pcr idx to retrieve 775 - * @res_buf: TPM_PCR value 776 - * size of res_buf is 20 bytes (or NULL if you don't care) 774 + * @res_buf: TPM_PCR value 775 + * size of res_buf is 20 bytes (or NULL if you don't care) 777 776 * 778 777 * The TPM driver should be built-in, but for whatever reason it 779 778 * isn't, protect against the chip disappearing, by incrementing ··· 795 794 796 795 /** 797 796 * tpm_pcr_extend - extend pcr value with hash 798 - * @chip_num: tpm idx # or AN& 797 + * @chip_num: tpm idx # or AN& 799 798 * @pcr_idx: pcr idx to extend 800 - * @hash: hash value used to extend pcr value 799 + * @hash: hash value used to extend pcr value 801 800 * 802 801 * The TPM driver should be built-in, but for whatever reason it 803 802 * isn't, protect against the chip disappearing, by incrementing ··· 848 847 unsigned long duration; 849 848 struct tpm_cmd_t cmd; 850 849 851 - duration = tpm_calc_ordinal_duration(chip, 852 - TPM_ORD_CONTINUE_SELFTEST); 850 + duration = tpm_calc_ordinal_duration(chip, TPM_ORD_CONTINUE_SELFTEST); 853 851 854 852 loops = jiffies_to_msecs(duration) / delay_msec; 855 853 ··· 965 965 if (err) 966 966 goto out; 967 967 968 - /* 968 + /* 969 969 ignore header 10 bytes 970 970 algorithm 32 bits (1 == RSA ) 971 971 encscheme 16 bits 972 972 sigscheme 16 bits 973 - parameters (RSA 12->bytes: keybit, #primes, expbit) 973 + parameters (RSA 12->bytes: keybit, #primes, expbit) 974 974 keylenbytes 32 bits 975 975 256 byte modulus 976 976 ignore checksum 20 bytes ··· 1020 1020 str += sprintf(str, "Manufacturer: 0x%x\n", 1021 1021 be32_to_cpu(cap.manufacturer_id)); 1022 1022 1023 - rc = tpm_getcap(dev, CAP_VERSION_1_1, &cap, 1024 - "attempting to determine the 1.1 version"); 1025 - if (rc) 1026 - return 0; 1027 - str += sprintf(str, 1028 - "TCG version: %d.%d\nFirmware version: %d.%d\n", 1029 - cap.tpm_version.Major, cap.tpm_version.Minor, 1030 - cap.tpm_version.revMajor, cap.tpm_version.revMinor); 1023 + /* Try to get a TPM version 1.2 TPM_CAP_VERSION_INFO */ 1024 + rc = tpm_getcap(dev, CAP_VERSION_1_2, &cap, 1025 + "attempting to determine the 1.2 version"); 1026 + if (!rc) { 1027 + str += sprintf(str, 1028 + "TCG version: %d.%d\nFirmware version: %d.%d\n", 1029 + cap.tpm_version_1_2.Major, 1030 + cap.tpm_version_1_2.Minor, 1031 + cap.tpm_version_1_2.revMajor, 1032 + cap.tpm_version_1_2.revMinor); 1033 + } else { 1034 + /* Otherwise just use TPM_STRUCT_VER */ 1035 + rc = tpm_getcap(dev, CAP_VERSION_1_1, &cap, 1036 + "attempting to determine the 1.1 version"); 1037 + if (rc) 1038 + return 0; 1039 + str += sprintf(str, 1040 + "TCG version: %d.%d\nFirmware version: %d.%d\n", 1041 + cap.tpm_version.Major, 1042 + cap.tpm_version.Minor, 1043 + cap.tpm_version.revMajor, 1044 + cap.tpm_version.revMinor); 1045 + } 1046 + 1031 1047 return str - buf; 1032 1048 } 1033 1049 EXPORT_SYMBOL_GPL(tpm_show_caps); 1034 - 1035 - ssize_t tpm_show_caps_1_2(struct device * dev, 1036 - struct device_attribute * attr, char *buf) 1037 - { 1038 - cap_t cap; 1039 - ssize_t rc; 1040 - char *str = buf; 1041 - 1042 - rc = tpm_getcap(dev, TPM_CAP_PROP_MANUFACTURER, &cap, 1043 - "attempting to determine the manufacturer"); 1044 - if (rc) 1045 - return 0; 1046 - str += sprintf(str, "Manufacturer: 0x%x\n", 1047 - be32_to_cpu(cap.manufacturer_id)); 1048 - rc = tpm_getcap(dev, CAP_VERSION_1_2, &cap, 1049 - "attempting to determine the 1.2 version"); 1050 - if (rc) 1051 - return 0; 1052 - str += sprintf(str, 1053 - "TCG version: %d.%d\nFirmware version: %d.%d\n", 1054 - cap.tpm_version_1_2.Major, cap.tpm_version_1_2.Minor, 1055 - cap.tpm_version_1_2.revMajor, 1056 - cap.tpm_version_1_2.revMinor); 1057 - return str - buf; 1058 - } 1059 - EXPORT_SYMBOL_GPL(tpm_show_caps_1_2); 1060 1050 1061 1051 ssize_t tpm_show_durations(struct device *dev, struct device_attribute *attr, 1062 1052 char *buf) ··· 1092 1102 } 1093 1103 EXPORT_SYMBOL_GPL(tpm_store_cancel); 1094 1104 1095 - static bool wait_for_tpm_stat_cond(struct tpm_chip *chip, u8 mask, bool check_cancel, 1096 - bool *canceled) 1105 + static bool wait_for_tpm_stat_cond(struct tpm_chip *chip, u8 mask, 1106 + bool check_cancel, bool *canceled) 1097 1107 { 1098 1108 u8 status = chip->vendor.status(chip); 1099 1109 ··· 1160 1170 */ 1161 1171 int tpm_open(struct inode *inode, struct file *file) 1162 1172 { 1163 - int minor = iminor(inode); 1164 - struct tpm_chip *chip = NULL, *pos; 1165 - 1166 - rcu_read_lock(); 1167 - list_for_each_entry_rcu(pos, &tpm_chip_list, list) { 1168 - if (pos->vendor.miscdev.minor == minor) { 1169 - chip = pos; 1170 - get_device(chip->dev); 1171 - break; 1172 - } 1173 - } 1174 - rcu_read_unlock(); 1175 - 1176 - if (!chip) 1177 - return -ENODEV; 1173 + struct miscdevice *misc = file->private_data; 1174 + struct tpm_chip *chip = container_of(misc, struct tpm_chip, 1175 + vendor.miscdev); 1178 1176 1179 1177 if (test_and_set_bit(0, &chip->is_open)) { 1180 1178 dev_dbg(chip->dev, "Another process owns this TPM\n"); 1181 - put_device(chip->dev); 1182 1179 return -EBUSY; 1183 1180 } 1184 1181 1185 1182 chip->data_buffer = kzalloc(TPM_BUFSIZE, GFP_KERNEL); 1186 1183 if (chip->data_buffer == NULL) { 1187 1184 clear_bit(0, &chip->is_open); 1188 - put_device(chip->dev); 1189 1185 return -ENOMEM; 1190 1186 } 1191 1187 1192 1188 atomic_set(&chip->data_pending, 0); 1193 1189 1194 1190 file->private_data = chip; 1191 + get_device(chip->dev); 1195 1192 return 0; 1196 1193 } 1197 1194 EXPORT_SYMBOL_GPL(tpm_open); ··· 1440 1463 chip->vendor.release(chip->dev); 1441 1464 1442 1465 clear_bit(chip->dev_num, dev_mask); 1443 - kfree(chip->vendor.miscdev.name); 1444 1466 } 1445 1467 EXPORT_SYMBOL_GPL(tpm_dev_vendor_release); 1446 1468 ··· 1463 1487 EXPORT_SYMBOL_GPL(tpm_dev_release); 1464 1488 1465 1489 /* 1466 - * Called from tpm_<specific>.c probe function only for devices 1490 + * Called from tpm_<specific>.c probe function only for devices 1467 1491 * the driver has determined it should claim. Prior to calling 1468 1492 * this function the specific probe function has called pci_enable_device 1469 1493 * upon errant exit from this function specific probe function should call ··· 1472 1496 struct tpm_chip *tpm_register_hardware(struct device *dev, 1473 1497 const struct tpm_vendor_specific *entry) 1474 1498 { 1475 - #define DEVNAME_SIZE 7 1476 - 1477 - char *devname; 1478 1499 struct tpm_chip *chip; 1479 1500 1480 1501 /* Driver specific per-device data */ 1481 1502 chip = kzalloc(sizeof(*chip), GFP_KERNEL); 1482 - devname = kmalloc(DEVNAME_SIZE, GFP_KERNEL); 1483 1503 1484 - if (chip == NULL || devname == NULL) 1485 - goto out_free; 1504 + if (chip == NULL) 1505 + return NULL; 1486 1506 1487 1507 mutex_init(&chip->buffer_mutex); 1488 1508 mutex_init(&chip->tpm_mutex); ··· 1503 1531 1504 1532 set_bit(chip->dev_num, dev_mask); 1505 1533 1506 - scnprintf(devname, DEVNAME_SIZE, "%s%d", "tpm", chip->dev_num); 1507 - chip->vendor.miscdev.name = devname; 1534 + scnprintf(chip->devname, sizeof(chip->devname), "%s%d", "tpm", 1535 + chip->dev_num); 1536 + chip->vendor.miscdev.name = chip->devname; 1508 1537 1509 1538 chip->vendor.miscdev.parent = dev; 1510 1539 chip->dev = get_device(dev); ··· 1531 1558 goto put_device; 1532 1559 } 1533 1560 1534 - chip->bios_dir = tpm_bios_log_setup(devname); 1561 + chip->bios_dir = tpm_bios_log_setup(chip->devname); 1535 1562 1536 1563 /* Make chip available */ 1537 1564 spin_lock(&driver_lock); ··· 1544 1571 put_device(chip->dev); 1545 1572 out_free: 1546 1573 kfree(chip); 1547 - kfree(devname); 1548 1574 return NULL; 1549 1575 } 1550 1576 EXPORT_SYMBOL_GPL(tpm_register_hardware);
+1 -2
drivers/char/tpm/tpm.h
··· 59 59 char *); 60 60 extern ssize_t tpm_show_caps(struct device *, struct device_attribute *attr, 61 61 char *); 62 - extern ssize_t tpm_show_caps_1_2(struct device *, struct device_attribute *attr, 63 - char *); 64 62 extern ssize_t tpm_store_cancel(struct device *, struct device_attribute *attr, 65 63 const char *, size_t); 66 64 extern ssize_t tpm_show_enabled(struct device *, struct device_attribute *attr, ··· 120 122 struct device *dev; /* Device stuff */ 121 123 122 124 int dev_num; /* /dev/tpm# */ 125 + char devname[7]; 123 126 unsigned long is_open; /* only one allowed */ 124 127 int time_expired; 125 128
+1 -1
drivers/char/tpm/tpm_atmel.c
··· 202 202 203 203 have_region = 204 204 (atmel_request_region 205 - (tpm_atmel.base, region_size, "tpm_atmel0") == NULL) ? 0 : 1; 205 + (base, region_size, "tpm_atmel0") == NULL) ? 0 : 1; 206 206 207 207 pdev = platform_device_register_simple("tpm_atmel", -1, NULL, 0); 208 208 if (IS_ERR(pdev)) {
-3
drivers/char/tpm/tpm_eventlog.c
··· 406 406 out: 407 407 return NULL; 408 408 } 409 - EXPORT_SYMBOL_GPL(tpm_bios_log_setup); 410 409 411 410 void tpm_bios_log_teardown(struct dentry **lst) 412 411 { ··· 414 415 for (i = 0; i < 3; i++) 415 416 securityfs_remove(lst[i]); 416 417 } 417 - EXPORT_SYMBOL_GPL(tpm_bios_log_teardown); 418 - MODULE_LICENSE("GPL");
+284
drivers/char/tpm/tpm_i2c_atmel.c
··· 1 + /* 2 + * ATMEL I2C TPM AT97SC3204T 3 + * 4 + * Copyright (C) 2012 V Lab Technologies 5 + * Teddy Reed <teddy@prosauce.org> 6 + * Copyright (C) 2013, Obsidian Research Corp. 7 + * Jason Gunthorpe <jgunthorpe@obsidianresearch.com> 8 + * Device driver for ATMEL I2C TPMs. 9 + * 10 + * Teddy Reed determined the basic I2C command flow, unlike other I2C TPM 11 + * devices the raw TCG formatted TPM command data is written via I2C and then 12 + * raw TCG formatted TPM command data is returned via I2C. 13 + * 14 + * TGC status/locality/etc functions seen in the LPC implementation do not 15 + * seem to be present. 16 + * 17 + * This program is free software: you can redistribute it and/or modify 18 + * it under the terms of the GNU General Public License as published by 19 + * the Free Software Foundation, either version 2 of the License, or 20 + * (at your option) any later version. 21 + * 22 + * This program is distributed in the hope that it will be useful, 23 + * but WITHOUT ANY WARRANTY; without even the implied warranty of 24 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 25 + * GNU General Public License for more details. 26 + * 27 + * You should have received a copy of the GNU General Public License 28 + * along with this program. If not, see http://www.gnu.org/licenses/>. 29 + */ 30 + #include <linux/init.h> 31 + #include <linux/module.h> 32 + #include <linux/moduleparam.h> 33 + #include <linux/slab.h> 34 + #include <linux/i2c.h> 35 + #include "tpm.h" 36 + 37 + #define I2C_DRIVER_NAME "tpm_i2c_atmel" 38 + 39 + #define TPM_I2C_SHORT_TIMEOUT 750 /* ms */ 40 + #define TPM_I2C_LONG_TIMEOUT 2000 /* 2 sec */ 41 + 42 + #define ATMEL_STS_OK 1 43 + 44 + struct priv_data { 45 + size_t len; 46 + /* This is the amount we read on the first try. 25 was chosen to fit a 47 + * fair number of read responses in the buffer so a 2nd retry can be 48 + * avoided in small message cases. */ 49 + u8 buffer[sizeof(struct tpm_output_header) + 25]; 50 + }; 51 + 52 + static int i2c_atmel_send(struct tpm_chip *chip, u8 *buf, size_t len) 53 + { 54 + struct priv_data *priv = chip->vendor.priv; 55 + struct i2c_client *client = to_i2c_client(chip->dev); 56 + s32 status; 57 + 58 + priv->len = 0; 59 + 60 + if (len <= 2) 61 + return -EIO; 62 + 63 + status = i2c_master_send(client, buf, len); 64 + 65 + dev_dbg(chip->dev, 66 + "%s(buf=%*ph len=%0zx) -> sts=%d\n", __func__, 67 + (int)min_t(size_t, 64, len), buf, len, status); 68 + return status; 69 + } 70 + 71 + static int i2c_atmel_recv(struct tpm_chip *chip, u8 *buf, size_t count) 72 + { 73 + struct priv_data *priv = chip->vendor.priv; 74 + struct i2c_client *client = to_i2c_client(chip->dev); 75 + struct tpm_output_header *hdr = 76 + (struct tpm_output_header *)priv->buffer; 77 + u32 expected_len; 78 + int rc; 79 + 80 + if (priv->len == 0) 81 + return -EIO; 82 + 83 + /* Get the message size from the message header, if we didn't get the 84 + * whole message in read_status then we need to re-read the 85 + * message. */ 86 + expected_len = be32_to_cpu(hdr->length); 87 + if (expected_len > count) 88 + return -ENOMEM; 89 + 90 + if (priv->len >= expected_len) { 91 + dev_dbg(chip->dev, 92 + "%s early(buf=%*ph count=%0zx) -> ret=%d\n", __func__, 93 + (int)min_t(size_t, 64, expected_len), buf, count, 94 + expected_len); 95 + memcpy(buf, priv->buffer, expected_len); 96 + return expected_len; 97 + } 98 + 99 + rc = i2c_master_recv(client, buf, expected_len); 100 + dev_dbg(chip->dev, 101 + "%s reread(buf=%*ph count=%0zx) -> ret=%d\n", __func__, 102 + (int)min_t(size_t, 64, expected_len), buf, count, 103 + expected_len); 104 + return rc; 105 + } 106 + 107 + static void i2c_atmel_cancel(struct tpm_chip *chip) 108 + { 109 + dev_err(chip->dev, "TPM operation cancellation was requested, but is not supported"); 110 + } 111 + 112 + static u8 i2c_atmel_read_status(struct tpm_chip *chip) 113 + { 114 + struct priv_data *priv = chip->vendor.priv; 115 + struct i2c_client *client = to_i2c_client(chip->dev); 116 + int rc; 117 + 118 + /* The TPM fails the I2C read until it is ready, so we do the entire 119 + * transfer here and buffer it locally. This way the common code can 120 + * properly handle the timeouts. */ 121 + priv->len = 0; 122 + memset(priv->buffer, 0, sizeof(priv->buffer)); 123 + 124 + 125 + /* Once the TPM has completed the command the command remains readable 126 + * until another command is issued. */ 127 + rc = i2c_master_recv(client, priv->buffer, sizeof(priv->buffer)); 128 + dev_dbg(chip->dev, 129 + "%s: sts=%d", __func__, rc); 130 + if (rc <= 0) 131 + return 0; 132 + 133 + priv->len = rc; 134 + 135 + return ATMEL_STS_OK; 136 + } 137 + 138 + static const struct file_operations i2c_atmel_ops = { 139 + .owner = THIS_MODULE, 140 + .llseek = no_llseek, 141 + .open = tpm_open, 142 + .read = tpm_read, 143 + .write = tpm_write, 144 + .release = tpm_release, 145 + }; 146 + 147 + static DEVICE_ATTR(pubek, S_IRUGO, tpm_show_pubek, NULL); 148 + static DEVICE_ATTR(pcrs, S_IRUGO, tpm_show_pcrs, NULL); 149 + static DEVICE_ATTR(enabled, S_IRUGO, tpm_show_enabled, NULL); 150 + static DEVICE_ATTR(active, S_IRUGO, tpm_show_active, NULL); 151 + static DEVICE_ATTR(owned, S_IRUGO, tpm_show_owned, NULL); 152 + static DEVICE_ATTR(temp_deactivated, S_IRUGO, tpm_show_temp_deactivated, NULL); 153 + static DEVICE_ATTR(caps, S_IRUGO, tpm_show_caps, NULL); 154 + static DEVICE_ATTR(cancel, S_IWUSR | S_IWGRP, NULL, tpm_store_cancel); 155 + static DEVICE_ATTR(durations, S_IRUGO, tpm_show_durations, NULL); 156 + static DEVICE_ATTR(timeouts, S_IRUGO, tpm_show_timeouts, NULL); 157 + 158 + static struct attribute *i2c_atmel_attrs[] = { 159 + &dev_attr_pubek.attr, 160 + &dev_attr_pcrs.attr, 161 + &dev_attr_enabled.attr, 162 + &dev_attr_active.attr, 163 + &dev_attr_owned.attr, 164 + &dev_attr_temp_deactivated.attr, 165 + &dev_attr_caps.attr, 166 + &dev_attr_cancel.attr, 167 + &dev_attr_durations.attr, 168 + &dev_attr_timeouts.attr, 169 + NULL, 170 + }; 171 + 172 + static struct attribute_group i2c_atmel_attr_grp = { 173 + .attrs = i2c_atmel_attrs 174 + }; 175 + 176 + static bool i2c_atmel_req_canceled(struct tpm_chip *chip, u8 status) 177 + { 178 + return 0; 179 + } 180 + 181 + static const struct tpm_vendor_specific i2c_atmel = { 182 + .status = i2c_atmel_read_status, 183 + .recv = i2c_atmel_recv, 184 + .send = i2c_atmel_send, 185 + .cancel = i2c_atmel_cancel, 186 + .req_complete_mask = ATMEL_STS_OK, 187 + .req_complete_val = ATMEL_STS_OK, 188 + .req_canceled = i2c_atmel_req_canceled, 189 + .attr_group = &i2c_atmel_attr_grp, 190 + .miscdev.fops = &i2c_atmel_ops, 191 + }; 192 + 193 + static int i2c_atmel_probe(struct i2c_client *client, 194 + const struct i2c_device_id *id) 195 + { 196 + int rc; 197 + struct tpm_chip *chip; 198 + struct device *dev = &client->dev; 199 + 200 + if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C)) 201 + return -ENODEV; 202 + 203 + chip = tpm_register_hardware(dev, &i2c_atmel); 204 + if (!chip) { 205 + dev_err(dev, "%s() error in tpm_register_hardware\n", __func__); 206 + return -ENODEV; 207 + } 208 + 209 + chip->vendor.priv = devm_kzalloc(dev, sizeof(struct priv_data), 210 + GFP_KERNEL); 211 + 212 + /* Default timeouts */ 213 + chip->vendor.timeout_a = msecs_to_jiffies(TPM_I2C_SHORT_TIMEOUT); 214 + chip->vendor.timeout_b = msecs_to_jiffies(TPM_I2C_LONG_TIMEOUT); 215 + chip->vendor.timeout_c = msecs_to_jiffies(TPM_I2C_SHORT_TIMEOUT); 216 + chip->vendor.timeout_d = msecs_to_jiffies(TPM_I2C_SHORT_TIMEOUT); 217 + chip->vendor.irq = 0; 218 + 219 + /* There is no known way to probe for this device, and all version 220 + * information seems to be read via TPM commands. Thus we rely on the 221 + * TPM startup process in the common code to detect the device. */ 222 + if (tpm_get_timeouts(chip)) { 223 + rc = -ENODEV; 224 + goto out_err; 225 + } 226 + 227 + if (tpm_do_selftest(chip)) { 228 + rc = -ENODEV; 229 + goto out_err; 230 + } 231 + 232 + return 0; 233 + 234 + out_err: 235 + tpm_dev_vendor_release(chip); 236 + tpm_remove_hardware(chip->dev); 237 + return rc; 238 + } 239 + 240 + static int i2c_atmel_remove(struct i2c_client *client) 241 + { 242 + struct device *dev = &(client->dev); 243 + struct tpm_chip *chip = dev_get_drvdata(dev); 244 + 245 + if (chip) 246 + tpm_dev_vendor_release(chip); 247 + tpm_remove_hardware(dev); 248 + kfree(chip); 249 + return 0; 250 + } 251 + 252 + static const struct i2c_device_id i2c_atmel_id[] = { 253 + {I2C_DRIVER_NAME, 0}, 254 + {} 255 + }; 256 + MODULE_DEVICE_TABLE(i2c, i2c_atmel_id); 257 + 258 + #ifdef CONFIG_OF 259 + static const struct of_device_id i2c_atmel_of_match[] = { 260 + {.compatible = "atmel,at97sc3204t"}, 261 + {}, 262 + }; 263 + MODULE_DEVICE_TABLE(of, i2c_atmel_of_match); 264 + #endif 265 + 266 + static SIMPLE_DEV_PM_OPS(i2c_atmel_pm_ops, tpm_pm_suspend, tpm_pm_resume); 267 + 268 + static struct i2c_driver i2c_atmel_driver = { 269 + .id_table = i2c_atmel_id, 270 + .probe = i2c_atmel_probe, 271 + .remove = i2c_atmel_remove, 272 + .driver = { 273 + .name = I2C_DRIVER_NAME, 274 + .owner = THIS_MODULE, 275 + .pm = &i2c_atmel_pm_ops, 276 + .of_match_table = of_match_ptr(i2c_atmel_of_match), 277 + }, 278 + }; 279 + 280 + module_i2c_driver(i2c_atmel_driver); 281 + 282 + MODULE_AUTHOR("Jason Gunthorpe <jgunthorpe@obsidianresearch.com>"); 283 + MODULE_DESCRIPTION("Atmel TPM I2C Driver"); 284 + MODULE_LICENSE("GPL");
+1 -3
drivers/char/tpm/tpm_i2c_infineon.c
··· 581 581 static DEVICE_ATTR(active, S_IRUGO, tpm_show_active, NULL); 582 582 static DEVICE_ATTR(owned, S_IRUGO, tpm_show_owned, NULL); 583 583 static DEVICE_ATTR(temp_deactivated, S_IRUGO, tpm_show_temp_deactivated, NULL); 584 - static DEVICE_ATTR(caps, S_IRUGO, tpm_show_caps_1_2, NULL); 584 + static DEVICE_ATTR(caps, S_IRUGO, tpm_show_caps, NULL); 585 585 static DEVICE_ATTR(cancel, S_IWUSR | S_IWGRP, NULL, tpm_store_cancel); 586 586 static DEVICE_ATTR(durations, S_IRUGO, tpm_show_durations, NULL); 587 587 static DEVICE_ATTR(timeouts, S_IRUGO, tpm_show_timeouts, NULL); ··· 685 685 chip->dev->release = NULL; 686 686 chip->release = NULL; 687 687 tpm_dev.client = NULL; 688 - dev_set_drvdata(chip->dev, chip); 689 688 out_err: 690 689 return rc; 691 690 } ··· 765 766 chip->dev->release = NULL; 766 767 chip->release = NULL; 767 768 tpm_dev.client = NULL; 768 - dev_set_drvdata(chip->dev, chip); 769 769 770 770 return 0; 771 771 }
+710
drivers/char/tpm/tpm_i2c_nuvoton.c
··· 1 + /****************************************************************************** 2 + * Nuvoton TPM I2C Device Driver Interface for WPCT301/NPCT501, 3 + * based on the TCG TPM Interface Spec version 1.2. 4 + * Specifications at www.trustedcomputinggroup.org 5 + * 6 + * Copyright (C) 2011, Nuvoton Technology Corporation. 7 + * Dan Morav <dan.morav@nuvoton.com> 8 + * Copyright (C) 2013, Obsidian Research Corp. 9 + * Jason Gunthorpe <jgunthorpe@obsidianresearch.com> 10 + * 11 + * This program is free software: you can redistribute it and/or modify 12 + * it under the terms of the GNU General Public License as published by 13 + * the Free Software Foundation, either version 2 of the License, or 14 + * (at your option) any later version. 15 + * 16 + * This program is distributed in the hope that it will be useful, 17 + * but WITHOUT ANY WARRANTY; without even the implied warranty of 18 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 19 + * GNU General Public License for more details. 20 + * 21 + * You should have received a copy of the GNU General Public License 22 + * along with this program. If not, see http://www.gnu.org/licenses/>. 23 + * 24 + * Nuvoton contact information: APC.Support@nuvoton.com 25 + *****************************************************************************/ 26 + 27 + #include <linux/init.h> 28 + #include <linux/module.h> 29 + #include <linux/moduleparam.h> 30 + #include <linux/slab.h> 31 + #include <linux/interrupt.h> 32 + #include <linux/wait.h> 33 + #include <linux/i2c.h> 34 + #include "tpm.h" 35 + 36 + /* I2C interface offsets */ 37 + #define TPM_STS 0x00 38 + #define TPM_BURST_COUNT 0x01 39 + #define TPM_DATA_FIFO_W 0x20 40 + #define TPM_DATA_FIFO_R 0x40 41 + #define TPM_VID_DID_RID 0x60 42 + /* TPM command header size */ 43 + #define TPM_HEADER_SIZE 10 44 + #define TPM_RETRY 5 45 + /* 46 + * I2C bus device maximum buffer size w/o counting I2C address or command 47 + * i.e. max size required for I2C write is 34 = addr, command, 32 bytes data 48 + */ 49 + #define TPM_I2C_MAX_BUF_SIZE 32 50 + #define TPM_I2C_RETRY_COUNT 32 51 + #define TPM_I2C_BUS_DELAY 1 /* msec */ 52 + #define TPM_I2C_RETRY_DELAY_SHORT 2 /* msec */ 53 + #define TPM_I2C_RETRY_DELAY_LONG 10 /* msec */ 54 + 55 + #define I2C_DRIVER_NAME "tpm_i2c_nuvoton" 56 + 57 + struct priv_data { 58 + unsigned int intrs; 59 + }; 60 + 61 + static s32 i2c_nuvoton_read_buf(struct i2c_client *client, u8 offset, u8 size, 62 + u8 *data) 63 + { 64 + s32 status; 65 + 66 + status = i2c_smbus_read_i2c_block_data(client, offset, size, data); 67 + dev_dbg(&client->dev, 68 + "%s(offset=%u size=%u data=%*ph) -> sts=%d\n", __func__, 69 + offset, size, (int)size, data, status); 70 + return status; 71 + } 72 + 73 + static s32 i2c_nuvoton_write_buf(struct i2c_client *client, u8 offset, u8 size, 74 + u8 *data) 75 + { 76 + s32 status; 77 + 78 + status = i2c_smbus_write_i2c_block_data(client, offset, size, data); 79 + dev_dbg(&client->dev, 80 + "%s(offset=%u size=%u data=%*ph) -> sts=%d\n", __func__, 81 + offset, size, (int)size, data, status); 82 + return status; 83 + } 84 + 85 + #define TPM_STS_VALID 0x80 86 + #define TPM_STS_COMMAND_READY 0x40 87 + #define TPM_STS_GO 0x20 88 + #define TPM_STS_DATA_AVAIL 0x10 89 + #define TPM_STS_EXPECT 0x08 90 + #define TPM_STS_RESPONSE_RETRY 0x02 91 + #define TPM_STS_ERR_VAL 0x07 /* bit2...bit0 reads always 0 */ 92 + 93 + #define TPM_I2C_SHORT_TIMEOUT 750 /* ms */ 94 + #define TPM_I2C_LONG_TIMEOUT 2000 /* 2 sec */ 95 + 96 + /* read TPM_STS register */ 97 + static u8 i2c_nuvoton_read_status(struct tpm_chip *chip) 98 + { 99 + struct i2c_client *client = to_i2c_client(chip->dev); 100 + s32 status; 101 + u8 data; 102 + 103 + status = i2c_nuvoton_read_buf(client, TPM_STS, 1, &data); 104 + if (status <= 0) { 105 + dev_err(chip->dev, "%s() error return %d\n", __func__, 106 + status); 107 + data = TPM_STS_ERR_VAL; 108 + } 109 + 110 + return data; 111 + } 112 + 113 + /* write byte to TPM_STS register */ 114 + static s32 i2c_nuvoton_write_status(struct i2c_client *client, u8 data) 115 + { 116 + s32 status; 117 + int i; 118 + 119 + /* this causes the current command to be aborted */ 120 + for (i = 0, status = -1; i < TPM_I2C_RETRY_COUNT && status < 0; i++) { 121 + status = i2c_nuvoton_write_buf(client, TPM_STS, 1, &data); 122 + msleep(TPM_I2C_BUS_DELAY); 123 + } 124 + return status; 125 + } 126 + 127 + /* write commandReady to TPM_STS register */ 128 + static void i2c_nuvoton_ready(struct tpm_chip *chip) 129 + { 130 + struct i2c_client *client = to_i2c_client(chip->dev); 131 + s32 status; 132 + 133 + /* this causes the current command to be aborted */ 134 + status = i2c_nuvoton_write_status(client, TPM_STS_COMMAND_READY); 135 + if (status < 0) 136 + dev_err(chip->dev, 137 + "%s() fail to write TPM_STS.commandReady\n", __func__); 138 + } 139 + 140 + /* read burstCount field from TPM_STS register 141 + * return -1 on fail to read */ 142 + static int i2c_nuvoton_get_burstcount(struct i2c_client *client, 143 + struct tpm_chip *chip) 144 + { 145 + unsigned long stop = jiffies + chip->vendor.timeout_d; 146 + s32 status; 147 + int burst_count = -1; 148 + u8 data; 149 + 150 + /* wait for burstcount to be non-zero */ 151 + do { 152 + /* in I2C burstCount is 1 byte */ 153 + status = i2c_nuvoton_read_buf(client, TPM_BURST_COUNT, 1, 154 + &data); 155 + if (status > 0 && data > 0) { 156 + burst_count = min_t(u8, TPM_I2C_MAX_BUF_SIZE, data); 157 + break; 158 + } 159 + msleep(TPM_I2C_BUS_DELAY); 160 + } while (time_before(jiffies, stop)); 161 + 162 + return burst_count; 163 + } 164 + 165 + /* 166 + * WPCT301/NPCT501 SINT# supports only dataAvail 167 + * any call to this function which is not waiting for dataAvail will 168 + * set queue to NULL to avoid waiting for interrupt 169 + */ 170 + static bool i2c_nuvoton_check_status(struct tpm_chip *chip, u8 mask, u8 value) 171 + { 172 + u8 status = i2c_nuvoton_read_status(chip); 173 + return (status != TPM_STS_ERR_VAL) && ((status & mask) == value); 174 + } 175 + 176 + static int i2c_nuvoton_wait_for_stat(struct tpm_chip *chip, u8 mask, u8 value, 177 + u32 timeout, wait_queue_head_t *queue) 178 + { 179 + if (chip->vendor.irq && queue) { 180 + s32 rc; 181 + DEFINE_WAIT(wait); 182 + struct priv_data *priv = chip->vendor.priv; 183 + unsigned int cur_intrs = priv->intrs; 184 + 185 + enable_irq(chip->vendor.irq); 186 + rc = wait_event_interruptible_timeout(*queue, 187 + cur_intrs != priv->intrs, 188 + timeout); 189 + if (rc > 0) 190 + return 0; 191 + /* At this point we know that the SINT pin is asserted, so we 192 + * do not need to do i2c_nuvoton_check_status */ 193 + } else { 194 + unsigned long ten_msec, stop; 195 + bool status_valid; 196 + 197 + /* check current status */ 198 + status_valid = i2c_nuvoton_check_status(chip, mask, value); 199 + if (status_valid) 200 + return 0; 201 + 202 + /* use polling to wait for the event */ 203 + ten_msec = jiffies + msecs_to_jiffies(TPM_I2C_RETRY_DELAY_LONG); 204 + stop = jiffies + timeout; 205 + do { 206 + if (time_before(jiffies, ten_msec)) 207 + msleep(TPM_I2C_RETRY_DELAY_SHORT); 208 + else 209 + msleep(TPM_I2C_RETRY_DELAY_LONG); 210 + status_valid = i2c_nuvoton_check_status(chip, mask, 211 + value); 212 + if (status_valid) 213 + return 0; 214 + } while (time_before(jiffies, stop)); 215 + } 216 + dev_err(chip->dev, "%s(%02x, %02x) -> timeout\n", __func__, mask, 217 + value); 218 + return -ETIMEDOUT; 219 + } 220 + 221 + /* wait for dataAvail field to be set in the TPM_STS register */ 222 + static int i2c_nuvoton_wait_for_data_avail(struct tpm_chip *chip, u32 timeout, 223 + wait_queue_head_t *queue) 224 + { 225 + return i2c_nuvoton_wait_for_stat(chip, 226 + TPM_STS_DATA_AVAIL | TPM_STS_VALID, 227 + TPM_STS_DATA_AVAIL | TPM_STS_VALID, 228 + timeout, queue); 229 + } 230 + 231 + /* Read @count bytes into @buf from TPM_RD_FIFO register */ 232 + static int i2c_nuvoton_recv_data(struct i2c_client *client, 233 + struct tpm_chip *chip, u8 *buf, size_t count) 234 + { 235 + s32 rc; 236 + int burst_count, bytes2read, size = 0; 237 + 238 + while (size < count && 239 + i2c_nuvoton_wait_for_data_avail(chip, 240 + chip->vendor.timeout_c, 241 + &chip->vendor.read_queue) == 0) { 242 + burst_count = i2c_nuvoton_get_burstcount(client, chip); 243 + if (burst_count < 0) { 244 + dev_err(chip->dev, 245 + "%s() fail to read burstCount=%d\n", __func__, 246 + burst_count); 247 + return -EIO; 248 + } 249 + bytes2read = min_t(size_t, burst_count, count - size); 250 + rc = i2c_nuvoton_read_buf(client, TPM_DATA_FIFO_R, 251 + bytes2read, &buf[size]); 252 + if (rc < 0) { 253 + dev_err(chip->dev, 254 + "%s() fail on i2c_nuvoton_read_buf()=%d\n", 255 + __func__, rc); 256 + return -EIO; 257 + } 258 + dev_dbg(chip->dev, "%s(%d):", __func__, bytes2read); 259 + size += bytes2read; 260 + } 261 + 262 + return size; 263 + } 264 + 265 + /* Read TPM command results */ 266 + static int i2c_nuvoton_recv(struct tpm_chip *chip, u8 *buf, size_t count) 267 + { 268 + struct device *dev = chip->dev; 269 + struct i2c_client *client = to_i2c_client(dev); 270 + s32 rc; 271 + int expected, status, burst_count, retries, size = 0; 272 + 273 + if (count < TPM_HEADER_SIZE) { 274 + i2c_nuvoton_ready(chip); /* return to idle */ 275 + dev_err(dev, "%s() count < header size\n", __func__); 276 + return -EIO; 277 + } 278 + for (retries = 0; retries < TPM_RETRY; retries++) { 279 + if (retries > 0) { 280 + /* if this is not the first trial, set responseRetry */ 281 + i2c_nuvoton_write_status(client, 282 + TPM_STS_RESPONSE_RETRY); 283 + } 284 + /* 285 + * read first available (> 10 bytes), including: 286 + * tag, paramsize, and result 287 + */ 288 + status = i2c_nuvoton_wait_for_data_avail( 289 + chip, chip->vendor.timeout_c, &chip->vendor.read_queue); 290 + if (status != 0) { 291 + dev_err(dev, "%s() timeout on dataAvail\n", __func__); 292 + size = -ETIMEDOUT; 293 + continue; 294 + } 295 + burst_count = i2c_nuvoton_get_burstcount(client, chip); 296 + if (burst_count < 0) { 297 + dev_err(dev, "%s() fail to get burstCount\n", __func__); 298 + size = -EIO; 299 + continue; 300 + } 301 + size = i2c_nuvoton_recv_data(client, chip, buf, 302 + burst_count); 303 + if (size < TPM_HEADER_SIZE) { 304 + dev_err(dev, "%s() fail to read header\n", __func__); 305 + size = -EIO; 306 + continue; 307 + } 308 + /* 309 + * convert number of expected bytes field from big endian 32 bit 310 + * to machine native 311 + */ 312 + expected = be32_to_cpu(*(__be32 *) (buf + 2)); 313 + if (expected > count) { 314 + dev_err(dev, "%s() expected > count\n", __func__); 315 + size = -EIO; 316 + continue; 317 + } 318 + rc = i2c_nuvoton_recv_data(client, chip, &buf[size], 319 + expected - size); 320 + size += rc; 321 + if (rc < 0 || size < expected) { 322 + dev_err(dev, "%s() fail to read remainder of result\n", 323 + __func__); 324 + size = -EIO; 325 + continue; 326 + } 327 + if (i2c_nuvoton_wait_for_stat( 328 + chip, TPM_STS_VALID | TPM_STS_DATA_AVAIL, 329 + TPM_STS_VALID, chip->vendor.timeout_c, 330 + NULL)) { 331 + dev_err(dev, "%s() error left over data\n", __func__); 332 + size = -ETIMEDOUT; 333 + continue; 334 + } 335 + break; 336 + } 337 + i2c_nuvoton_ready(chip); 338 + dev_dbg(chip->dev, "%s() -> %d\n", __func__, size); 339 + return size; 340 + } 341 + 342 + /* 343 + * Send TPM command. 344 + * 345 + * If interrupts are used (signaled by an irq set in the vendor structure) 346 + * tpm.c can skip polling for the data to be available as the interrupt is 347 + * waited for here 348 + */ 349 + static int i2c_nuvoton_send(struct tpm_chip *chip, u8 *buf, size_t len) 350 + { 351 + struct device *dev = chip->dev; 352 + struct i2c_client *client = to_i2c_client(dev); 353 + u32 ordinal; 354 + size_t count = 0; 355 + int burst_count, bytes2write, retries, rc = -EIO; 356 + 357 + for (retries = 0; retries < TPM_RETRY; retries++) { 358 + i2c_nuvoton_ready(chip); 359 + if (i2c_nuvoton_wait_for_stat(chip, TPM_STS_COMMAND_READY, 360 + TPM_STS_COMMAND_READY, 361 + chip->vendor.timeout_b, NULL)) { 362 + dev_err(dev, "%s() timeout on commandReady\n", 363 + __func__); 364 + rc = -EIO; 365 + continue; 366 + } 367 + rc = 0; 368 + while (count < len - 1) { 369 + burst_count = i2c_nuvoton_get_burstcount(client, 370 + chip); 371 + if (burst_count < 0) { 372 + dev_err(dev, "%s() fail get burstCount\n", 373 + __func__); 374 + rc = -EIO; 375 + break; 376 + } 377 + bytes2write = min_t(size_t, burst_count, 378 + len - 1 - count); 379 + rc = i2c_nuvoton_write_buf(client, TPM_DATA_FIFO_W, 380 + bytes2write, &buf[count]); 381 + if (rc < 0) { 382 + dev_err(dev, "%s() fail i2cWriteBuf\n", 383 + __func__); 384 + break; 385 + } 386 + dev_dbg(dev, "%s(%d):", __func__, bytes2write); 387 + count += bytes2write; 388 + rc = i2c_nuvoton_wait_for_stat(chip, 389 + TPM_STS_VALID | 390 + TPM_STS_EXPECT, 391 + TPM_STS_VALID | 392 + TPM_STS_EXPECT, 393 + chip->vendor.timeout_c, 394 + NULL); 395 + if (rc < 0) { 396 + dev_err(dev, "%s() timeout on Expect\n", 397 + __func__); 398 + rc = -ETIMEDOUT; 399 + break; 400 + } 401 + } 402 + if (rc < 0) 403 + continue; 404 + 405 + /* write last byte */ 406 + rc = i2c_nuvoton_write_buf(client, TPM_DATA_FIFO_W, 1, 407 + &buf[count]); 408 + if (rc < 0) { 409 + dev_err(dev, "%s() fail to write last byte\n", 410 + __func__); 411 + rc = -EIO; 412 + continue; 413 + } 414 + dev_dbg(dev, "%s(last): %02x", __func__, buf[count]); 415 + rc = i2c_nuvoton_wait_for_stat(chip, 416 + TPM_STS_VALID | TPM_STS_EXPECT, 417 + TPM_STS_VALID, 418 + chip->vendor.timeout_c, NULL); 419 + if (rc) { 420 + dev_err(dev, "%s() timeout on Expect to clear\n", 421 + __func__); 422 + rc = -ETIMEDOUT; 423 + continue; 424 + } 425 + break; 426 + } 427 + if (rc < 0) { 428 + /* retries == TPM_RETRY */ 429 + i2c_nuvoton_ready(chip); 430 + return rc; 431 + } 432 + /* execute the TPM command */ 433 + rc = i2c_nuvoton_write_status(client, TPM_STS_GO); 434 + if (rc < 0) { 435 + dev_err(dev, "%s() fail to write Go\n", __func__); 436 + i2c_nuvoton_ready(chip); 437 + return rc; 438 + } 439 + ordinal = be32_to_cpu(*((__be32 *) (buf + 6))); 440 + rc = i2c_nuvoton_wait_for_data_avail(chip, 441 + tpm_calc_ordinal_duration(chip, 442 + ordinal), 443 + &chip->vendor.read_queue); 444 + if (rc) { 445 + dev_err(dev, "%s() timeout command duration\n", __func__); 446 + i2c_nuvoton_ready(chip); 447 + return rc; 448 + } 449 + 450 + dev_dbg(dev, "%s() -> %zd\n", __func__, len); 451 + return len; 452 + } 453 + 454 + static bool i2c_nuvoton_req_canceled(struct tpm_chip *chip, u8 status) 455 + { 456 + return (status == TPM_STS_COMMAND_READY); 457 + } 458 + 459 + static const struct file_operations i2c_nuvoton_ops = { 460 + .owner = THIS_MODULE, 461 + .llseek = no_llseek, 462 + .open = tpm_open, 463 + .read = tpm_read, 464 + .write = tpm_write, 465 + .release = tpm_release, 466 + }; 467 + 468 + static DEVICE_ATTR(pubek, S_IRUGO, tpm_show_pubek, NULL); 469 + static DEVICE_ATTR(pcrs, S_IRUGO, tpm_show_pcrs, NULL); 470 + static DEVICE_ATTR(enabled, S_IRUGO, tpm_show_enabled, NULL); 471 + static DEVICE_ATTR(active, S_IRUGO, tpm_show_active, NULL); 472 + static DEVICE_ATTR(owned, S_IRUGO, tpm_show_owned, NULL); 473 + static DEVICE_ATTR(temp_deactivated, S_IRUGO, tpm_show_temp_deactivated, NULL); 474 + static DEVICE_ATTR(caps, S_IRUGO, tpm_show_caps, NULL); 475 + static DEVICE_ATTR(cancel, S_IWUSR | S_IWGRP, NULL, tpm_store_cancel); 476 + static DEVICE_ATTR(durations, S_IRUGO, tpm_show_durations, NULL); 477 + static DEVICE_ATTR(timeouts, S_IRUGO, tpm_show_timeouts, NULL); 478 + 479 + static struct attribute *i2c_nuvoton_attrs[] = { 480 + &dev_attr_pubek.attr, 481 + &dev_attr_pcrs.attr, 482 + &dev_attr_enabled.attr, 483 + &dev_attr_active.attr, 484 + &dev_attr_owned.attr, 485 + &dev_attr_temp_deactivated.attr, 486 + &dev_attr_caps.attr, 487 + &dev_attr_cancel.attr, 488 + &dev_attr_durations.attr, 489 + &dev_attr_timeouts.attr, 490 + NULL, 491 + }; 492 + 493 + static struct attribute_group i2c_nuvoton_attr_grp = { 494 + .attrs = i2c_nuvoton_attrs 495 + }; 496 + 497 + static const struct tpm_vendor_specific tpm_i2c = { 498 + .status = i2c_nuvoton_read_status, 499 + .recv = i2c_nuvoton_recv, 500 + .send = i2c_nuvoton_send, 501 + .cancel = i2c_nuvoton_ready, 502 + .req_complete_mask = TPM_STS_DATA_AVAIL | TPM_STS_VALID, 503 + .req_complete_val = TPM_STS_DATA_AVAIL | TPM_STS_VALID, 504 + .req_canceled = i2c_nuvoton_req_canceled, 505 + .attr_group = &i2c_nuvoton_attr_grp, 506 + .miscdev.fops = &i2c_nuvoton_ops, 507 + }; 508 + 509 + /* The only purpose for the handler is to signal to any waiting threads that 510 + * the interrupt is currently being asserted. The driver does not do any 511 + * processing triggered by interrupts, and the chip provides no way to mask at 512 + * the source (plus that would be slow over I2C). Run the IRQ as a one-shot, 513 + * this means it cannot be shared. */ 514 + static irqreturn_t i2c_nuvoton_int_handler(int dummy, void *dev_id) 515 + { 516 + struct tpm_chip *chip = dev_id; 517 + struct priv_data *priv = chip->vendor.priv; 518 + 519 + priv->intrs++; 520 + wake_up(&chip->vendor.read_queue); 521 + disable_irq_nosync(chip->vendor.irq); 522 + return IRQ_HANDLED; 523 + } 524 + 525 + static int get_vid(struct i2c_client *client, u32 *res) 526 + { 527 + static const u8 vid_did_rid_value[] = { 0x50, 0x10, 0xfe }; 528 + u32 temp; 529 + s32 rc; 530 + 531 + if (!i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_BYTE_DATA)) 532 + return -ENODEV; 533 + rc = i2c_nuvoton_read_buf(client, TPM_VID_DID_RID, 4, (u8 *)&temp); 534 + if (rc < 0) 535 + return rc; 536 + 537 + /* check WPCT301 values - ignore RID */ 538 + if (memcmp(&temp, vid_did_rid_value, sizeof(vid_did_rid_value))) { 539 + /* 540 + * f/w rev 2.81 has an issue where the VID_DID_RID is not 541 + * reporting the right value. so give it another chance at 542 + * offset 0x20 (FIFO_W). 543 + */ 544 + rc = i2c_nuvoton_read_buf(client, TPM_DATA_FIFO_W, 4, 545 + (u8 *) (&temp)); 546 + if (rc < 0) 547 + return rc; 548 + 549 + /* check WPCT301 values - ignore RID */ 550 + if (memcmp(&temp, vid_did_rid_value, 551 + sizeof(vid_did_rid_value))) 552 + return -ENODEV; 553 + } 554 + 555 + *res = temp; 556 + return 0; 557 + } 558 + 559 + static int i2c_nuvoton_probe(struct i2c_client *client, 560 + const struct i2c_device_id *id) 561 + { 562 + int rc; 563 + struct tpm_chip *chip; 564 + struct device *dev = &client->dev; 565 + u32 vid = 0; 566 + 567 + rc = get_vid(client, &vid); 568 + if (rc) 569 + return rc; 570 + 571 + dev_info(dev, "VID: %04X DID: %02X RID: %02X\n", (u16) vid, 572 + (u8) (vid >> 16), (u8) (vid >> 24)); 573 + 574 + chip = tpm_register_hardware(dev, &tpm_i2c); 575 + if (!chip) { 576 + dev_err(dev, "%s() error in tpm_register_hardware\n", __func__); 577 + return -ENODEV; 578 + } 579 + 580 + chip->vendor.priv = devm_kzalloc(dev, sizeof(struct priv_data), 581 + GFP_KERNEL); 582 + init_waitqueue_head(&chip->vendor.read_queue); 583 + init_waitqueue_head(&chip->vendor.int_queue); 584 + 585 + /* Default timeouts */ 586 + chip->vendor.timeout_a = msecs_to_jiffies(TPM_I2C_SHORT_TIMEOUT); 587 + chip->vendor.timeout_b = msecs_to_jiffies(TPM_I2C_LONG_TIMEOUT); 588 + chip->vendor.timeout_c = msecs_to_jiffies(TPM_I2C_SHORT_TIMEOUT); 589 + chip->vendor.timeout_d = msecs_to_jiffies(TPM_I2C_SHORT_TIMEOUT); 590 + 591 + /* 592 + * I2C intfcaps (interrupt capabilitieis) in the chip are hard coded to: 593 + * TPM_INTF_INT_LEVEL_LOW | TPM_INTF_DATA_AVAIL_INT 594 + * The IRQ should be set in the i2c_board_info (which is done 595 + * automatically in of_i2c_register_devices, for device tree users */ 596 + chip->vendor.irq = client->irq; 597 + 598 + if (chip->vendor.irq) { 599 + dev_dbg(dev, "%s() chip-vendor.irq\n", __func__); 600 + rc = devm_request_irq(dev, chip->vendor.irq, 601 + i2c_nuvoton_int_handler, 602 + IRQF_TRIGGER_LOW, 603 + chip->vendor.miscdev.name, 604 + chip); 605 + if (rc) { 606 + dev_err(dev, "%s() Unable to request irq: %d for use\n", 607 + __func__, chip->vendor.irq); 608 + chip->vendor.irq = 0; 609 + } else { 610 + /* Clear any pending interrupt */ 611 + i2c_nuvoton_ready(chip); 612 + /* - wait for TPM_STS==0xA0 (stsValid, commandReady) */ 613 + rc = i2c_nuvoton_wait_for_stat(chip, 614 + TPM_STS_COMMAND_READY, 615 + TPM_STS_COMMAND_READY, 616 + chip->vendor.timeout_b, 617 + NULL); 618 + if (rc == 0) { 619 + /* 620 + * TIS is in ready state 621 + * write dummy byte to enter reception state 622 + * TPM_DATA_FIFO_W <- rc (0) 623 + */ 624 + rc = i2c_nuvoton_write_buf(client, 625 + TPM_DATA_FIFO_W, 626 + 1, (u8 *) (&rc)); 627 + if (rc < 0) 628 + goto out_err; 629 + /* TPM_STS <- 0x40 (commandReady) */ 630 + i2c_nuvoton_ready(chip); 631 + } else { 632 + /* 633 + * timeout_b reached - command was 634 + * aborted. TIS should now be in idle state - 635 + * only TPM_STS_VALID should be set 636 + */ 637 + if (i2c_nuvoton_read_status(chip) != 638 + TPM_STS_VALID) { 639 + rc = -EIO; 640 + goto out_err; 641 + } 642 + } 643 + } 644 + } 645 + 646 + if (tpm_get_timeouts(chip)) { 647 + rc = -ENODEV; 648 + goto out_err; 649 + } 650 + 651 + if (tpm_do_selftest(chip)) { 652 + rc = -ENODEV; 653 + goto out_err; 654 + } 655 + 656 + return 0; 657 + 658 + out_err: 659 + tpm_dev_vendor_release(chip); 660 + tpm_remove_hardware(chip->dev); 661 + return rc; 662 + } 663 + 664 + static int i2c_nuvoton_remove(struct i2c_client *client) 665 + { 666 + struct device *dev = &(client->dev); 667 + struct tpm_chip *chip = dev_get_drvdata(dev); 668 + 669 + if (chip) 670 + tpm_dev_vendor_release(chip); 671 + tpm_remove_hardware(dev); 672 + kfree(chip); 673 + return 0; 674 + } 675 + 676 + 677 + static const struct i2c_device_id i2c_nuvoton_id[] = { 678 + {I2C_DRIVER_NAME, 0}, 679 + {} 680 + }; 681 + MODULE_DEVICE_TABLE(i2c, i2c_nuvoton_id); 682 + 683 + #ifdef CONFIG_OF 684 + static const struct of_device_id i2c_nuvoton_of_match[] = { 685 + {.compatible = "nuvoton,npct501"}, 686 + {.compatible = "winbond,wpct301"}, 687 + {}, 688 + }; 689 + MODULE_DEVICE_TABLE(of, i2c_nuvoton_of_match); 690 + #endif 691 + 692 + static SIMPLE_DEV_PM_OPS(i2c_nuvoton_pm_ops, tpm_pm_suspend, tpm_pm_resume); 693 + 694 + static struct i2c_driver i2c_nuvoton_driver = { 695 + .id_table = i2c_nuvoton_id, 696 + .probe = i2c_nuvoton_probe, 697 + .remove = i2c_nuvoton_remove, 698 + .driver = { 699 + .name = I2C_DRIVER_NAME, 700 + .owner = THIS_MODULE, 701 + .pm = &i2c_nuvoton_pm_ops, 702 + .of_match_table = of_match_ptr(i2c_nuvoton_of_match), 703 + }, 704 + }; 705 + 706 + module_i2c_driver(i2c_nuvoton_driver); 707 + 708 + MODULE_AUTHOR("Dan Morav (dan.morav@nuvoton.com)"); 709 + MODULE_DESCRIPTION("Nuvoton TPM I2C Driver"); 710 + MODULE_LICENSE("GPL");
+1 -11
drivers/char/tpm/tpm_i2c_stm_st33.c
··· 584 584 static DEVICE_ATTR(active, S_IRUGO, tpm_show_active, NULL); 585 585 static DEVICE_ATTR(owned, S_IRUGO, tpm_show_owned, NULL); 586 586 static DEVICE_ATTR(temp_deactivated, S_IRUGO, tpm_show_temp_deactivated, NULL); 587 - static DEVICE_ATTR(caps, S_IRUGO, tpm_show_caps_1_2, NULL); 587 + static DEVICE_ATTR(caps, S_IRUGO, tpm_show_caps, NULL); 588 588 static DEVICE_ATTR(cancel, S_IWUSR | S_IWGRP, NULL, tpm_store_cancel); 589 589 590 590 static struct attribute *stm_tpm_attrs[] = { ··· 746 746 747 747 tpm_get_timeouts(chip); 748 748 749 - i2c_set_clientdata(client, chip); 750 - 751 749 dev_info(chip->dev, "TPM I2C Initialized\n"); 752 750 return 0; 753 751 _irq_set: ··· 805 807 #ifdef CONFIG_PM_SLEEP 806 808 /* 807 809 * tpm_st33_i2c_pm_suspend suspend the TPM device 808 - * Added: Work around when suspend and no tpm application is running, suspend 809 - * may fail because chip->data_buffer is not set (only set in tpm_open in Linux 810 - * TPM core) 811 810 * @param: client, the i2c_client drescription (TPM I2C description). 812 811 * @param: mesg, the power management message. 813 812 * @return: 0 in case of success. 814 813 */ 815 814 static int tpm_st33_i2c_pm_suspend(struct device *dev) 816 815 { 817 - struct tpm_chip *chip = dev_get_drvdata(dev); 818 816 struct st33zp24_platform_data *pin_infos = dev->platform_data; 819 817 int ret = 0; 820 818 821 819 if (power_mgt) { 822 820 gpio_set_value(pin_infos->io_lpcpd, 0); 823 821 } else { 824 - if (chip->data_buffer == NULL) 825 - chip->data_buffer = pin_infos->tpm_i2c_buffer[0]; 826 822 ret = tpm_pm_suspend(dev); 827 823 } 828 824 return ret; ··· 841 849 TPM_STS_VALID) == TPM_STS_VALID, 842 850 chip->vendor.timeout_b); 843 851 } else { 844 - if (chip->data_buffer == NULL) 845 - chip->data_buffer = pin_infos->tpm_i2c_buffer[0]; 846 852 ret = tpm_pm_resume(dev); 847 853 if (!ret) 848 854 tpm_do_selftest(chip);
+3 -3
drivers/char/tpm/tpm_ibmvtpm.c
··· 98 98 99 99 if (count < len) { 100 100 dev_err(ibmvtpm->dev, 101 - "Invalid size in recv: count=%ld, crq_size=%d\n", 101 + "Invalid size in recv: count=%zd, crq_size=%d\n", 102 102 count, len); 103 103 return -EIO; 104 104 } ··· 136 136 137 137 if (count > ibmvtpm->rtce_size) { 138 138 dev_err(ibmvtpm->dev, 139 - "Invalid size in send: count=%ld, rtce_size=%d\n", 139 + "Invalid size in send: count=%zd, rtce_size=%d\n", 140 140 count, ibmvtpm->rtce_size); 141 141 return -EIO; 142 142 } ··· 419 419 static DEVICE_ATTR(owned, S_IRUGO, tpm_show_owned, NULL); 420 420 static DEVICE_ATTR(temp_deactivated, S_IRUGO, tpm_show_temp_deactivated, 421 421 NULL); 422 - static DEVICE_ATTR(caps, S_IRUGO, tpm_show_caps_1_2, NULL); 422 + static DEVICE_ATTR(caps, S_IRUGO, tpm_show_caps, NULL); 423 423 static DEVICE_ATTR(cancel, S_IWUSR | S_IWGRP, NULL, tpm_store_cancel); 424 424 static DEVICE_ATTR(durations, S_IRUGO, tpm_show_durations, NULL); 425 425 static DEVICE_ATTR(timeouts, S_IRUGO, tpm_show_timeouts, NULL);
-4
drivers/char/tpm/tpm_ppi.c
··· 452 452 { 453 453 return sysfs_create_group(parent, &ppi_attr_grp); 454 454 } 455 - EXPORT_SYMBOL_GPL(tpm_add_ppi); 456 455 457 456 void tpm_remove_ppi(struct kobject *parent) 458 457 { 459 458 sysfs_remove_group(parent, &ppi_attr_grp); 460 459 } 461 - EXPORT_SYMBOL_GPL(tpm_remove_ppi); 462 - 463 - MODULE_LICENSE("GPL");
+1 -1
drivers/char/tpm/tpm_tis.c
··· 448 448 static DEVICE_ATTR(owned, S_IRUGO, tpm_show_owned, NULL); 449 449 static DEVICE_ATTR(temp_deactivated, S_IRUGO, tpm_show_temp_deactivated, 450 450 NULL); 451 - static DEVICE_ATTR(caps, S_IRUGO, tpm_show_caps_1_2, NULL); 451 + static DEVICE_ATTR(caps, S_IRUGO, tpm_show_caps, NULL); 452 452 static DEVICE_ATTR(cancel, S_IWUSR | S_IWGRP, NULL, tpm_store_cancel); 453 453 static DEVICE_ATTR(durations, S_IRUGO, tpm_show_durations, NULL); 454 454 static DEVICE_ATTR(timeouts, S_IRUGO, tpm_show_timeouts, NULL);
-2
drivers/char/tpm/xen-tpmfront.c
··· 351 351 352 352 tpm_get_timeouts(priv->chip); 353 353 354 - dev_set_drvdata(&dev->dev, priv->chip); 355 - 356 354 return rv; 357 355 } 358 356
+40
include/crypto/hash_info.h
··· 1 + /* 2 + * Hash Info: Hash algorithms information 3 + * 4 + * Copyright (c) 2013 Dmitry Kasatkin <d.kasatkin@samsung.com> 5 + * 6 + * This program is free software; you can redistribute it and/or modify it 7 + * under the terms of the GNU General Public License as published by the Free 8 + * Software Foundation; either version 2 of the License, or (at your option) 9 + * any later version. 10 + * 11 + */ 12 + 13 + #ifndef _CRYPTO_HASH_INFO_H 14 + #define _CRYPTO_HASH_INFO_H 15 + 16 + #include <crypto/sha.h> 17 + #include <crypto/md5.h> 18 + 19 + #include <uapi/linux/hash_info.h> 20 + 21 + /* not defined in include/crypto/ */ 22 + #define RMD128_DIGEST_SIZE 16 23 + #define RMD160_DIGEST_SIZE 20 24 + #define RMD256_DIGEST_SIZE 32 25 + #define RMD320_DIGEST_SIZE 40 26 + 27 + /* not defined in include/crypto/ */ 28 + #define WP512_DIGEST_SIZE 64 29 + #define WP384_DIGEST_SIZE 48 30 + #define WP256_DIGEST_SIZE 32 31 + 32 + /* not defined in include/crypto/ */ 33 + #define TGR128_DIGEST_SIZE 16 34 + #define TGR160_DIGEST_SIZE 20 35 + #define TGR192_DIGEST_SIZE 24 36 + 37 + extern const char *const hash_algo_name[HASH_ALGO__LAST]; 38 + extern const int hash_digest_size[HASH_ALGO__LAST]; 39 + 40 + #endif /* _CRYPTO_HASH_INFO_H */
+9 -16
include/crypto/public_key.h
··· 15 15 #define _LINUX_PUBLIC_KEY_H 16 16 17 17 #include <linux/mpi.h> 18 + #include <crypto/hash_info.h> 18 19 19 20 enum pkey_algo { 20 21 PKEY_ALGO_DSA, ··· 23 22 PKEY_ALGO__LAST 24 23 }; 25 24 26 - extern const char *const pkey_algo[PKEY_ALGO__LAST]; 25 + extern const char *const pkey_algo_name[PKEY_ALGO__LAST]; 26 + extern const struct public_key_algorithm *pkey_algo[PKEY_ALGO__LAST]; 27 27 28 - enum pkey_hash_algo { 29 - PKEY_HASH_MD4, 30 - PKEY_HASH_MD5, 31 - PKEY_HASH_SHA1, 32 - PKEY_HASH_RIPE_MD_160, 33 - PKEY_HASH_SHA256, 34 - PKEY_HASH_SHA384, 35 - PKEY_HASH_SHA512, 36 - PKEY_HASH_SHA224, 37 - PKEY_HASH__LAST 38 - }; 39 - 40 - extern const char *const pkey_hash_algo[PKEY_HASH__LAST]; 28 + /* asymmetric key implementation supports only up to SHA224 */ 29 + #define PKEY_HASH__LAST (HASH_ALGO_SHA224 + 1) 41 30 42 31 enum pkey_id_type { 43 32 PKEY_ID_PGP, /* OpenPGP generated key ID */ ··· 35 44 PKEY_ID_TYPE__LAST 36 45 }; 37 46 38 - extern const char *const pkey_id_type[PKEY_ID_TYPE__LAST]; 47 + extern const char *const pkey_id_type_name[PKEY_ID_TYPE__LAST]; 39 48 40 49 /* 41 50 * Cryptographic data for the public-key subtype of the asymmetric key type. ··· 50 59 #define PKEY_CAN_DECRYPT 0x02 51 60 #define PKEY_CAN_SIGN 0x04 52 61 #define PKEY_CAN_VERIFY 0x08 62 + enum pkey_algo pkey_algo : 8; 53 63 enum pkey_id_type id_type : 8; 54 64 union { 55 65 MPI mpi[5]; ··· 80 88 u8 *digest; 81 89 u8 digest_size; /* Number of bytes in digest */ 82 90 u8 nr_mpi; /* Occupancy of mpi[] */ 83 - enum pkey_hash_algo pkey_hash_algo : 8; 91 + enum pkey_algo pkey_algo : 8; 92 + enum hash_algo pkey_hash_algo : 8; 84 93 union { 85 94 MPI mpi[2]; 86 95 struct {
+25
include/keys/big_key-type.h
··· 1 + /* Big capacity key type. 2 + * 3 + * Copyright (C) 2013 Red Hat, Inc. All Rights Reserved. 4 + * Written by David Howells (dhowells@redhat.com) 5 + * 6 + * This program is free software; you can redistribute it and/or 7 + * modify it under the terms of the GNU General Public License 8 + * as published by the Free Software Foundation; either version 9 + * 2 of the License, or (at your option) any later version. 10 + */ 11 + 12 + #ifndef _KEYS_BIG_KEY_TYPE_H 13 + #define _KEYS_BIG_KEY_TYPE_H 14 + 15 + #include <linux/key-type.h> 16 + 17 + extern struct key_type key_type_big_key; 18 + 19 + extern int big_key_instantiate(struct key *key, struct key_preparsed_payload *prep); 20 + extern void big_key_revoke(struct key *key); 21 + extern void big_key_destroy(struct key *key); 22 + extern void big_key_describe(const struct key *big_key, struct seq_file *m); 23 + extern long big_key_read(const struct key *key, char __user *buffer, size_t buflen); 24 + 25 + #endif /* _KEYS_BIG_KEY_TYPE_H */
+2 -15
include/keys/keyring-type.h
··· 1 1 /* Keyring key type 2 2 * 3 - * Copyright (C) 2008 Red Hat, Inc. All Rights Reserved. 3 + * Copyright (C) 2008, 2013 Red Hat, Inc. All Rights Reserved. 4 4 * Written by David Howells (dhowells@redhat.com) 5 5 * 6 6 * This program is free software; you can redistribute it and/or ··· 13 13 #define _KEYS_KEYRING_TYPE_H 14 14 15 15 #include <linux/key.h> 16 - #include <linux/rcupdate.h> 17 - 18 - /* 19 - * the keyring payload contains a list of the keys to which the keyring is 20 - * subscribed 21 - */ 22 - struct keyring_list { 23 - struct rcu_head rcu; /* RCU deletion hook */ 24 - unsigned short maxkeys; /* max keys this list can hold */ 25 - unsigned short nkeys; /* number of keys currently held */ 26 - unsigned short delkey; /* key to be unlinked by RCU */ 27 - struct key __rcu *keys[0]; 28 - }; 29 - 16 + #include <linux/assoc_array.h> 30 17 31 18 #endif /* _KEYS_KEYRING_TYPE_H */
+23
include/keys/system_keyring.h
··· 1 + /* System keyring containing trusted public keys. 2 + * 3 + * Copyright (C) 2013 Red Hat, Inc. All Rights Reserved. 4 + * Written by David Howells (dhowells@redhat.com) 5 + * 6 + * This program is free software; you can redistribute it and/or 7 + * modify it under the terms of the GNU General Public Licence 8 + * as published by the Free Software Foundation; either version 9 + * 2 of the Licence, or (at your option) any later version. 10 + */ 11 + 12 + #ifndef _KEYS_SYSTEM_KEYRING_H 13 + #define _KEYS_SYSTEM_KEYRING_H 14 + 15 + #ifdef CONFIG_SYSTEM_TRUSTED_KEYRING 16 + 17 + #include <linux/key.h> 18 + 19 + extern struct key *system_trusted_keyring; 20 + 21 + #endif 22 + 23 + #endif /* _KEYS_SYSTEM_KEYRING_H */
+92
include/linux/assoc_array.h
··· 1 + /* Generic associative array implementation. 2 + * 3 + * See Documentation/assoc_array.txt for information. 4 + * 5 + * Copyright (C) 2013 Red Hat, Inc. All Rights Reserved. 6 + * Written by David Howells (dhowells@redhat.com) 7 + * 8 + * This program is free software; you can redistribute it and/or 9 + * modify it under the terms of the GNU General Public Licence 10 + * as published by the Free Software Foundation; either version 11 + * 2 of the Licence, or (at your option) any later version. 12 + */ 13 + 14 + #ifndef _LINUX_ASSOC_ARRAY_H 15 + #define _LINUX_ASSOC_ARRAY_H 16 + 17 + #ifdef CONFIG_ASSOCIATIVE_ARRAY 18 + 19 + #include <linux/types.h> 20 + 21 + #define ASSOC_ARRAY_KEY_CHUNK_SIZE BITS_PER_LONG /* Key data retrieved in chunks of this size */ 22 + 23 + /* 24 + * Generic associative array. 25 + */ 26 + struct assoc_array { 27 + struct assoc_array_ptr *root; /* The node at the root of the tree */ 28 + unsigned long nr_leaves_on_tree; 29 + }; 30 + 31 + /* 32 + * Operations on objects and index keys for use by array manipulation routines. 33 + */ 34 + struct assoc_array_ops { 35 + /* Method to get a chunk of an index key from caller-supplied data */ 36 + unsigned long (*get_key_chunk)(const void *index_key, int level); 37 + 38 + /* Method to get a piece of an object's index key */ 39 + unsigned long (*get_object_key_chunk)(const void *object, int level); 40 + 41 + /* Is this the object we're looking for? */ 42 + bool (*compare_object)(const void *object, const void *index_key); 43 + 44 + /* How different are two objects, to a bit position in their keys? (or 45 + * -1 if they're the same) 46 + */ 47 + int (*diff_objects)(const void *a, const void *b); 48 + 49 + /* Method to free an object. */ 50 + void (*free_object)(void *object); 51 + }; 52 + 53 + /* 54 + * Access and manipulation functions. 55 + */ 56 + struct assoc_array_edit; 57 + 58 + static inline void assoc_array_init(struct assoc_array *array) 59 + { 60 + array->root = NULL; 61 + array->nr_leaves_on_tree = 0; 62 + } 63 + 64 + extern int assoc_array_iterate(const struct assoc_array *array, 65 + int (*iterator)(const void *object, 66 + void *iterator_data), 67 + void *iterator_data); 68 + extern void *assoc_array_find(const struct assoc_array *array, 69 + const struct assoc_array_ops *ops, 70 + const void *index_key); 71 + extern void assoc_array_destroy(struct assoc_array *array, 72 + const struct assoc_array_ops *ops); 73 + extern struct assoc_array_edit *assoc_array_insert(struct assoc_array *array, 74 + const struct assoc_array_ops *ops, 75 + const void *index_key, 76 + void *object); 77 + extern void assoc_array_insert_set_object(struct assoc_array_edit *edit, 78 + void *object); 79 + extern struct assoc_array_edit *assoc_array_delete(struct assoc_array *array, 80 + const struct assoc_array_ops *ops, 81 + const void *index_key); 82 + extern struct assoc_array_edit *assoc_array_clear(struct assoc_array *array, 83 + const struct assoc_array_ops *ops); 84 + extern void assoc_array_apply_edit(struct assoc_array_edit *edit); 85 + extern void assoc_array_cancel_edit(struct assoc_array_edit *edit); 86 + extern int assoc_array_gc(struct assoc_array *array, 87 + const struct assoc_array_ops *ops, 88 + bool (*iterator)(void *object, void *iterator_data), 89 + void *iterator_data); 90 + 91 + #endif /* CONFIG_ASSOCIATIVE_ARRAY */ 92 + #endif /* _LINUX_ASSOC_ARRAY_H */
+182
include/linux/assoc_array_priv.h
··· 1 + /* Private definitions for the generic associative array implementation. 2 + * 3 + * See Documentation/assoc_array.txt for information. 4 + * 5 + * Copyright (C) 2013 Red Hat, Inc. All Rights Reserved. 6 + * Written by David Howells (dhowells@redhat.com) 7 + * 8 + * This program is free software; you can redistribute it and/or 9 + * modify it under the terms of the GNU General Public Licence 10 + * as published by the Free Software Foundation; either version 11 + * 2 of the Licence, or (at your option) any later version. 12 + */ 13 + 14 + #ifndef _LINUX_ASSOC_ARRAY_PRIV_H 15 + #define _LINUX_ASSOC_ARRAY_PRIV_H 16 + 17 + #ifdef CONFIG_ASSOCIATIVE_ARRAY 18 + 19 + #include <linux/assoc_array.h> 20 + 21 + #define ASSOC_ARRAY_FAN_OUT 16 /* Number of slots per node */ 22 + #define ASSOC_ARRAY_FAN_MASK (ASSOC_ARRAY_FAN_OUT - 1) 23 + #define ASSOC_ARRAY_LEVEL_STEP (ilog2(ASSOC_ARRAY_FAN_OUT)) 24 + #define ASSOC_ARRAY_LEVEL_STEP_MASK (ASSOC_ARRAY_LEVEL_STEP - 1) 25 + #define ASSOC_ARRAY_KEY_CHUNK_MASK (ASSOC_ARRAY_KEY_CHUNK_SIZE - 1) 26 + #define ASSOC_ARRAY_KEY_CHUNK_SHIFT (ilog2(BITS_PER_LONG)) 27 + 28 + /* 29 + * Undefined type representing a pointer with type information in the bottom 30 + * two bits. 31 + */ 32 + struct assoc_array_ptr; 33 + 34 + /* 35 + * An N-way node in the tree. 36 + * 37 + * Each slot contains one of four things: 38 + * 39 + * (1) Nothing (NULL). 40 + * 41 + * (2) A leaf object (pointer types 0). 42 + * 43 + * (3) A next-level node (pointer type 1, subtype 0). 44 + * 45 + * (4) A shortcut (pointer type 1, subtype 1). 46 + * 47 + * The tree is optimised for search-by-ID, but permits reasonable iteration 48 + * also. 49 + * 50 + * The tree is navigated by constructing an index key consisting of an array of 51 + * segments, where each segment is ilog2(ASSOC_ARRAY_FAN_OUT) bits in size. 52 + * 53 + * The segments correspond to levels of the tree (the first segment is used at 54 + * level 0, the second at level 1, etc.). 55 + */ 56 + struct assoc_array_node { 57 + struct assoc_array_ptr *back_pointer; 58 + u8 parent_slot; 59 + struct assoc_array_ptr *slots[ASSOC_ARRAY_FAN_OUT]; 60 + unsigned long nr_leaves_on_branch; 61 + }; 62 + 63 + /* 64 + * A shortcut through the index space out to where a collection of nodes/leaves 65 + * with the same IDs live. 66 + */ 67 + struct assoc_array_shortcut { 68 + struct assoc_array_ptr *back_pointer; 69 + int parent_slot; 70 + int skip_to_level; 71 + struct assoc_array_ptr *next_node; 72 + unsigned long index_key[]; 73 + }; 74 + 75 + /* 76 + * Preallocation cache. 77 + */ 78 + struct assoc_array_edit { 79 + struct rcu_head rcu; 80 + struct assoc_array *array; 81 + const struct assoc_array_ops *ops; 82 + const struct assoc_array_ops *ops_for_excised_subtree; 83 + struct assoc_array_ptr *leaf; 84 + struct assoc_array_ptr **leaf_p; 85 + struct assoc_array_ptr *dead_leaf; 86 + struct assoc_array_ptr *new_meta[3]; 87 + struct assoc_array_ptr *excised_meta[1]; 88 + struct assoc_array_ptr *excised_subtree; 89 + struct assoc_array_ptr **set_backpointers[ASSOC_ARRAY_FAN_OUT]; 90 + struct assoc_array_ptr *set_backpointers_to; 91 + struct assoc_array_node *adjust_count_on; 92 + long adjust_count_by; 93 + struct { 94 + struct assoc_array_ptr **ptr; 95 + struct assoc_array_ptr *to; 96 + } set[2]; 97 + struct { 98 + u8 *p; 99 + u8 to; 100 + } set_parent_slot[1]; 101 + u8 segment_cache[ASSOC_ARRAY_FAN_OUT + 1]; 102 + }; 103 + 104 + /* 105 + * Internal tree member pointers are marked in the bottom one or two bits to 106 + * indicate what type they are so that we don't have to look behind every 107 + * pointer to see what it points to. 108 + * 109 + * We provide functions to test type annotations and to create and translate 110 + * the annotated pointers. 111 + */ 112 + #define ASSOC_ARRAY_PTR_TYPE_MASK 0x1UL 113 + #define ASSOC_ARRAY_PTR_LEAF_TYPE 0x0UL /* Points to leaf (or nowhere) */ 114 + #define ASSOC_ARRAY_PTR_META_TYPE 0x1UL /* Points to node or shortcut */ 115 + #define ASSOC_ARRAY_PTR_SUBTYPE_MASK 0x2UL 116 + #define ASSOC_ARRAY_PTR_NODE_SUBTYPE 0x0UL 117 + #define ASSOC_ARRAY_PTR_SHORTCUT_SUBTYPE 0x2UL 118 + 119 + static inline bool assoc_array_ptr_is_meta(const struct assoc_array_ptr *x) 120 + { 121 + return (unsigned long)x & ASSOC_ARRAY_PTR_TYPE_MASK; 122 + } 123 + static inline bool assoc_array_ptr_is_leaf(const struct assoc_array_ptr *x) 124 + { 125 + return !assoc_array_ptr_is_meta(x); 126 + } 127 + static inline bool assoc_array_ptr_is_shortcut(const struct assoc_array_ptr *x) 128 + { 129 + return (unsigned long)x & ASSOC_ARRAY_PTR_SUBTYPE_MASK; 130 + } 131 + static inline bool assoc_array_ptr_is_node(const struct assoc_array_ptr *x) 132 + { 133 + return !assoc_array_ptr_is_shortcut(x); 134 + } 135 + 136 + static inline void *assoc_array_ptr_to_leaf(const struct assoc_array_ptr *x) 137 + { 138 + return (void *)((unsigned long)x & ~ASSOC_ARRAY_PTR_TYPE_MASK); 139 + } 140 + 141 + static inline 142 + unsigned long __assoc_array_ptr_to_meta(const struct assoc_array_ptr *x) 143 + { 144 + return (unsigned long)x & 145 + ~(ASSOC_ARRAY_PTR_SUBTYPE_MASK | ASSOC_ARRAY_PTR_TYPE_MASK); 146 + } 147 + static inline 148 + struct assoc_array_node *assoc_array_ptr_to_node(const struct assoc_array_ptr *x) 149 + { 150 + return (struct assoc_array_node *)__assoc_array_ptr_to_meta(x); 151 + } 152 + static inline 153 + struct assoc_array_shortcut *assoc_array_ptr_to_shortcut(const struct assoc_array_ptr *x) 154 + { 155 + return (struct assoc_array_shortcut *)__assoc_array_ptr_to_meta(x); 156 + } 157 + 158 + static inline 159 + struct assoc_array_ptr *__assoc_array_x_to_ptr(const void *p, unsigned long t) 160 + { 161 + return (struct assoc_array_ptr *)((unsigned long)p | t); 162 + } 163 + static inline 164 + struct assoc_array_ptr *assoc_array_leaf_to_ptr(const void *p) 165 + { 166 + return __assoc_array_x_to_ptr(p, ASSOC_ARRAY_PTR_LEAF_TYPE); 167 + } 168 + static inline 169 + struct assoc_array_ptr *assoc_array_node_to_ptr(const struct assoc_array_node *p) 170 + { 171 + return __assoc_array_x_to_ptr( 172 + p, ASSOC_ARRAY_PTR_META_TYPE | ASSOC_ARRAY_PTR_NODE_SUBTYPE); 173 + } 174 + static inline 175 + struct assoc_array_ptr *assoc_array_shortcut_to_ptr(const struct assoc_array_shortcut *p) 176 + { 177 + return __assoc_array_x_to_ptr( 178 + p, ASSOC_ARRAY_PTR_META_TYPE | ASSOC_ARRAY_PTR_SHORTCUT_SUBTYPE); 179 + } 180 + 181 + #endif /* CONFIG_ASSOCIATIVE_ARRAY */ 182 + #endif /* _LINUX_ASSOC_ARRAY_PRIV_H */
+6
include/linux/key-type.h
··· 45 45 const void *data; /* Raw data */ 46 46 size_t datalen; /* Raw datalen */ 47 47 size_t quotalen; /* Quota length for proposed payload */ 48 + bool trusted; /* True if key is trusted */ 48 49 }; 49 50 50 51 typedef int (*request_key_actor_t)(struct key_construction *key, ··· 63 62 * function only needs to be called if the real datalen is different 64 63 */ 65 64 size_t def_datalen; 65 + 66 + /* Default key search algorithm. */ 67 + unsigned def_lookup_type; 68 + #define KEYRING_SEARCH_LOOKUP_DIRECT 0x0000 /* Direct lookup by description. */ 69 + #define KEYRING_SEARCH_LOOKUP_ITERATE 0x0001 /* Iterative search. */ 66 70 67 71 /* vet a description */ 68 72 int (*vet_description)(const char *description);
+37 -15
include/linux/key.h
··· 22 22 #include <linux/sysctl.h> 23 23 #include <linux/rwsem.h> 24 24 #include <linux/atomic.h> 25 + #include <linux/assoc_array.h> 25 26 26 27 #ifdef __KERNEL__ 27 28 #include <linux/uidgid.h> ··· 83 82 struct keyring_list; 84 83 struct keyring_name; 85 84 85 + struct keyring_index_key { 86 + struct key_type *type; 87 + const char *description; 88 + size_t desc_len; 89 + }; 90 + 86 91 /*****************************************************************************/ 87 92 /* 88 93 * key reference with possession attribute handling ··· 106 99 typedef struct __key_reference_with_attributes *key_ref_t; 107 100 108 101 static inline key_ref_t make_key_ref(const struct key *key, 109 - unsigned long possession) 102 + bool possession) 110 103 { 111 104 return (key_ref_t) ((unsigned long) key | possession); 112 105 } ··· 116 109 return (struct key *) ((unsigned long) key_ref & ~1UL); 117 110 } 118 111 119 - static inline unsigned long is_key_possessed(const key_ref_t key_ref) 112 + static inline bool is_key_possessed(const key_ref_t key_ref) 120 113 { 121 114 return (unsigned long) key_ref & 1UL; 122 115 } ··· 136 129 struct list_head graveyard_link; 137 130 struct rb_node serial_node; 138 131 }; 139 - struct key_type *type; /* type of key */ 140 132 struct rw_semaphore sem; /* change vs change sem */ 141 133 struct key_user *user; /* owner of this key */ 142 134 void *security; /* security data for this key */ ··· 168 162 #define KEY_FLAG_NEGATIVE 5 /* set if key is negative */ 169 163 #define KEY_FLAG_ROOT_CAN_CLEAR 6 /* set if key can be cleared by root without permission */ 170 164 #define KEY_FLAG_INVALIDATED 7 /* set if key has been invalidated */ 165 + #define KEY_FLAG_TRUSTED 8 /* set if key is trusted */ 166 + #define KEY_FLAG_TRUSTED_ONLY 9 /* set if keyring only accepts links to trusted keys */ 171 167 172 - /* the description string 173 - * - this is used to match a key against search criteria 174 - * - this should be a printable string 168 + /* the key type and key description string 169 + * - the desc is used to match a key against search criteria 170 + * - it should be a printable string 175 171 * - eg: for krb5 AFS, this might be "afs@REDHAT.COM" 176 172 */ 177 - char *description; 173 + union { 174 + struct keyring_index_key index_key; 175 + struct { 176 + struct key_type *type; /* type of key */ 177 + char *description; 178 + }; 179 + }; 178 180 179 181 /* type specific data 180 182 * - this is used by the keyring type to index the name ··· 199 185 * whatever 200 186 */ 201 187 union { 202 - unsigned long value; 203 - void __rcu *rcudata; 204 - void *data; 205 - struct keyring_list __rcu *subscriptions; 206 - } payload; 188 + union { 189 + unsigned long value; 190 + void __rcu *rcudata; 191 + void *data; 192 + void *data2[2]; 193 + } payload; 194 + struct assoc_array keys; 195 + }; 207 196 }; 208 197 209 198 extern struct key *key_alloc(struct key_type *type, ··· 220 203 #define KEY_ALLOC_IN_QUOTA 0x0000 /* add to quota, reject if would overrun */ 221 204 #define KEY_ALLOC_QUOTA_OVERRUN 0x0001 /* add to quota, permit even if overrun */ 222 205 #define KEY_ALLOC_NOT_IN_QUOTA 0x0002 /* not in quota */ 206 + #define KEY_ALLOC_TRUSTED 0x0004 /* Key should be flagged as trusted */ 223 207 224 208 extern void key_revoke(struct key *key); 225 209 extern void key_invalidate(struct key *key); 226 210 extern void key_put(struct key *key); 227 211 212 + static inline struct key *__key_get(struct key *key) 213 + { 214 + atomic_inc(&key->usage); 215 + return key; 216 + } 217 + 228 218 static inline struct key *key_get(struct key *key) 229 219 { 230 - if (key) 231 - atomic_inc(&key->usage); 232 - return key; 220 + return key ? __key_get(key) : key; 233 221 } 234 222 235 223 static inline void key_ref_put(key_ref_t key_ref)
+18 -8
include/linux/security.h
··· 1052 1052 * @xfrm_policy_delete_security: 1053 1053 * @ctx contains the xfrm_sec_ctx. 1054 1054 * Authorize deletion of xp->security. 1055 - * @xfrm_state_alloc_security: 1055 + * @xfrm_state_alloc: 1056 1056 * @x contains the xfrm_state being added to the Security Association 1057 1057 * Database by the XFRM system. 1058 1058 * @sec_ctx contains the security context information being provided by 1059 1059 * the user-level SA generation program (e.g., setkey or racoon). 1060 - * @secid contains the secid from which to take the mls portion of the context. 1061 1060 * Allocate a security structure to the x->security field; the security 1062 1061 * field is initialized to NULL when the xfrm_state is allocated. Set the 1063 - * context to correspond to either sec_ctx or polsec, with the mls portion 1064 - * taken from secid in the latter case. 1065 - * Return 0 if operation was successful (memory to allocate, legal context). 1062 + * context to correspond to sec_ctx. Return 0 if operation was successful 1063 + * (memory to allocate, legal context). 1064 + * @xfrm_state_alloc_acquire: 1065 + * @x contains the xfrm_state being added to the Security Association 1066 + * Database by the XFRM system. 1067 + * @polsec contains the policy's security context. 1068 + * @secid contains the secid from which to take the mls portion of the 1069 + * context. 1070 + * Allocate a security structure to the x->security field; the security 1071 + * field is initialized to NULL when the xfrm_state is allocated. Set the 1072 + * context to correspond to secid. Return 0 if operation was successful 1073 + * (memory to allocate, legal context). 1066 1074 * @xfrm_state_free_security: 1067 1075 * @x contains the xfrm_state. 1068 1076 * Deallocate x->security. ··· 1687 1679 int (*xfrm_policy_clone_security) (struct xfrm_sec_ctx *old_ctx, struct xfrm_sec_ctx **new_ctx); 1688 1680 void (*xfrm_policy_free_security) (struct xfrm_sec_ctx *ctx); 1689 1681 int (*xfrm_policy_delete_security) (struct xfrm_sec_ctx *ctx); 1690 - int (*xfrm_state_alloc_security) (struct xfrm_state *x, 1691 - struct xfrm_user_sec_ctx *sec_ctx, 1692 - u32 secid); 1682 + int (*xfrm_state_alloc) (struct xfrm_state *x, 1683 + struct xfrm_user_sec_ctx *sec_ctx); 1684 + int (*xfrm_state_alloc_acquire) (struct xfrm_state *x, 1685 + struct xfrm_sec_ctx *polsec, 1686 + u32 secid); 1693 1687 void (*xfrm_state_free_security) (struct xfrm_state *x); 1694 1688 int (*xfrm_state_delete_security) (struct xfrm_state *x); 1695 1689 int (*xfrm_policy_lookup) (struct xfrm_sec_ctx *ctx, u32 fl_secid, u8 dir);
+6
include/linux/user_namespace.h
··· 27 27 kuid_t owner; 28 28 kgid_t group; 29 29 unsigned int proc_inum; 30 + 31 + /* Register of per-UID persistent keyrings for this namespace */ 32 + #ifdef CONFIG_PERSISTENT_KEYRINGS 33 + struct key *persistent_keyring_register; 34 + struct rw_semaphore persistent_keyring_register_sem; 35 + #endif 30 36 }; 31 37 32 38 extern struct user_namespace init_user_ns;
+37
include/uapi/linux/hash_info.h
··· 1 + /* 2 + * Hash Info: Hash algorithms information 3 + * 4 + * Copyright (c) 2013 Dmitry Kasatkin <d.kasatkin@samsung.com> 5 + * 6 + * This program is free software; you can redistribute it and/or modify it 7 + * under the terms of the GNU General Public License as published by the Free 8 + * Software Foundation; either version 2 of the License, or (at your option) 9 + * any later version. 10 + * 11 + */ 12 + 13 + #ifndef _UAPI_LINUX_HASH_INFO_H 14 + #define _UAPI_LINUX_HASH_INFO_H 15 + 16 + enum hash_algo { 17 + HASH_ALGO_MD4, 18 + HASH_ALGO_MD5, 19 + HASH_ALGO_SHA1, 20 + HASH_ALGO_RIPE_MD_160, 21 + HASH_ALGO_SHA256, 22 + HASH_ALGO_SHA384, 23 + HASH_ALGO_SHA512, 24 + HASH_ALGO_SHA224, 25 + HASH_ALGO_RIPE_MD_128, 26 + HASH_ALGO_RIPE_MD_256, 27 + HASH_ALGO_RIPE_MD_320, 28 + HASH_ALGO_WP_256, 29 + HASH_ALGO_WP_384, 30 + HASH_ALGO_WP_512, 31 + HASH_ALGO_TGR_128, 32 + HASH_ALGO_TGR_160, 33 + HASH_ALGO_TGR_192, 34 + HASH_ALGO__LAST 35 + }; 36 + 37 + #endif /* _UAPI_LINUX_HASH_INFO_H */
+1
include/uapi/linux/keyctl.h
··· 56 56 #define KEYCTL_REJECT 19 /* reject a partially constructed key */ 57 57 #define KEYCTL_INSTANTIATE_IOV 20 /* instantiate a partially constructed key */ 58 58 #define KEYCTL_INVALIDATE 21 /* invalidate a key */ 59 + #define KEYCTL_GET_PERSISTENT 22 /* get a user's persistent keyring */ 59 60 60 61 #endif /* _LINUX_KEYCTL_H */
+13
init/Kconfig
··· 1655 1655 default 0 if BASE_FULL 1656 1656 default 1 if !BASE_FULL 1657 1657 1658 + config SYSTEM_TRUSTED_KEYRING 1659 + bool "Provide system-wide ring of trusted keys" 1660 + depends on KEYS 1661 + help 1662 + Provide a system keyring to which trusted keys can be added. Keys in 1663 + the keyring are considered to be trusted. Keys may be added at will 1664 + by the kernel from compiled-in data and from hardware key stores, but 1665 + userspace may only add extra keys if those keys can be verified by 1666 + keys already in the keyring. 1667 + 1668 + Keys in this keyring are used by module signature checking. 1669 + 1658 1670 menuconfig MODULES 1659 1671 bool "Enable loadable module support" 1660 1672 option modules ··· 1740 1728 config MODULE_SIG 1741 1729 bool "Module signature verification" 1742 1730 depends on MODULES 1731 + select SYSTEM_TRUSTED_KEYRING 1743 1732 select KEYS 1744 1733 select CRYPTO 1745 1734 select ASYMMETRIC_KEY_TYPE
+47 -13
kernel/Makefile
··· 41 41 obj-y += up.o 42 42 endif 43 43 obj-$(CONFIG_UID16) += uid16.o 44 + obj-$(CONFIG_SYSTEM_TRUSTED_KEYRING) += system_keyring.o system_certificates.o 44 45 obj-$(CONFIG_MODULES) += module.o 45 - obj-$(CONFIG_MODULE_SIG) += module_signing.o modsign_pubkey.o modsign_certificate.o 46 + obj-$(CONFIG_MODULE_SIG) += module_signing.o 46 47 obj-$(CONFIG_KALLSYMS) += kallsyms.o 47 48 obj-$(CONFIG_BSD_PROCESS_ACCT) += acct.o 48 49 obj-$(CONFIG_KEXEC) += kexec.o ··· 123 122 $(obj)/timeconst.h: $(obj)/hz.bc $(src)/timeconst.bc FORCE 124 123 $(call if_changed,bc) 125 124 125 + ############################################################################### 126 + # 127 + # Roll all the X.509 certificates that we can find together and pull them into 128 + # the kernel so that they get loaded into the system trusted keyring during 129 + # boot. 130 + # 131 + # We look in the source root and the build root for all files whose name ends 132 + # in ".x509". Unfortunately, this will generate duplicate filenames, so we 133 + # have make canonicalise the pathnames and then sort them to discard the 134 + # duplicates. 135 + # 136 + ############################################################################### 137 + ifeq ($(CONFIG_SYSTEM_TRUSTED_KEYRING),y) 138 + X509_CERTIFICATES-y := $(wildcard *.x509) $(wildcard $(srctree)/*.x509) 139 + X509_CERTIFICATES-$(CONFIG_MODULE_SIG) += signing_key.x509 140 + X509_CERTIFICATES := $(sort $(foreach CERT,$(X509_CERTIFICATES-y), \ 141 + $(or $(realpath $(CERT)),$(CERT)))) 142 + 143 + ifeq ($(X509_CERTIFICATES),) 144 + $(warning *** No X.509 certificates found ***) 145 + endif 146 + 147 + ifneq ($(wildcard $(obj)/.x509.list),) 148 + ifneq ($(shell cat $(obj)/.x509.list),$(X509_CERTIFICATES)) 149 + $(info X.509 certificate list changed) 150 + $(shell rm $(obj)/.x509.list) 151 + endif 152 + endif 153 + 154 + kernel/system_certificates.o: $(obj)/x509_certificate_list 155 + 156 + quiet_cmd_x509certs = CERTS $@ 157 + cmd_x509certs = cat $(X509_CERTIFICATES) /dev/null >$@ $(foreach X509,$(X509_CERTIFICATES),; echo " - Including cert $(X509)") 158 + 159 + targets += $(obj)/x509_certificate_list 160 + $(obj)/x509_certificate_list: $(X509_CERTIFICATES) $(obj)/.x509.list 161 + $(call if_changed,x509certs) 162 + 163 + targets += $(obj)/.x509.list 164 + $(obj)/.x509.list: 165 + @echo $(X509_CERTIFICATES) >$@ 166 + 167 + clean-files := x509_certificate_list .x509.list 168 + endif 169 + 126 170 ifeq ($(CONFIG_MODULE_SIG),y) 127 - # 128 - # Pull the signing certificate and any extra certificates into the kernel 129 - # 130 - 131 - quiet_cmd_touch = TOUCH $@ 132 - cmd_touch = touch $@ 133 - 134 - extra_certificates: 135 - $(call cmd,touch) 136 - 137 - kernel/modsign_certificate.o: signing_key.x509 extra_certificates 138 - 139 171 ############################################################################### 140 172 # 141 173 # If module signing is requested, say by allyesconfig, but a key has not been
-12
kernel/modsign_certificate.S
··· 1 - #include <linux/export.h> 2 - 3 - #define GLOBAL(name) \ 4 - .globl VMLINUX_SYMBOL(name); \ 5 - VMLINUX_SYMBOL(name): 6 - 7 - .section ".init.data","aw" 8 - 9 - GLOBAL(modsign_certificate_list) 10 - .incbin "signing_key.x509" 11 - .incbin "extra_certificates" 12 - GLOBAL(modsign_certificate_list_end)
-104
kernel/modsign_pubkey.c
··· 1 - /* Public keys for module signature verification 2 - * 3 - * Copyright (C) 2012 Red Hat, Inc. All Rights Reserved. 4 - * Written by David Howells (dhowells@redhat.com) 5 - * 6 - * This program is free software; you can redistribute it and/or 7 - * modify it under the terms of the GNU General Public Licence 8 - * as published by the Free Software Foundation; either version 9 - * 2 of the Licence, or (at your option) any later version. 10 - */ 11 - 12 - #include <linux/kernel.h> 13 - #include <linux/sched.h> 14 - #include <linux/cred.h> 15 - #include <linux/err.h> 16 - #include <keys/asymmetric-type.h> 17 - #include "module-internal.h" 18 - 19 - struct key *modsign_keyring; 20 - 21 - extern __initconst const u8 modsign_certificate_list[]; 22 - extern __initconst const u8 modsign_certificate_list_end[]; 23 - 24 - /* 25 - * We need to make sure ccache doesn't cache the .o file as it doesn't notice 26 - * if modsign.pub changes. 27 - */ 28 - static __initconst const char annoy_ccache[] = __TIME__ "foo"; 29 - 30 - /* 31 - * Load the compiled-in keys 32 - */ 33 - static __init int module_verify_init(void) 34 - { 35 - pr_notice("Initialise module verification\n"); 36 - 37 - modsign_keyring = keyring_alloc(".module_sign", 38 - KUIDT_INIT(0), KGIDT_INIT(0), 39 - current_cred(), 40 - ((KEY_POS_ALL & ~KEY_POS_SETATTR) | 41 - KEY_USR_VIEW | KEY_USR_READ), 42 - KEY_ALLOC_NOT_IN_QUOTA, NULL); 43 - if (IS_ERR(modsign_keyring)) 44 - panic("Can't allocate module signing keyring\n"); 45 - 46 - return 0; 47 - } 48 - 49 - /* 50 - * Must be initialised before we try and load the keys into the keyring. 51 - */ 52 - device_initcall(module_verify_init); 53 - 54 - /* 55 - * Load the compiled-in keys 56 - */ 57 - static __init int load_module_signing_keys(void) 58 - { 59 - key_ref_t key; 60 - const u8 *p, *end; 61 - size_t plen; 62 - 63 - pr_notice("Loading module verification certificates\n"); 64 - 65 - end = modsign_certificate_list_end; 66 - p = modsign_certificate_list; 67 - while (p < end) { 68 - /* Each cert begins with an ASN.1 SEQUENCE tag and must be more 69 - * than 256 bytes in size. 70 - */ 71 - if (end - p < 4) 72 - goto dodgy_cert; 73 - if (p[0] != 0x30 && 74 - p[1] != 0x82) 75 - goto dodgy_cert; 76 - plen = (p[2] << 8) | p[3]; 77 - plen += 4; 78 - if (plen > end - p) 79 - goto dodgy_cert; 80 - 81 - key = key_create_or_update(make_key_ref(modsign_keyring, 1), 82 - "asymmetric", 83 - NULL, 84 - p, 85 - plen, 86 - (KEY_POS_ALL & ~KEY_POS_SETATTR) | 87 - KEY_USR_VIEW, 88 - KEY_ALLOC_NOT_IN_QUOTA); 89 - if (IS_ERR(key)) 90 - pr_err("MODSIGN: Problem loading in-kernel X.509 certificate (%ld)\n", 91 - PTR_ERR(key)); 92 - else 93 - pr_notice("MODSIGN: Loaded cert '%s'\n", 94 - key_ref_to_ptr(key)->description); 95 - p += plen; 96 - } 97 - 98 - return 0; 99 - 100 - dodgy_cert: 101 - pr_err("MODSIGN: Problem parsing in-kernel X.509 certificate list\n"); 102 - return 0; 103 - } 104 - late_initcall(load_module_signing_keys);
-2
kernel/module-internal.h
··· 9 9 * 2 of the Licence, or (at your option) any later version. 10 10 */ 11 11 12 - extern struct key *modsign_keyring; 13 - 14 12 extern int mod_verify_sig(const void *mod, unsigned long *_modlen);
+6 -5
kernel/module_signing.c
··· 14 14 #include <crypto/public_key.h> 15 15 #include <crypto/hash.h> 16 16 #include <keys/asymmetric-type.h> 17 + #include <keys/system_keyring.h> 17 18 #include "module-internal.h" 18 19 19 20 /* ··· 29 28 */ 30 29 struct module_signature { 31 30 u8 algo; /* Public-key crypto algorithm [enum pkey_algo] */ 32 - u8 hash; /* Digest algorithm [enum pkey_hash_algo] */ 31 + u8 hash; /* Digest algorithm [enum hash_algo] */ 33 32 u8 id_type; /* Key identifier type [enum pkey_id_type] */ 34 33 u8 signer_len; /* Length of signer's name */ 35 34 u8 key_id_len; /* Length of key identifier */ ··· 40 39 /* 41 40 * Digest the module contents. 42 41 */ 43 - static struct public_key_signature *mod_make_digest(enum pkey_hash_algo hash, 42 + static struct public_key_signature *mod_make_digest(enum hash_algo hash, 44 43 const void *mod, 45 44 unsigned long modlen) 46 45 { ··· 55 54 /* Allocate the hashing algorithm we're going to need and find out how 56 55 * big the hash operational data will be. 57 56 */ 58 - tfm = crypto_alloc_shash(pkey_hash_algo[hash], 0, 0); 57 + tfm = crypto_alloc_shash(hash_algo_name[hash], 0, 0); 59 58 if (IS_ERR(tfm)) 60 59 return (PTR_ERR(tfm) == -ENOENT) ? ERR_PTR(-ENOPKG) : ERR_CAST(tfm); 61 60 ··· 158 157 159 158 pr_debug("Look up: \"%s\"\n", id); 160 159 161 - key = keyring_search(make_key_ref(modsign_keyring, 1), 160 + key = keyring_search(make_key_ref(system_trusted_keyring, 1), 162 161 &key_type_asymmetric, id); 163 162 if (IS_ERR(key)) 164 163 pr_warn("Request for unknown module key '%s' err %ld\n", ··· 218 217 return -ENOPKG; 219 218 220 219 if (ms.hash >= PKEY_HASH__LAST || 221 - !pkey_hash_algo[ms.hash]) 220 + !hash_algo_name[ms.hash]) 222 221 return -ENOPKG; 223 222 224 223 key = request_asymmetric_key(sig, ms.signer_len,
+10
kernel/system_certificates.S
··· 1 + #include <linux/export.h> 2 + #include <linux/init.h> 3 + 4 + __INITRODATA 5 + 6 + .globl VMLINUX_SYMBOL(system_certificate_list) 7 + VMLINUX_SYMBOL(system_certificate_list): 8 + .incbin "kernel/x509_certificate_list" 9 + .globl VMLINUX_SYMBOL(system_certificate_list_end) 10 + VMLINUX_SYMBOL(system_certificate_list_end):
+105
kernel/system_keyring.c
··· 1 + /* System trusted keyring for trusted public keys 2 + * 3 + * Copyright (C) 2012 Red Hat, Inc. All Rights Reserved. 4 + * Written by David Howells (dhowells@redhat.com) 5 + * 6 + * This program is free software; you can redistribute it and/or 7 + * modify it under the terms of the GNU General Public Licence 8 + * as published by the Free Software Foundation; either version 9 + * 2 of the Licence, or (at your option) any later version. 10 + */ 11 + 12 + #include <linux/export.h> 13 + #include <linux/kernel.h> 14 + #include <linux/sched.h> 15 + #include <linux/cred.h> 16 + #include <linux/err.h> 17 + #include <keys/asymmetric-type.h> 18 + #include <keys/system_keyring.h> 19 + #include "module-internal.h" 20 + 21 + struct key *system_trusted_keyring; 22 + EXPORT_SYMBOL_GPL(system_trusted_keyring); 23 + 24 + extern __initconst const u8 system_certificate_list[]; 25 + extern __initconst const u8 system_certificate_list_end[]; 26 + 27 + /* 28 + * Load the compiled-in keys 29 + */ 30 + static __init int system_trusted_keyring_init(void) 31 + { 32 + pr_notice("Initialise system trusted keyring\n"); 33 + 34 + system_trusted_keyring = 35 + keyring_alloc(".system_keyring", 36 + KUIDT_INIT(0), KGIDT_INIT(0), current_cred(), 37 + ((KEY_POS_ALL & ~KEY_POS_SETATTR) | 38 + KEY_USR_VIEW | KEY_USR_READ | KEY_USR_SEARCH), 39 + KEY_ALLOC_NOT_IN_QUOTA, NULL); 40 + if (IS_ERR(system_trusted_keyring)) 41 + panic("Can't allocate system trusted keyring\n"); 42 + 43 + set_bit(KEY_FLAG_TRUSTED_ONLY, &system_trusted_keyring->flags); 44 + return 0; 45 + } 46 + 47 + /* 48 + * Must be initialised before we try and load the keys into the keyring. 49 + */ 50 + device_initcall(system_trusted_keyring_init); 51 + 52 + /* 53 + * Load the compiled-in list of X.509 certificates. 54 + */ 55 + static __init int load_system_certificate_list(void) 56 + { 57 + key_ref_t key; 58 + const u8 *p, *end; 59 + size_t plen; 60 + 61 + pr_notice("Loading compiled-in X.509 certificates\n"); 62 + 63 + end = system_certificate_list_end; 64 + p = system_certificate_list; 65 + while (p < end) { 66 + /* Each cert begins with an ASN.1 SEQUENCE tag and must be more 67 + * than 256 bytes in size. 68 + */ 69 + if (end - p < 4) 70 + goto dodgy_cert; 71 + if (p[0] != 0x30 && 72 + p[1] != 0x82) 73 + goto dodgy_cert; 74 + plen = (p[2] << 8) | p[3]; 75 + plen += 4; 76 + if (plen > end - p) 77 + goto dodgy_cert; 78 + 79 + key = key_create_or_update(make_key_ref(system_trusted_keyring, 1), 80 + "asymmetric", 81 + NULL, 82 + p, 83 + plen, 84 + ((KEY_POS_ALL & ~KEY_POS_SETATTR) | 85 + KEY_USR_VIEW | KEY_USR_READ), 86 + KEY_ALLOC_NOT_IN_QUOTA | 87 + KEY_ALLOC_TRUSTED); 88 + if (IS_ERR(key)) { 89 + pr_err("Problem loading in-kernel X.509 certificate (%ld)\n", 90 + PTR_ERR(key)); 91 + } else { 92 + pr_notice("Loaded X.509 cert '%s'\n", 93 + key_ref_to_ptr(key)->description); 94 + key_ref_put(key); 95 + } 96 + p += plen; 97 + } 98 + 99 + return 0; 100 + 101 + dodgy_cert: 102 + pr_err("Problem parsing in-kernel X.509 certificate list\n"); 103 + return 0; 104 + } 105 + late_initcall(load_system_certificate_list);
+4
kernel/user.c
··· 51 51 .owner = GLOBAL_ROOT_UID, 52 52 .group = GLOBAL_ROOT_GID, 53 53 .proc_inum = PROC_USER_INIT_INO, 54 + #ifdef CONFIG_KEYS_KERBEROS_CACHE 55 + .krb_cache_register_sem = 56 + __RWSEM_INITIALIZER(init_user_ns.krb_cache_register_sem), 57 + #endif 54 58 }; 55 59 EXPORT_SYMBOL_GPL(init_user_ns); 56 60
+6
kernel/user_namespace.c
··· 101 101 102 102 set_cred_user_ns(new, ns); 103 103 104 + #ifdef CONFIG_PERSISTENT_KEYRINGS 105 + init_rwsem(&ns->persistent_keyring_register_sem); 106 + #endif 104 107 return 0; 105 108 } 106 109 ··· 133 130 134 131 do { 135 132 parent = ns->parent; 133 + #ifdef CONFIG_PERSISTENT_KEYRINGS 134 + key_put(ns->persistent_keyring_register); 135 + #endif 136 136 proc_free_inum(ns->proc_inum); 137 137 kmem_cache_free(user_ns_cachep, ns); 138 138 ns = parent;
+14
lib/Kconfig
··· 322 322 config BTREE 323 323 boolean 324 324 325 + config ASSOCIATIVE_ARRAY 326 + bool 327 + help 328 + Generic associative array. Can be searched and iterated over whilst 329 + it is being modified. It is also reasonably quick to search and 330 + modify. The algorithms are non-recursive, and the trees are highly 331 + capacious. 332 + 333 + See: 334 + 335 + Documentation/assoc_array.txt 336 + 337 + for more information. 338 + 325 339 config HAS_IOMEM 326 340 boolean 327 341 depends on !NO_IOMEM
+1
lib/Makefile
··· 47 47 obj-$(CONFIG_GENERIC_HWEIGHT) += hweight.o 48 48 49 49 obj-$(CONFIG_BTREE) += btree.o 50 + obj-$(CONFIG_ASSOCIATIVE_ARRAY) += assoc_array.o 50 51 obj-$(CONFIG_DEBUG_PREEMPT) += smp_processor_id.o 51 52 obj-$(CONFIG_DEBUG_LIST) += list_debug.o 52 53 obj-$(CONFIG_DEBUG_OBJECTS) += debugobjects.o
+1746
lib/assoc_array.c
··· 1 + /* Generic associative array implementation. 2 + * 3 + * See Documentation/assoc_array.txt for information. 4 + * 5 + * Copyright (C) 2013 Red Hat, Inc. All Rights Reserved. 6 + * Written by David Howells (dhowells@redhat.com) 7 + * 8 + * This program is free software; you can redistribute it and/or 9 + * modify it under the terms of the GNU General Public Licence 10 + * as published by the Free Software Foundation; either version 11 + * 2 of the Licence, or (at your option) any later version. 12 + */ 13 + //#define DEBUG 14 + #include <linux/slab.h> 15 + #include <linux/err.h> 16 + #include <linux/assoc_array_priv.h> 17 + 18 + /* 19 + * Iterate over an associative array. The caller must hold the RCU read lock 20 + * or better. 21 + */ 22 + static int assoc_array_subtree_iterate(const struct assoc_array_ptr *root, 23 + const struct assoc_array_ptr *stop, 24 + int (*iterator)(const void *leaf, 25 + void *iterator_data), 26 + void *iterator_data) 27 + { 28 + const struct assoc_array_shortcut *shortcut; 29 + const struct assoc_array_node *node; 30 + const struct assoc_array_ptr *cursor, *ptr, *parent; 31 + unsigned long has_meta; 32 + int slot, ret; 33 + 34 + cursor = root; 35 + 36 + begin_node: 37 + if (assoc_array_ptr_is_shortcut(cursor)) { 38 + /* Descend through a shortcut */ 39 + shortcut = assoc_array_ptr_to_shortcut(cursor); 40 + smp_read_barrier_depends(); 41 + cursor = ACCESS_ONCE(shortcut->next_node); 42 + } 43 + 44 + node = assoc_array_ptr_to_node(cursor); 45 + smp_read_barrier_depends(); 46 + slot = 0; 47 + 48 + /* We perform two passes of each node. 49 + * 50 + * The first pass does all the leaves in this node. This means we 51 + * don't miss any leaves if the node is split up by insertion whilst 52 + * we're iterating over the branches rooted here (we may, however, see 53 + * some leaves twice). 54 + */ 55 + has_meta = 0; 56 + for (; slot < ASSOC_ARRAY_FAN_OUT; slot++) { 57 + ptr = ACCESS_ONCE(node->slots[slot]); 58 + has_meta |= (unsigned long)ptr; 59 + if (ptr && assoc_array_ptr_is_leaf(ptr)) { 60 + /* We need a barrier between the read of the pointer 61 + * and dereferencing the pointer - but only if we are 62 + * actually going to dereference it. 63 + */ 64 + smp_read_barrier_depends(); 65 + 66 + /* Invoke the callback */ 67 + ret = iterator(assoc_array_ptr_to_leaf(ptr), 68 + iterator_data); 69 + if (ret) 70 + return ret; 71 + } 72 + } 73 + 74 + /* The second pass attends to all the metadata pointers. If we follow 75 + * one of these we may find that we don't come back here, but rather go 76 + * back to a replacement node with the leaves in a different layout. 77 + * 78 + * We are guaranteed to make progress, however, as the slot number for 79 + * a particular portion of the key space cannot change - and we 80 + * continue at the back pointer + 1. 81 + */ 82 + if (!(has_meta & ASSOC_ARRAY_PTR_META_TYPE)) 83 + goto finished_node; 84 + slot = 0; 85 + 86 + continue_node: 87 + node = assoc_array_ptr_to_node(cursor); 88 + smp_read_barrier_depends(); 89 + 90 + for (; slot < ASSOC_ARRAY_FAN_OUT; slot++) { 91 + ptr = ACCESS_ONCE(node->slots[slot]); 92 + if (assoc_array_ptr_is_meta(ptr)) { 93 + cursor = ptr; 94 + goto begin_node; 95 + } 96 + } 97 + 98 + finished_node: 99 + /* Move up to the parent (may need to skip back over a shortcut) */ 100 + parent = ACCESS_ONCE(node->back_pointer); 101 + slot = node->parent_slot; 102 + if (parent == stop) 103 + return 0; 104 + 105 + if (assoc_array_ptr_is_shortcut(parent)) { 106 + shortcut = assoc_array_ptr_to_shortcut(parent); 107 + smp_read_barrier_depends(); 108 + cursor = parent; 109 + parent = ACCESS_ONCE(shortcut->back_pointer); 110 + slot = shortcut->parent_slot; 111 + if (parent == stop) 112 + return 0; 113 + } 114 + 115 + /* Ascend to next slot in parent node */ 116 + cursor = parent; 117 + slot++; 118 + goto continue_node; 119 + } 120 + 121 + /** 122 + * assoc_array_iterate - Pass all objects in the array to a callback 123 + * @array: The array to iterate over. 124 + * @iterator: The callback function. 125 + * @iterator_data: Private data for the callback function. 126 + * 127 + * Iterate over all the objects in an associative array. Each one will be 128 + * presented to the iterator function. 129 + * 130 + * If the array is being modified concurrently with the iteration then it is 131 + * possible that some objects in the array will be passed to the iterator 132 + * callback more than once - though every object should be passed at least 133 + * once. If this is undesirable then the caller must lock against modification 134 + * for the duration of this function. 135 + * 136 + * The function will return 0 if no objects were in the array or else it will 137 + * return the result of the last iterator function called. Iteration stops 138 + * immediately if any call to the iteration function results in a non-zero 139 + * return. 140 + * 141 + * The caller should hold the RCU read lock or better if concurrent 142 + * modification is possible. 143 + */ 144 + int assoc_array_iterate(const struct assoc_array *array, 145 + int (*iterator)(const void *object, 146 + void *iterator_data), 147 + void *iterator_data) 148 + { 149 + struct assoc_array_ptr *root = ACCESS_ONCE(array->root); 150 + 151 + if (!root) 152 + return 0; 153 + return assoc_array_subtree_iterate(root, NULL, iterator, iterator_data); 154 + } 155 + 156 + enum assoc_array_walk_status { 157 + assoc_array_walk_tree_empty, 158 + assoc_array_walk_found_terminal_node, 159 + assoc_array_walk_found_wrong_shortcut, 160 + } status; 161 + 162 + struct assoc_array_walk_result { 163 + struct { 164 + struct assoc_array_node *node; /* Node in which leaf might be found */ 165 + int level; 166 + int slot; 167 + } terminal_node; 168 + struct { 169 + struct assoc_array_shortcut *shortcut; 170 + int level; 171 + int sc_level; 172 + unsigned long sc_segments; 173 + unsigned long dissimilarity; 174 + } wrong_shortcut; 175 + }; 176 + 177 + /* 178 + * Navigate through the internal tree looking for the closest node to the key. 179 + */ 180 + static enum assoc_array_walk_status 181 + assoc_array_walk(const struct assoc_array *array, 182 + const struct assoc_array_ops *ops, 183 + const void *index_key, 184 + struct assoc_array_walk_result *result) 185 + { 186 + struct assoc_array_shortcut *shortcut; 187 + struct assoc_array_node *node; 188 + struct assoc_array_ptr *cursor, *ptr; 189 + unsigned long sc_segments, dissimilarity; 190 + unsigned long segments; 191 + int level, sc_level, next_sc_level; 192 + int slot; 193 + 194 + pr_devel("-->%s()\n", __func__); 195 + 196 + cursor = ACCESS_ONCE(array->root); 197 + if (!cursor) 198 + return assoc_array_walk_tree_empty; 199 + 200 + level = 0; 201 + 202 + /* Use segments from the key for the new leaf to navigate through the 203 + * internal tree, skipping through nodes and shortcuts that are on 204 + * route to the destination. Eventually we'll come to a slot that is 205 + * either empty or contains a leaf at which point we've found a node in 206 + * which the leaf we're looking for might be found or into which it 207 + * should be inserted. 208 + */ 209 + jumped: 210 + segments = ops->get_key_chunk(index_key, level); 211 + pr_devel("segments[%d]: %lx\n", level, segments); 212 + 213 + if (assoc_array_ptr_is_shortcut(cursor)) 214 + goto follow_shortcut; 215 + 216 + consider_node: 217 + node = assoc_array_ptr_to_node(cursor); 218 + smp_read_barrier_depends(); 219 + 220 + slot = segments >> (level & ASSOC_ARRAY_KEY_CHUNK_MASK); 221 + slot &= ASSOC_ARRAY_FAN_MASK; 222 + ptr = ACCESS_ONCE(node->slots[slot]); 223 + 224 + pr_devel("consider slot %x [ix=%d type=%lu]\n", 225 + slot, level, (unsigned long)ptr & 3); 226 + 227 + if (!assoc_array_ptr_is_meta(ptr)) { 228 + /* The node doesn't have a node/shortcut pointer in the slot 229 + * corresponding to the index key that we have to follow. 230 + */ 231 + result->terminal_node.node = node; 232 + result->terminal_node.level = level; 233 + result->terminal_node.slot = slot; 234 + pr_devel("<--%s() = terminal_node\n", __func__); 235 + return assoc_array_walk_found_terminal_node; 236 + } 237 + 238 + if (assoc_array_ptr_is_node(ptr)) { 239 + /* There is a pointer to a node in the slot corresponding to 240 + * this index key segment, so we need to follow it. 241 + */ 242 + cursor = ptr; 243 + level += ASSOC_ARRAY_LEVEL_STEP; 244 + if ((level & ASSOC_ARRAY_KEY_CHUNK_MASK) != 0) 245 + goto consider_node; 246 + goto jumped; 247 + } 248 + 249 + /* There is a shortcut in the slot corresponding to the index key 250 + * segment. We follow the shortcut if its partial index key matches 251 + * this leaf's. Otherwise we need to split the shortcut. 252 + */ 253 + cursor = ptr; 254 + follow_shortcut: 255 + shortcut = assoc_array_ptr_to_shortcut(cursor); 256 + smp_read_barrier_depends(); 257 + pr_devel("shortcut to %d\n", shortcut->skip_to_level); 258 + sc_level = level + ASSOC_ARRAY_LEVEL_STEP; 259 + BUG_ON(sc_level > shortcut->skip_to_level); 260 + 261 + do { 262 + /* Check the leaf against the shortcut's index key a word at a 263 + * time, trimming the final word (the shortcut stores the index 264 + * key completely from the root to the shortcut's target). 265 + */ 266 + if ((sc_level & ASSOC_ARRAY_KEY_CHUNK_MASK) == 0) 267 + segments = ops->get_key_chunk(index_key, sc_level); 268 + 269 + sc_segments = shortcut->index_key[sc_level >> ASSOC_ARRAY_KEY_CHUNK_SHIFT]; 270 + dissimilarity = segments ^ sc_segments; 271 + 272 + if (round_up(sc_level, ASSOC_ARRAY_KEY_CHUNK_SIZE) > shortcut->skip_to_level) { 273 + /* Trim segments that are beyond the shortcut */ 274 + int shift = shortcut->skip_to_level & ASSOC_ARRAY_KEY_CHUNK_MASK; 275 + dissimilarity &= ~(ULONG_MAX << shift); 276 + next_sc_level = shortcut->skip_to_level; 277 + } else { 278 + next_sc_level = sc_level + ASSOC_ARRAY_KEY_CHUNK_SIZE; 279 + next_sc_level = round_down(next_sc_level, ASSOC_ARRAY_KEY_CHUNK_SIZE); 280 + } 281 + 282 + if (dissimilarity != 0) { 283 + /* This shortcut points elsewhere */ 284 + result->wrong_shortcut.shortcut = shortcut; 285 + result->wrong_shortcut.level = level; 286 + result->wrong_shortcut.sc_level = sc_level; 287 + result->wrong_shortcut.sc_segments = sc_segments; 288 + result->wrong_shortcut.dissimilarity = dissimilarity; 289 + return assoc_array_walk_found_wrong_shortcut; 290 + } 291 + 292 + sc_level = next_sc_level; 293 + } while (sc_level < shortcut->skip_to_level); 294 + 295 + /* The shortcut matches the leaf's index to this point. */ 296 + cursor = ACCESS_ONCE(shortcut->next_node); 297 + if (((level ^ sc_level) & ~ASSOC_ARRAY_KEY_CHUNK_MASK) != 0) { 298 + level = sc_level; 299 + goto jumped; 300 + } else { 301 + level = sc_level; 302 + goto consider_node; 303 + } 304 + } 305 + 306 + /** 307 + * assoc_array_find - Find an object by index key 308 + * @array: The associative array to search. 309 + * @ops: The operations to use. 310 + * @index_key: The key to the object. 311 + * 312 + * Find an object in an associative array by walking through the internal tree 313 + * to the node that should contain the object and then searching the leaves 314 + * there. NULL is returned if the requested object was not found in the array. 315 + * 316 + * The caller must hold the RCU read lock or better. 317 + */ 318 + void *assoc_array_find(const struct assoc_array *array, 319 + const struct assoc_array_ops *ops, 320 + const void *index_key) 321 + { 322 + struct assoc_array_walk_result result; 323 + const struct assoc_array_node *node; 324 + const struct assoc_array_ptr *ptr; 325 + const void *leaf; 326 + int slot; 327 + 328 + if (assoc_array_walk(array, ops, index_key, &result) != 329 + assoc_array_walk_found_terminal_node) 330 + return NULL; 331 + 332 + node = result.terminal_node.node; 333 + smp_read_barrier_depends(); 334 + 335 + /* If the target key is available to us, it's has to be pointed to by 336 + * the terminal node. 337 + */ 338 + for (slot = 0; slot < ASSOC_ARRAY_FAN_OUT; slot++) { 339 + ptr = ACCESS_ONCE(node->slots[slot]); 340 + if (ptr && assoc_array_ptr_is_leaf(ptr)) { 341 + /* We need a barrier between the read of the pointer 342 + * and dereferencing the pointer - but only if we are 343 + * actually going to dereference it. 344 + */ 345 + leaf = assoc_array_ptr_to_leaf(ptr); 346 + smp_read_barrier_depends(); 347 + if (ops->compare_object(leaf, index_key)) 348 + return (void *)leaf; 349 + } 350 + } 351 + 352 + return NULL; 353 + } 354 + 355 + /* 356 + * Destructively iterate over an associative array. The caller must prevent 357 + * other simultaneous accesses. 358 + */ 359 + static void assoc_array_destroy_subtree(struct assoc_array_ptr *root, 360 + const struct assoc_array_ops *ops) 361 + { 362 + struct assoc_array_shortcut *shortcut; 363 + struct assoc_array_node *node; 364 + struct assoc_array_ptr *cursor, *parent = NULL; 365 + int slot = -1; 366 + 367 + pr_devel("-->%s()\n", __func__); 368 + 369 + cursor = root; 370 + if (!cursor) { 371 + pr_devel("empty\n"); 372 + return; 373 + } 374 + 375 + move_to_meta: 376 + if (assoc_array_ptr_is_shortcut(cursor)) { 377 + /* Descend through a shortcut */ 378 + pr_devel("[%d] shortcut\n", slot); 379 + BUG_ON(!assoc_array_ptr_is_shortcut(cursor)); 380 + shortcut = assoc_array_ptr_to_shortcut(cursor); 381 + BUG_ON(shortcut->back_pointer != parent); 382 + BUG_ON(slot != -1 && shortcut->parent_slot != slot); 383 + parent = cursor; 384 + cursor = shortcut->next_node; 385 + slot = -1; 386 + BUG_ON(!assoc_array_ptr_is_node(cursor)); 387 + } 388 + 389 + pr_devel("[%d] node\n", slot); 390 + node = assoc_array_ptr_to_node(cursor); 391 + BUG_ON(node->back_pointer != parent); 392 + BUG_ON(slot != -1 && node->parent_slot != slot); 393 + slot = 0; 394 + 395 + continue_node: 396 + pr_devel("Node %p [back=%p]\n", node, node->back_pointer); 397 + for (; slot < ASSOC_ARRAY_FAN_OUT; slot++) { 398 + struct assoc_array_ptr *ptr = node->slots[slot]; 399 + if (!ptr) 400 + continue; 401 + if (assoc_array_ptr_is_meta(ptr)) { 402 + parent = cursor; 403 + cursor = ptr; 404 + goto move_to_meta; 405 + } 406 + 407 + if (ops) { 408 + pr_devel("[%d] free leaf\n", slot); 409 + ops->free_object(assoc_array_ptr_to_leaf(ptr)); 410 + } 411 + } 412 + 413 + parent = node->back_pointer; 414 + slot = node->parent_slot; 415 + pr_devel("free node\n"); 416 + kfree(node); 417 + if (!parent) 418 + return; /* Done */ 419 + 420 + /* Move back up to the parent (may need to free a shortcut on 421 + * the way up) */ 422 + if (assoc_array_ptr_is_shortcut(parent)) { 423 + shortcut = assoc_array_ptr_to_shortcut(parent); 424 + BUG_ON(shortcut->next_node != cursor); 425 + cursor = parent; 426 + parent = shortcut->back_pointer; 427 + slot = shortcut->parent_slot; 428 + pr_devel("free shortcut\n"); 429 + kfree(shortcut); 430 + if (!parent) 431 + return; 432 + 433 + BUG_ON(!assoc_array_ptr_is_node(parent)); 434 + } 435 + 436 + /* Ascend to next slot in parent node */ 437 + pr_devel("ascend to %p[%d]\n", parent, slot); 438 + cursor = parent; 439 + node = assoc_array_ptr_to_node(cursor); 440 + slot++; 441 + goto continue_node; 442 + } 443 + 444 + /** 445 + * assoc_array_destroy - Destroy an associative array 446 + * @array: The array to destroy. 447 + * @ops: The operations to use. 448 + * 449 + * Discard all metadata and free all objects in an associative array. The 450 + * array will be empty and ready to use again upon completion. This function 451 + * cannot fail. 452 + * 453 + * The caller must prevent all other accesses whilst this takes place as no 454 + * attempt is made to adjust pointers gracefully to permit RCU readlock-holding 455 + * accesses to continue. On the other hand, no memory allocation is required. 456 + */ 457 + void assoc_array_destroy(struct assoc_array *array, 458 + const struct assoc_array_ops *ops) 459 + { 460 + assoc_array_destroy_subtree(array->root, ops); 461 + array->root = NULL; 462 + } 463 + 464 + /* 465 + * Handle insertion into an empty tree. 466 + */ 467 + static bool assoc_array_insert_in_empty_tree(struct assoc_array_edit *edit) 468 + { 469 + struct assoc_array_node *new_n0; 470 + 471 + pr_devel("-->%s()\n", __func__); 472 + 473 + new_n0 = kzalloc(sizeof(struct assoc_array_node), GFP_KERNEL); 474 + if (!new_n0) 475 + return false; 476 + 477 + edit->new_meta[0] = assoc_array_node_to_ptr(new_n0); 478 + edit->leaf_p = &new_n0->slots[0]; 479 + edit->adjust_count_on = new_n0; 480 + edit->set[0].ptr = &edit->array->root; 481 + edit->set[0].to = assoc_array_node_to_ptr(new_n0); 482 + 483 + pr_devel("<--%s() = ok [no root]\n", __func__); 484 + return true; 485 + } 486 + 487 + /* 488 + * Handle insertion into a terminal node. 489 + */ 490 + static bool assoc_array_insert_into_terminal_node(struct assoc_array_edit *edit, 491 + const struct assoc_array_ops *ops, 492 + const void *index_key, 493 + struct assoc_array_walk_result *result) 494 + { 495 + struct assoc_array_shortcut *shortcut, *new_s0; 496 + struct assoc_array_node *node, *new_n0, *new_n1, *side; 497 + struct assoc_array_ptr *ptr; 498 + unsigned long dissimilarity, base_seg, blank; 499 + size_t keylen; 500 + bool have_meta; 501 + int level, diff; 502 + int slot, next_slot, free_slot, i, j; 503 + 504 + node = result->terminal_node.node; 505 + level = result->terminal_node.level; 506 + edit->segment_cache[ASSOC_ARRAY_FAN_OUT] = result->terminal_node.slot; 507 + 508 + pr_devel("-->%s()\n", __func__); 509 + 510 + /* We arrived at a node which doesn't have an onward node or shortcut 511 + * pointer that we have to follow. This means that (a) the leaf we 512 + * want must go here (either by insertion or replacement) or (b) we 513 + * need to split this node and insert in one of the fragments. 514 + */ 515 + free_slot = -1; 516 + 517 + /* Firstly, we have to check the leaves in this node to see if there's 518 + * a matching one we should replace in place. 519 + */ 520 + for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) { 521 + ptr = node->slots[i]; 522 + if (!ptr) { 523 + free_slot = i; 524 + continue; 525 + } 526 + if (ops->compare_object(assoc_array_ptr_to_leaf(ptr), index_key)) { 527 + pr_devel("replace in slot %d\n", i); 528 + edit->leaf_p = &node->slots[i]; 529 + edit->dead_leaf = node->slots[i]; 530 + pr_devel("<--%s() = ok [replace]\n", __func__); 531 + return true; 532 + } 533 + } 534 + 535 + /* If there is a free slot in this node then we can just insert the 536 + * leaf here. 537 + */ 538 + if (free_slot >= 0) { 539 + pr_devel("insert in free slot %d\n", free_slot); 540 + edit->leaf_p = &node->slots[free_slot]; 541 + edit->adjust_count_on = node; 542 + pr_devel("<--%s() = ok [insert]\n", __func__); 543 + return true; 544 + } 545 + 546 + /* The node has no spare slots - so we're either going to have to split 547 + * it or insert another node before it. 548 + * 549 + * Whatever, we're going to need at least two new nodes - so allocate 550 + * those now. We may also need a new shortcut, but we deal with that 551 + * when we need it. 552 + */ 553 + new_n0 = kzalloc(sizeof(struct assoc_array_node), GFP_KERNEL); 554 + if (!new_n0) 555 + return false; 556 + edit->new_meta[0] = assoc_array_node_to_ptr(new_n0); 557 + new_n1 = kzalloc(sizeof(struct assoc_array_node), GFP_KERNEL); 558 + if (!new_n1) 559 + return false; 560 + edit->new_meta[1] = assoc_array_node_to_ptr(new_n1); 561 + 562 + /* We need to find out how similar the leaves are. */ 563 + pr_devel("no spare slots\n"); 564 + have_meta = false; 565 + for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) { 566 + ptr = node->slots[i]; 567 + if (assoc_array_ptr_is_meta(ptr)) { 568 + edit->segment_cache[i] = 0xff; 569 + have_meta = true; 570 + continue; 571 + } 572 + base_seg = ops->get_object_key_chunk( 573 + assoc_array_ptr_to_leaf(ptr), level); 574 + base_seg >>= level & ASSOC_ARRAY_KEY_CHUNK_MASK; 575 + edit->segment_cache[i] = base_seg & ASSOC_ARRAY_FAN_MASK; 576 + } 577 + 578 + if (have_meta) { 579 + pr_devel("have meta\n"); 580 + goto split_node; 581 + } 582 + 583 + /* The node contains only leaves */ 584 + dissimilarity = 0; 585 + base_seg = edit->segment_cache[0]; 586 + for (i = 1; i < ASSOC_ARRAY_FAN_OUT; i++) 587 + dissimilarity |= edit->segment_cache[i] ^ base_seg; 588 + 589 + pr_devel("only leaves; dissimilarity=%lx\n", dissimilarity); 590 + 591 + if ((dissimilarity & ASSOC_ARRAY_FAN_MASK) == 0) { 592 + /* The old leaves all cluster in the same slot. We will need 593 + * to insert a shortcut if the new node wants to cluster with them. 594 + */ 595 + if ((edit->segment_cache[ASSOC_ARRAY_FAN_OUT] ^ base_seg) == 0) 596 + goto all_leaves_cluster_together; 597 + 598 + /* Otherwise we can just insert a new node ahead of the old 599 + * one. 600 + */ 601 + goto present_leaves_cluster_but_not_new_leaf; 602 + } 603 + 604 + split_node: 605 + pr_devel("split node\n"); 606 + 607 + /* We need to split the current node; we know that the node doesn't 608 + * simply contain a full set of leaves that cluster together (it 609 + * contains meta pointers and/or non-clustering leaves). 610 + * 611 + * We need to expel at least two leaves out of a set consisting of the 612 + * leaves in the node and the new leaf. 613 + * 614 + * We need a new node (n0) to replace the current one and a new node to 615 + * take the expelled nodes (n1). 616 + */ 617 + edit->set[0].to = assoc_array_node_to_ptr(new_n0); 618 + new_n0->back_pointer = node->back_pointer; 619 + new_n0->parent_slot = node->parent_slot; 620 + new_n1->back_pointer = assoc_array_node_to_ptr(new_n0); 621 + new_n1->parent_slot = -1; /* Need to calculate this */ 622 + 623 + do_split_node: 624 + pr_devel("do_split_node\n"); 625 + 626 + new_n0->nr_leaves_on_branch = node->nr_leaves_on_branch; 627 + new_n1->nr_leaves_on_branch = 0; 628 + 629 + /* Begin by finding two matching leaves. There have to be at least two 630 + * that match - even if there are meta pointers - because any leaf that 631 + * would match a slot with a meta pointer in it must be somewhere 632 + * behind that meta pointer and cannot be here. Further, given N 633 + * remaining leaf slots, we now have N+1 leaves to go in them. 634 + */ 635 + for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) { 636 + slot = edit->segment_cache[i]; 637 + if (slot != 0xff) 638 + for (j = i + 1; j < ASSOC_ARRAY_FAN_OUT + 1; j++) 639 + if (edit->segment_cache[j] == slot) 640 + goto found_slot_for_multiple_occupancy; 641 + } 642 + found_slot_for_multiple_occupancy: 643 + pr_devel("same slot: %x %x [%02x]\n", i, j, slot); 644 + BUG_ON(i >= ASSOC_ARRAY_FAN_OUT); 645 + BUG_ON(j >= ASSOC_ARRAY_FAN_OUT + 1); 646 + BUG_ON(slot >= ASSOC_ARRAY_FAN_OUT); 647 + 648 + new_n1->parent_slot = slot; 649 + 650 + /* Metadata pointers cannot change slot */ 651 + for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) 652 + if (assoc_array_ptr_is_meta(node->slots[i])) 653 + new_n0->slots[i] = node->slots[i]; 654 + else 655 + new_n0->slots[i] = NULL; 656 + BUG_ON(new_n0->slots[slot] != NULL); 657 + new_n0->slots[slot] = assoc_array_node_to_ptr(new_n1); 658 + 659 + /* Filter the leaf pointers between the new nodes */ 660 + free_slot = -1; 661 + next_slot = 0; 662 + for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) { 663 + if (assoc_array_ptr_is_meta(node->slots[i])) 664 + continue; 665 + if (edit->segment_cache[i] == slot) { 666 + new_n1->slots[next_slot++] = node->slots[i]; 667 + new_n1->nr_leaves_on_branch++; 668 + } else { 669 + do { 670 + free_slot++; 671 + } while (new_n0->slots[free_slot] != NULL); 672 + new_n0->slots[free_slot] = node->slots[i]; 673 + } 674 + } 675 + 676 + pr_devel("filtered: f=%x n=%x\n", free_slot, next_slot); 677 + 678 + if (edit->segment_cache[ASSOC_ARRAY_FAN_OUT] != slot) { 679 + do { 680 + free_slot++; 681 + } while (new_n0->slots[free_slot] != NULL); 682 + edit->leaf_p = &new_n0->slots[free_slot]; 683 + edit->adjust_count_on = new_n0; 684 + } else { 685 + edit->leaf_p = &new_n1->slots[next_slot++]; 686 + edit->adjust_count_on = new_n1; 687 + } 688 + 689 + BUG_ON(next_slot <= 1); 690 + 691 + edit->set_backpointers_to = assoc_array_node_to_ptr(new_n0); 692 + for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) { 693 + if (edit->segment_cache[i] == 0xff) { 694 + ptr = node->slots[i]; 695 + BUG_ON(assoc_array_ptr_is_leaf(ptr)); 696 + if (assoc_array_ptr_is_node(ptr)) { 697 + side = assoc_array_ptr_to_node(ptr); 698 + edit->set_backpointers[i] = &side->back_pointer; 699 + } else { 700 + shortcut = assoc_array_ptr_to_shortcut(ptr); 701 + edit->set_backpointers[i] = &shortcut->back_pointer; 702 + } 703 + } 704 + } 705 + 706 + ptr = node->back_pointer; 707 + if (!ptr) 708 + edit->set[0].ptr = &edit->array->root; 709 + else if (assoc_array_ptr_is_node(ptr)) 710 + edit->set[0].ptr = &assoc_array_ptr_to_node(ptr)->slots[node->parent_slot]; 711 + else 712 + edit->set[0].ptr = &assoc_array_ptr_to_shortcut(ptr)->next_node; 713 + edit->excised_meta[0] = assoc_array_node_to_ptr(node); 714 + pr_devel("<--%s() = ok [split node]\n", __func__); 715 + return true; 716 + 717 + present_leaves_cluster_but_not_new_leaf: 718 + /* All the old leaves cluster in the same slot, but the new leaf wants 719 + * to go into a different slot, so we create a new node to hold the new 720 + * leaf and a pointer to a new node holding all the old leaves. 721 + */ 722 + pr_devel("present leaves cluster but not new leaf\n"); 723 + 724 + new_n0->back_pointer = node->back_pointer; 725 + new_n0->parent_slot = node->parent_slot; 726 + new_n0->nr_leaves_on_branch = node->nr_leaves_on_branch; 727 + new_n1->back_pointer = assoc_array_node_to_ptr(new_n0); 728 + new_n1->parent_slot = edit->segment_cache[0]; 729 + new_n1->nr_leaves_on_branch = node->nr_leaves_on_branch; 730 + edit->adjust_count_on = new_n0; 731 + 732 + for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) 733 + new_n1->slots[i] = node->slots[i]; 734 + 735 + new_n0->slots[edit->segment_cache[0]] = assoc_array_node_to_ptr(new_n0); 736 + edit->leaf_p = &new_n0->slots[edit->segment_cache[ASSOC_ARRAY_FAN_OUT]]; 737 + 738 + edit->set[0].ptr = &assoc_array_ptr_to_node(node->back_pointer)->slots[node->parent_slot]; 739 + edit->set[0].to = assoc_array_node_to_ptr(new_n0); 740 + edit->excised_meta[0] = assoc_array_node_to_ptr(node); 741 + pr_devel("<--%s() = ok [insert node before]\n", __func__); 742 + return true; 743 + 744 + all_leaves_cluster_together: 745 + /* All the leaves, new and old, want to cluster together in this node 746 + * in the same slot, so we have to replace this node with a shortcut to 747 + * skip over the identical parts of the key and then place a pair of 748 + * nodes, one inside the other, at the end of the shortcut and 749 + * distribute the keys between them. 750 + * 751 + * Firstly we need to work out where the leaves start diverging as a 752 + * bit position into their keys so that we know how big the shortcut 753 + * needs to be. 754 + * 755 + * We only need to make a single pass of N of the N+1 leaves because if 756 + * any keys differ between themselves at bit X then at least one of 757 + * them must also differ with the base key at bit X or before. 758 + */ 759 + pr_devel("all leaves cluster together\n"); 760 + diff = INT_MAX; 761 + for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) { 762 + int x = ops->diff_objects(assoc_array_ptr_to_leaf(edit->leaf), 763 + assoc_array_ptr_to_leaf(node->slots[i])); 764 + if (x < diff) { 765 + BUG_ON(x < 0); 766 + diff = x; 767 + } 768 + } 769 + BUG_ON(diff == INT_MAX); 770 + BUG_ON(diff < level + ASSOC_ARRAY_LEVEL_STEP); 771 + 772 + keylen = round_up(diff, ASSOC_ARRAY_KEY_CHUNK_SIZE); 773 + keylen >>= ASSOC_ARRAY_KEY_CHUNK_SHIFT; 774 + 775 + new_s0 = kzalloc(sizeof(struct assoc_array_shortcut) + 776 + keylen * sizeof(unsigned long), GFP_KERNEL); 777 + if (!new_s0) 778 + return false; 779 + edit->new_meta[2] = assoc_array_shortcut_to_ptr(new_s0); 780 + 781 + edit->set[0].to = assoc_array_shortcut_to_ptr(new_s0); 782 + new_s0->back_pointer = node->back_pointer; 783 + new_s0->parent_slot = node->parent_slot; 784 + new_s0->next_node = assoc_array_node_to_ptr(new_n0); 785 + new_n0->back_pointer = assoc_array_shortcut_to_ptr(new_s0); 786 + new_n0->parent_slot = 0; 787 + new_n1->back_pointer = assoc_array_node_to_ptr(new_n0); 788 + new_n1->parent_slot = -1; /* Need to calculate this */ 789 + 790 + new_s0->skip_to_level = level = diff & ~ASSOC_ARRAY_LEVEL_STEP_MASK; 791 + pr_devel("skip_to_level = %d [diff %d]\n", level, diff); 792 + BUG_ON(level <= 0); 793 + 794 + for (i = 0; i < keylen; i++) 795 + new_s0->index_key[i] = 796 + ops->get_key_chunk(index_key, i * ASSOC_ARRAY_KEY_CHUNK_SIZE); 797 + 798 + blank = ULONG_MAX << (level & ASSOC_ARRAY_KEY_CHUNK_MASK); 799 + pr_devel("blank off [%zu] %d: %lx\n", keylen - 1, level, blank); 800 + new_s0->index_key[keylen - 1] &= ~blank; 801 + 802 + /* This now reduces to a node splitting exercise for which we'll need 803 + * to regenerate the disparity table. 804 + */ 805 + for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) { 806 + ptr = node->slots[i]; 807 + base_seg = ops->get_object_key_chunk(assoc_array_ptr_to_leaf(ptr), 808 + level); 809 + base_seg >>= level & ASSOC_ARRAY_KEY_CHUNK_MASK; 810 + edit->segment_cache[i] = base_seg & ASSOC_ARRAY_FAN_MASK; 811 + } 812 + 813 + base_seg = ops->get_key_chunk(index_key, level); 814 + base_seg >>= level & ASSOC_ARRAY_KEY_CHUNK_MASK; 815 + edit->segment_cache[ASSOC_ARRAY_FAN_OUT] = base_seg & ASSOC_ARRAY_FAN_MASK; 816 + goto do_split_node; 817 + } 818 + 819 + /* 820 + * Handle insertion into the middle of a shortcut. 821 + */ 822 + static bool assoc_array_insert_mid_shortcut(struct assoc_array_edit *edit, 823 + const struct assoc_array_ops *ops, 824 + struct assoc_array_walk_result *result) 825 + { 826 + struct assoc_array_shortcut *shortcut, *new_s0, *new_s1; 827 + struct assoc_array_node *node, *new_n0, *side; 828 + unsigned long sc_segments, dissimilarity, blank; 829 + size_t keylen; 830 + int level, sc_level, diff; 831 + int sc_slot; 832 + 833 + shortcut = result->wrong_shortcut.shortcut; 834 + level = result->wrong_shortcut.level; 835 + sc_level = result->wrong_shortcut.sc_level; 836 + sc_segments = result->wrong_shortcut.sc_segments; 837 + dissimilarity = result->wrong_shortcut.dissimilarity; 838 + 839 + pr_devel("-->%s(ix=%d dis=%lx scix=%d)\n", 840 + __func__, level, dissimilarity, sc_level); 841 + 842 + /* We need to split a shortcut and insert a node between the two 843 + * pieces. Zero-length pieces will be dispensed with entirely. 844 + * 845 + * First of all, we need to find out in which level the first 846 + * difference was. 847 + */ 848 + diff = __ffs(dissimilarity); 849 + diff &= ~ASSOC_ARRAY_LEVEL_STEP_MASK; 850 + diff += sc_level & ~ASSOC_ARRAY_KEY_CHUNK_MASK; 851 + pr_devel("diff=%d\n", diff); 852 + 853 + if (!shortcut->back_pointer) { 854 + edit->set[0].ptr = &edit->array->root; 855 + } else if (assoc_array_ptr_is_node(shortcut->back_pointer)) { 856 + node = assoc_array_ptr_to_node(shortcut->back_pointer); 857 + edit->set[0].ptr = &node->slots[shortcut->parent_slot]; 858 + } else { 859 + BUG(); 860 + } 861 + 862 + edit->excised_meta[0] = assoc_array_shortcut_to_ptr(shortcut); 863 + 864 + /* Create a new node now since we're going to need it anyway */ 865 + new_n0 = kzalloc(sizeof(struct assoc_array_node), GFP_KERNEL); 866 + if (!new_n0) 867 + return false; 868 + edit->new_meta[0] = assoc_array_node_to_ptr(new_n0); 869 + edit->adjust_count_on = new_n0; 870 + 871 + /* Insert a new shortcut before the new node if this segment isn't of 872 + * zero length - otherwise we just connect the new node directly to the 873 + * parent. 874 + */ 875 + level += ASSOC_ARRAY_LEVEL_STEP; 876 + if (diff > level) { 877 + pr_devel("pre-shortcut %d...%d\n", level, diff); 878 + keylen = round_up(diff, ASSOC_ARRAY_KEY_CHUNK_SIZE); 879 + keylen >>= ASSOC_ARRAY_KEY_CHUNK_SHIFT; 880 + 881 + new_s0 = kzalloc(sizeof(struct assoc_array_shortcut) + 882 + keylen * sizeof(unsigned long), GFP_KERNEL); 883 + if (!new_s0) 884 + return false; 885 + edit->new_meta[1] = assoc_array_shortcut_to_ptr(new_s0); 886 + edit->set[0].to = assoc_array_shortcut_to_ptr(new_s0); 887 + new_s0->back_pointer = shortcut->back_pointer; 888 + new_s0->parent_slot = shortcut->parent_slot; 889 + new_s0->next_node = assoc_array_node_to_ptr(new_n0); 890 + new_s0->skip_to_level = diff; 891 + 892 + new_n0->back_pointer = assoc_array_shortcut_to_ptr(new_s0); 893 + new_n0->parent_slot = 0; 894 + 895 + memcpy(new_s0->index_key, shortcut->index_key, 896 + keylen * sizeof(unsigned long)); 897 + 898 + blank = ULONG_MAX << (diff & ASSOC_ARRAY_KEY_CHUNK_MASK); 899 + pr_devel("blank off [%zu] %d: %lx\n", keylen - 1, diff, blank); 900 + new_s0->index_key[keylen - 1] &= ~blank; 901 + } else { 902 + pr_devel("no pre-shortcut\n"); 903 + edit->set[0].to = assoc_array_node_to_ptr(new_n0); 904 + new_n0->back_pointer = shortcut->back_pointer; 905 + new_n0->parent_slot = shortcut->parent_slot; 906 + } 907 + 908 + side = assoc_array_ptr_to_node(shortcut->next_node); 909 + new_n0->nr_leaves_on_branch = side->nr_leaves_on_branch; 910 + 911 + /* We need to know which slot in the new node is going to take a 912 + * metadata pointer. 913 + */ 914 + sc_slot = sc_segments >> (diff & ASSOC_ARRAY_KEY_CHUNK_MASK); 915 + sc_slot &= ASSOC_ARRAY_FAN_MASK; 916 + 917 + pr_devel("new slot %lx >> %d -> %d\n", 918 + sc_segments, diff & ASSOC_ARRAY_KEY_CHUNK_MASK, sc_slot); 919 + 920 + /* Determine whether we need to follow the new node with a replacement 921 + * for the current shortcut. We could in theory reuse the current 922 + * shortcut if its parent slot number doesn't change - but that's a 923 + * 1-in-16 chance so not worth expending the code upon. 924 + */ 925 + level = diff + ASSOC_ARRAY_LEVEL_STEP; 926 + if (level < shortcut->skip_to_level) { 927 + pr_devel("post-shortcut %d...%d\n", level, shortcut->skip_to_level); 928 + keylen = round_up(shortcut->skip_to_level, ASSOC_ARRAY_KEY_CHUNK_SIZE); 929 + keylen >>= ASSOC_ARRAY_KEY_CHUNK_SHIFT; 930 + 931 + new_s1 = kzalloc(sizeof(struct assoc_array_shortcut) + 932 + keylen * sizeof(unsigned long), GFP_KERNEL); 933 + if (!new_s1) 934 + return false; 935 + edit->new_meta[2] = assoc_array_shortcut_to_ptr(new_s1); 936 + 937 + new_s1->back_pointer = assoc_array_node_to_ptr(new_n0); 938 + new_s1->parent_slot = sc_slot; 939 + new_s1->next_node = shortcut->next_node; 940 + new_s1->skip_to_level = shortcut->skip_to_level; 941 + 942 + new_n0->slots[sc_slot] = assoc_array_shortcut_to_ptr(new_s1); 943 + 944 + memcpy(new_s1->index_key, shortcut->index_key, 945 + keylen * sizeof(unsigned long)); 946 + 947 + edit->set[1].ptr = &side->back_pointer; 948 + edit->set[1].to = assoc_array_shortcut_to_ptr(new_s1); 949 + } else { 950 + pr_devel("no post-shortcut\n"); 951 + 952 + /* We don't have to replace the pointed-to node as long as we 953 + * use memory barriers to make sure the parent slot number is 954 + * changed before the back pointer (the parent slot number is 955 + * irrelevant to the old parent shortcut). 956 + */ 957 + new_n0->slots[sc_slot] = shortcut->next_node; 958 + edit->set_parent_slot[0].p = &side->parent_slot; 959 + edit->set_parent_slot[0].to = sc_slot; 960 + edit->set[1].ptr = &side->back_pointer; 961 + edit->set[1].to = assoc_array_node_to_ptr(new_n0); 962 + } 963 + 964 + /* Install the new leaf in a spare slot in the new node. */ 965 + if (sc_slot == 0) 966 + edit->leaf_p = &new_n0->slots[1]; 967 + else 968 + edit->leaf_p = &new_n0->slots[0]; 969 + 970 + pr_devel("<--%s() = ok [split shortcut]\n", __func__); 971 + return edit; 972 + } 973 + 974 + /** 975 + * assoc_array_insert - Script insertion of an object into an associative array 976 + * @array: The array to insert into. 977 + * @ops: The operations to use. 978 + * @index_key: The key to insert at. 979 + * @object: The object to insert. 980 + * 981 + * Precalculate and preallocate a script for the insertion or replacement of an 982 + * object in an associative array. This results in an edit script that can 983 + * either be applied or cancelled. 984 + * 985 + * The function returns a pointer to an edit script or -ENOMEM. 986 + * 987 + * The caller should lock against other modifications and must continue to hold 988 + * the lock until assoc_array_apply_edit() has been called. 989 + * 990 + * Accesses to the tree may take place concurrently with this function, 991 + * provided they hold the RCU read lock. 992 + */ 993 + struct assoc_array_edit *assoc_array_insert(struct assoc_array *array, 994 + const struct assoc_array_ops *ops, 995 + const void *index_key, 996 + void *object) 997 + { 998 + struct assoc_array_walk_result result; 999 + struct assoc_array_edit *edit; 1000 + 1001 + pr_devel("-->%s()\n", __func__); 1002 + 1003 + /* The leaf pointer we're given must not have the bottom bit set as we 1004 + * use those for type-marking the pointer. NULL pointers are also not 1005 + * allowed as they indicate an empty slot but we have to allow them 1006 + * here as they can be updated later. 1007 + */ 1008 + BUG_ON(assoc_array_ptr_is_meta(object)); 1009 + 1010 + edit = kzalloc(sizeof(struct assoc_array_edit), GFP_KERNEL); 1011 + if (!edit) 1012 + return ERR_PTR(-ENOMEM); 1013 + edit->array = array; 1014 + edit->ops = ops; 1015 + edit->leaf = assoc_array_leaf_to_ptr(object); 1016 + edit->adjust_count_by = 1; 1017 + 1018 + switch (assoc_array_walk(array, ops, index_key, &result)) { 1019 + case assoc_array_walk_tree_empty: 1020 + /* Allocate a root node if there isn't one yet */ 1021 + if (!assoc_array_insert_in_empty_tree(edit)) 1022 + goto enomem; 1023 + return edit; 1024 + 1025 + case assoc_array_walk_found_terminal_node: 1026 + /* We found a node that doesn't have a node/shortcut pointer in 1027 + * the slot corresponding to the index key that we have to 1028 + * follow. 1029 + */ 1030 + if (!assoc_array_insert_into_terminal_node(edit, ops, index_key, 1031 + &result)) 1032 + goto enomem; 1033 + return edit; 1034 + 1035 + case assoc_array_walk_found_wrong_shortcut: 1036 + /* We found a shortcut that didn't match our key in a slot we 1037 + * needed to follow. 1038 + */ 1039 + if (!assoc_array_insert_mid_shortcut(edit, ops, &result)) 1040 + goto enomem; 1041 + return edit; 1042 + } 1043 + 1044 + enomem: 1045 + /* Clean up after an out of memory error */ 1046 + pr_devel("enomem\n"); 1047 + assoc_array_cancel_edit(edit); 1048 + return ERR_PTR(-ENOMEM); 1049 + } 1050 + 1051 + /** 1052 + * assoc_array_insert_set_object - Set the new object pointer in an edit script 1053 + * @edit: The edit script to modify. 1054 + * @object: The object pointer to set. 1055 + * 1056 + * Change the object to be inserted in an edit script. The object pointed to 1057 + * by the old object is not freed. This must be done prior to applying the 1058 + * script. 1059 + */ 1060 + void assoc_array_insert_set_object(struct assoc_array_edit *edit, void *object) 1061 + { 1062 + BUG_ON(!object); 1063 + edit->leaf = assoc_array_leaf_to_ptr(object); 1064 + } 1065 + 1066 + struct assoc_array_delete_collapse_context { 1067 + struct assoc_array_node *node; 1068 + const void *skip_leaf; 1069 + int slot; 1070 + }; 1071 + 1072 + /* 1073 + * Subtree collapse to node iterator. 1074 + */ 1075 + static int assoc_array_delete_collapse_iterator(const void *leaf, 1076 + void *iterator_data) 1077 + { 1078 + struct assoc_array_delete_collapse_context *collapse = iterator_data; 1079 + 1080 + if (leaf == collapse->skip_leaf) 1081 + return 0; 1082 + 1083 + BUG_ON(collapse->slot >= ASSOC_ARRAY_FAN_OUT); 1084 + 1085 + collapse->node->slots[collapse->slot++] = assoc_array_leaf_to_ptr(leaf); 1086 + return 0; 1087 + } 1088 + 1089 + /** 1090 + * assoc_array_delete - Script deletion of an object from an associative array 1091 + * @array: The array to search. 1092 + * @ops: The operations to use. 1093 + * @index_key: The key to the object. 1094 + * 1095 + * Precalculate and preallocate a script for the deletion of an object from an 1096 + * associative array. This results in an edit script that can either be 1097 + * applied or cancelled. 1098 + * 1099 + * The function returns a pointer to an edit script if the object was found, 1100 + * NULL if the object was not found or -ENOMEM. 1101 + * 1102 + * The caller should lock against other modifications and must continue to hold 1103 + * the lock until assoc_array_apply_edit() has been called. 1104 + * 1105 + * Accesses to the tree may take place concurrently with this function, 1106 + * provided they hold the RCU read lock. 1107 + */ 1108 + struct assoc_array_edit *assoc_array_delete(struct assoc_array *array, 1109 + const struct assoc_array_ops *ops, 1110 + const void *index_key) 1111 + { 1112 + struct assoc_array_delete_collapse_context collapse; 1113 + struct assoc_array_walk_result result; 1114 + struct assoc_array_node *node, *new_n0; 1115 + struct assoc_array_edit *edit; 1116 + struct assoc_array_ptr *ptr; 1117 + bool has_meta; 1118 + int slot, i; 1119 + 1120 + pr_devel("-->%s()\n", __func__); 1121 + 1122 + edit = kzalloc(sizeof(struct assoc_array_edit), GFP_KERNEL); 1123 + if (!edit) 1124 + return ERR_PTR(-ENOMEM); 1125 + edit->array = array; 1126 + edit->ops = ops; 1127 + edit->adjust_count_by = -1; 1128 + 1129 + switch (assoc_array_walk(array, ops, index_key, &result)) { 1130 + case assoc_array_walk_found_terminal_node: 1131 + /* We found a node that should contain the leaf we've been 1132 + * asked to remove - *if* it's in the tree. 1133 + */ 1134 + pr_devel("terminal_node\n"); 1135 + node = result.terminal_node.node; 1136 + 1137 + for (slot = 0; slot < ASSOC_ARRAY_FAN_OUT; slot++) { 1138 + ptr = node->slots[slot]; 1139 + if (ptr && 1140 + assoc_array_ptr_is_leaf(ptr) && 1141 + ops->compare_object(assoc_array_ptr_to_leaf(ptr), 1142 + index_key)) 1143 + goto found_leaf; 1144 + } 1145 + case assoc_array_walk_tree_empty: 1146 + case assoc_array_walk_found_wrong_shortcut: 1147 + default: 1148 + assoc_array_cancel_edit(edit); 1149 + pr_devel("not found\n"); 1150 + return NULL; 1151 + } 1152 + 1153 + found_leaf: 1154 + BUG_ON(array->nr_leaves_on_tree <= 0); 1155 + 1156 + /* In the simplest form of deletion we just clear the slot and release 1157 + * the leaf after a suitable interval. 1158 + */ 1159 + edit->dead_leaf = node->slots[slot]; 1160 + edit->set[0].ptr = &node->slots[slot]; 1161 + edit->set[0].to = NULL; 1162 + edit->adjust_count_on = node; 1163 + 1164 + /* If that concludes erasure of the last leaf, then delete the entire 1165 + * internal array. 1166 + */ 1167 + if (array->nr_leaves_on_tree == 1) { 1168 + edit->set[1].ptr = &array->root; 1169 + edit->set[1].to = NULL; 1170 + edit->adjust_count_on = NULL; 1171 + edit->excised_subtree = array->root; 1172 + pr_devel("all gone\n"); 1173 + return edit; 1174 + } 1175 + 1176 + /* However, we'd also like to clear up some metadata blocks if we 1177 + * possibly can. 1178 + * 1179 + * We go for a simple algorithm of: if this node has FAN_OUT or fewer 1180 + * leaves in it, then attempt to collapse it - and attempt to 1181 + * recursively collapse up the tree. 1182 + * 1183 + * We could also try and collapse in partially filled subtrees to take 1184 + * up space in this node. 1185 + */ 1186 + if (node->nr_leaves_on_branch <= ASSOC_ARRAY_FAN_OUT + 1) { 1187 + struct assoc_array_node *parent, *grandparent; 1188 + struct assoc_array_ptr *ptr; 1189 + 1190 + /* First of all, we need to know if this node has metadata so 1191 + * that we don't try collapsing if all the leaves are already 1192 + * here. 1193 + */ 1194 + has_meta = false; 1195 + for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) { 1196 + ptr = node->slots[i]; 1197 + if (assoc_array_ptr_is_meta(ptr)) { 1198 + has_meta = true; 1199 + break; 1200 + } 1201 + } 1202 + 1203 + pr_devel("leaves: %ld [m=%d]\n", 1204 + node->nr_leaves_on_branch - 1, has_meta); 1205 + 1206 + /* Look further up the tree to see if we can collapse this node 1207 + * into a more proximal node too. 1208 + */ 1209 + parent = node; 1210 + collapse_up: 1211 + pr_devel("collapse subtree: %ld\n", parent->nr_leaves_on_branch); 1212 + 1213 + ptr = parent->back_pointer; 1214 + if (!ptr) 1215 + goto do_collapse; 1216 + if (assoc_array_ptr_is_shortcut(ptr)) { 1217 + struct assoc_array_shortcut *s = assoc_array_ptr_to_shortcut(ptr); 1218 + ptr = s->back_pointer; 1219 + if (!ptr) 1220 + goto do_collapse; 1221 + } 1222 + 1223 + grandparent = assoc_array_ptr_to_node(ptr); 1224 + if (grandparent->nr_leaves_on_branch <= ASSOC_ARRAY_FAN_OUT + 1) { 1225 + parent = grandparent; 1226 + goto collapse_up; 1227 + } 1228 + 1229 + do_collapse: 1230 + /* There's no point collapsing if the original node has no meta 1231 + * pointers to discard and if we didn't merge into one of that 1232 + * node's ancestry. 1233 + */ 1234 + if (has_meta || parent != node) { 1235 + node = parent; 1236 + 1237 + /* Create a new node to collapse into */ 1238 + new_n0 = kzalloc(sizeof(struct assoc_array_node), GFP_KERNEL); 1239 + if (!new_n0) 1240 + goto enomem; 1241 + edit->new_meta[0] = assoc_array_node_to_ptr(new_n0); 1242 + 1243 + new_n0->back_pointer = node->back_pointer; 1244 + new_n0->parent_slot = node->parent_slot; 1245 + new_n0->nr_leaves_on_branch = node->nr_leaves_on_branch; 1246 + edit->adjust_count_on = new_n0; 1247 + 1248 + collapse.node = new_n0; 1249 + collapse.skip_leaf = assoc_array_ptr_to_leaf(edit->dead_leaf); 1250 + collapse.slot = 0; 1251 + assoc_array_subtree_iterate(assoc_array_node_to_ptr(node), 1252 + node->back_pointer, 1253 + assoc_array_delete_collapse_iterator, 1254 + &collapse); 1255 + pr_devel("collapsed %d,%lu\n", collapse.slot, new_n0->nr_leaves_on_branch); 1256 + BUG_ON(collapse.slot != new_n0->nr_leaves_on_branch - 1); 1257 + 1258 + if (!node->back_pointer) { 1259 + edit->set[1].ptr = &array->root; 1260 + } else if (assoc_array_ptr_is_leaf(node->back_pointer)) { 1261 + BUG(); 1262 + } else if (assoc_array_ptr_is_node(node->back_pointer)) { 1263 + struct assoc_array_node *p = 1264 + assoc_array_ptr_to_node(node->back_pointer); 1265 + edit->set[1].ptr = &p->slots[node->parent_slot]; 1266 + } else if (assoc_array_ptr_is_shortcut(node->back_pointer)) { 1267 + struct assoc_array_shortcut *s = 1268 + assoc_array_ptr_to_shortcut(node->back_pointer); 1269 + edit->set[1].ptr = &s->next_node; 1270 + } 1271 + edit->set[1].to = assoc_array_node_to_ptr(new_n0); 1272 + edit->excised_subtree = assoc_array_node_to_ptr(node); 1273 + } 1274 + } 1275 + 1276 + return edit; 1277 + 1278 + enomem: 1279 + /* Clean up after an out of memory error */ 1280 + pr_devel("enomem\n"); 1281 + assoc_array_cancel_edit(edit); 1282 + return ERR_PTR(-ENOMEM); 1283 + } 1284 + 1285 + /** 1286 + * assoc_array_clear - Script deletion of all objects from an associative array 1287 + * @array: The array to clear. 1288 + * @ops: The operations to use. 1289 + * 1290 + * Precalculate and preallocate a script for the deletion of all the objects 1291 + * from an associative array. This results in an edit script that can either 1292 + * be applied or cancelled. 1293 + * 1294 + * The function returns a pointer to an edit script if there are objects to be 1295 + * deleted, NULL if there are no objects in the array or -ENOMEM. 1296 + * 1297 + * The caller should lock against other modifications and must continue to hold 1298 + * the lock until assoc_array_apply_edit() has been called. 1299 + * 1300 + * Accesses to the tree may take place concurrently with this function, 1301 + * provided they hold the RCU read lock. 1302 + */ 1303 + struct assoc_array_edit *assoc_array_clear(struct assoc_array *array, 1304 + const struct assoc_array_ops *ops) 1305 + { 1306 + struct assoc_array_edit *edit; 1307 + 1308 + pr_devel("-->%s()\n", __func__); 1309 + 1310 + if (!array->root) 1311 + return NULL; 1312 + 1313 + edit = kzalloc(sizeof(struct assoc_array_edit), GFP_KERNEL); 1314 + if (!edit) 1315 + return ERR_PTR(-ENOMEM); 1316 + edit->array = array; 1317 + edit->ops = ops; 1318 + edit->set[1].ptr = &array->root; 1319 + edit->set[1].to = NULL; 1320 + edit->excised_subtree = array->root; 1321 + edit->ops_for_excised_subtree = ops; 1322 + pr_devel("all gone\n"); 1323 + return edit; 1324 + } 1325 + 1326 + /* 1327 + * Handle the deferred destruction after an applied edit. 1328 + */ 1329 + static void assoc_array_rcu_cleanup(struct rcu_head *head) 1330 + { 1331 + struct assoc_array_edit *edit = 1332 + container_of(head, struct assoc_array_edit, rcu); 1333 + int i; 1334 + 1335 + pr_devel("-->%s()\n", __func__); 1336 + 1337 + if (edit->dead_leaf) 1338 + edit->ops->free_object(assoc_array_ptr_to_leaf(edit->dead_leaf)); 1339 + for (i = 0; i < ARRAY_SIZE(edit->excised_meta); i++) 1340 + if (edit->excised_meta[i]) 1341 + kfree(assoc_array_ptr_to_node(edit->excised_meta[i])); 1342 + 1343 + if (edit->excised_subtree) { 1344 + BUG_ON(assoc_array_ptr_is_leaf(edit->excised_subtree)); 1345 + if (assoc_array_ptr_is_node(edit->excised_subtree)) { 1346 + struct assoc_array_node *n = 1347 + assoc_array_ptr_to_node(edit->excised_subtree); 1348 + n->back_pointer = NULL; 1349 + } else { 1350 + struct assoc_array_shortcut *s = 1351 + assoc_array_ptr_to_shortcut(edit->excised_subtree); 1352 + s->back_pointer = NULL; 1353 + } 1354 + assoc_array_destroy_subtree(edit->excised_subtree, 1355 + edit->ops_for_excised_subtree); 1356 + } 1357 + 1358 + kfree(edit); 1359 + } 1360 + 1361 + /** 1362 + * assoc_array_apply_edit - Apply an edit script to an associative array 1363 + * @edit: The script to apply. 1364 + * 1365 + * Apply an edit script to an associative array to effect an insertion, 1366 + * deletion or clearance. As the edit script includes preallocated memory, 1367 + * this is guaranteed not to fail. 1368 + * 1369 + * The edit script, dead objects and dead metadata will be scheduled for 1370 + * destruction after an RCU grace period to permit those doing read-only 1371 + * accesses on the array to continue to do so under the RCU read lock whilst 1372 + * the edit is taking place. 1373 + */ 1374 + void assoc_array_apply_edit(struct assoc_array_edit *edit) 1375 + { 1376 + struct assoc_array_shortcut *shortcut; 1377 + struct assoc_array_node *node; 1378 + struct assoc_array_ptr *ptr; 1379 + int i; 1380 + 1381 + pr_devel("-->%s()\n", __func__); 1382 + 1383 + smp_wmb(); 1384 + if (edit->leaf_p) 1385 + *edit->leaf_p = edit->leaf; 1386 + 1387 + smp_wmb(); 1388 + for (i = 0; i < ARRAY_SIZE(edit->set_parent_slot); i++) 1389 + if (edit->set_parent_slot[i].p) 1390 + *edit->set_parent_slot[i].p = edit->set_parent_slot[i].to; 1391 + 1392 + smp_wmb(); 1393 + for (i = 0; i < ARRAY_SIZE(edit->set_backpointers); i++) 1394 + if (edit->set_backpointers[i]) 1395 + *edit->set_backpointers[i] = edit->set_backpointers_to; 1396 + 1397 + smp_wmb(); 1398 + for (i = 0; i < ARRAY_SIZE(edit->set); i++) 1399 + if (edit->set[i].ptr) 1400 + *edit->set[i].ptr = edit->set[i].to; 1401 + 1402 + if (edit->array->root == NULL) { 1403 + edit->array->nr_leaves_on_tree = 0; 1404 + } else if (edit->adjust_count_on) { 1405 + node = edit->adjust_count_on; 1406 + for (;;) { 1407 + node->nr_leaves_on_branch += edit->adjust_count_by; 1408 + 1409 + ptr = node->back_pointer; 1410 + if (!ptr) 1411 + break; 1412 + if (assoc_array_ptr_is_shortcut(ptr)) { 1413 + shortcut = assoc_array_ptr_to_shortcut(ptr); 1414 + ptr = shortcut->back_pointer; 1415 + if (!ptr) 1416 + break; 1417 + } 1418 + BUG_ON(!assoc_array_ptr_is_node(ptr)); 1419 + node = assoc_array_ptr_to_node(ptr); 1420 + } 1421 + 1422 + edit->array->nr_leaves_on_tree += edit->adjust_count_by; 1423 + } 1424 + 1425 + call_rcu(&edit->rcu, assoc_array_rcu_cleanup); 1426 + } 1427 + 1428 + /** 1429 + * assoc_array_cancel_edit - Discard an edit script. 1430 + * @edit: The script to discard. 1431 + * 1432 + * Free an edit script and all the preallocated data it holds without making 1433 + * any changes to the associative array it was intended for. 1434 + * 1435 + * NOTE! In the case of an insertion script, this does _not_ release the leaf 1436 + * that was to be inserted. That is left to the caller. 1437 + */ 1438 + void assoc_array_cancel_edit(struct assoc_array_edit *edit) 1439 + { 1440 + struct assoc_array_ptr *ptr; 1441 + int i; 1442 + 1443 + pr_devel("-->%s()\n", __func__); 1444 + 1445 + /* Clean up after an out of memory error */ 1446 + for (i = 0; i < ARRAY_SIZE(edit->new_meta); i++) { 1447 + ptr = edit->new_meta[i]; 1448 + if (ptr) { 1449 + if (assoc_array_ptr_is_node(ptr)) 1450 + kfree(assoc_array_ptr_to_node(ptr)); 1451 + else 1452 + kfree(assoc_array_ptr_to_shortcut(ptr)); 1453 + } 1454 + } 1455 + kfree(edit); 1456 + } 1457 + 1458 + /** 1459 + * assoc_array_gc - Garbage collect an associative array. 1460 + * @array: The array to clean. 1461 + * @ops: The operations to use. 1462 + * @iterator: A callback function to pass judgement on each object. 1463 + * @iterator_data: Private data for the callback function. 1464 + * 1465 + * Collect garbage from an associative array and pack down the internal tree to 1466 + * save memory. 1467 + * 1468 + * The iterator function is asked to pass judgement upon each object in the 1469 + * array. If it returns false, the object is discard and if it returns true, 1470 + * the object is kept. If it returns true, it must increment the object's 1471 + * usage count (or whatever it needs to do to retain it) before returning. 1472 + * 1473 + * This function returns 0 if successful or -ENOMEM if out of memory. In the 1474 + * latter case, the array is not changed. 1475 + * 1476 + * The caller should lock against other modifications and must continue to hold 1477 + * the lock until assoc_array_apply_edit() has been called. 1478 + * 1479 + * Accesses to the tree may take place concurrently with this function, 1480 + * provided they hold the RCU read lock. 1481 + */ 1482 + int assoc_array_gc(struct assoc_array *array, 1483 + const struct assoc_array_ops *ops, 1484 + bool (*iterator)(void *object, void *iterator_data), 1485 + void *iterator_data) 1486 + { 1487 + struct assoc_array_shortcut *shortcut, *new_s; 1488 + struct assoc_array_node *node, *new_n; 1489 + struct assoc_array_edit *edit; 1490 + struct assoc_array_ptr *cursor, *ptr; 1491 + struct assoc_array_ptr *new_root, *new_parent, **new_ptr_pp; 1492 + unsigned long nr_leaves_on_tree; 1493 + int keylen, slot, nr_free, next_slot, i; 1494 + 1495 + pr_devel("-->%s()\n", __func__); 1496 + 1497 + if (!array->root) 1498 + return 0; 1499 + 1500 + edit = kzalloc(sizeof(struct assoc_array_edit), GFP_KERNEL); 1501 + if (!edit) 1502 + return -ENOMEM; 1503 + edit->array = array; 1504 + edit->ops = ops; 1505 + edit->ops_for_excised_subtree = ops; 1506 + edit->set[0].ptr = &array->root; 1507 + edit->excised_subtree = array->root; 1508 + 1509 + new_root = new_parent = NULL; 1510 + new_ptr_pp = &new_root; 1511 + cursor = array->root; 1512 + 1513 + descend: 1514 + /* If this point is a shortcut, then we need to duplicate it and 1515 + * advance the target cursor. 1516 + */ 1517 + if (assoc_array_ptr_is_shortcut(cursor)) { 1518 + shortcut = assoc_array_ptr_to_shortcut(cursor); 1519 + keylen = round_up(shortcut->skip_to_level, ASSOC_ARRAY_KEY_CHUNK_SIZE); 1520 + keylen >>= ASSOC_ARRAY_KEY_CHUNK_SHIFT; 1521 + new_s = kmalloc(sizeof(struct assoc_array_shortcut) + 1522 + keylen * sizeof(unsigned long), GFP_KERNEL); 1523 + if (!new_s) 1524 + goto enomem; 1525 + pr_devel("dup shortcut %p -> %p\n", shortcut, new_s); 1526 + memcpy(new_s, shortcut, (sizeof(struct assoc_array_shortcut) + 1527 + keylen * sizeof(unsigned long))); 1528 + new_s->back_pointer = new_parent; 1529 + new_s->parent_slot = shortcut->parent_slot; 1530 + *new_ptr_pp = new_parent = assoc_array_shortcut_to_ptr(new_s); 1531 + new_ptr_pp = &new_s->next_node; 1532 + cursor = shortcut->next_node; 1533 + } 1534 + 1535 + /* Duplicate the node at this position */ 1536 + node = assoc_array_ptr_to_node(cursor); 1537 + new_n = kzalloc(sizeof(struct assoc_array_node), GFP_KERNEL); 1538 + if (!new_n) 1539 + goto enomem; 1540 + pr_devel("dup node %p -> %p\n", node, new_n); 1541 + new_n->back_pointer = new_parent; 1542 + new_n->parent_slot = node->parent_slot; 1543 + *new_ptr_pp = new_parent = assoc_array_node_to_ptr(new_n); 1544 + new_ptr_pp = NULL; 1545 + slot = 0; 1546 + 1547 + continue_node: 1548 + /* Filter across any leaves and gc any subtrees */ 1549 + for (; slot < ASSOC_ARRAY_FAN_OUT; slot++) { 1550 + ptr = node->slots[slot]; 1551 + if (!ptr) 1552 + continue; 1553 + 1554 + if (assoc_array_ptr_is_leaf(ptr)) { 1555 + if (iterator(assoc_array_ptr_to_leaf(ptr), 1556 + iterator_data)) 1557 + /* The iterator will have done any reference 1558 + * counting on the object for us. 1559 + */ 1560 + new_n->slots[slot] = ptr; 1561 + continue; 1562 + } 1563 + 1564 + new_ptr_pp = &new_n->slots[slot]; 1565 + cursor = ptr; 1566 + goto descend; 1567 + } 1568 + 1569 + pr_devel("-- compress node %p --\n", new_n); 1570 + 1571 + /* Count up the number of empty slots in this node and work out the 1572 + * subtree leaf count. 1573 + */ 1574 + new_n->nr_leaves_on_branch = 0; 1575 + nr_free = 0; 1576 + for (slot = 0; slot < ASSOC_ARRAY_FAN_OUT; slot++) { 1577 + ptr = new_n->slots[slot]; 1578 + if (!ptr) 1579 + nr_free++; 1580 + else if (assoc_array_ptr_is_leaf(ptr)) 1581 + new_n->nr_leaves_on_branch++; 1582 + } 1583 + pr_devel("free=%d, leaves=%lu\n", nr_free, new_n->nr_leaves_on_branch); 1584 + 1585 + /* See what we can fold in */ 1586 + next_slot = 0; 1587 + for (slot = 0; slot < ASSOC_ARRAY_FAN_OUT; slot++) { 1588 + struct assoc_array_shortcut *s; 1589 + struct assoc_array_node *child; 1590 + 1591 + ptr = new_n->slots[slot]; 1592 + if (!ptr || assoc_array_ptr_is_leaf(ptr)) 1593 + continue; 1594 + 1595 + s = NULL; 1596 + if (assoc_array_ptr_is_shortcut(ptr)) { 1597 + s = assoc_array_ptr_to_shortcut(ptr); 1598 + ptr = s->next_node; 1599 + } 1600 + 1601 + child = assoc_array_ptr_to_node(ptr); 1602 + new_n->nr_leaves_on_branch += child->nr_leaves_on_branch; 1603 + 1604 + if (child->nr_leaves_on_branch <= nr_free + 1) { 1605 + /* Fold the child node into this one */ 1606 + pr_devel("[%d] fold node %lu/%d [nx %d]\n", 1607 + slot, child->nr_leaves_on_branch, nr_free + 1, 1608 + next_slot); 1609 + 1610 + /* We would already have reaped an intervening shortcut 1611 + * on the way back up the tree. 1612 + */ 1613 + BUG_ON(s); 1614 + 1615 + new_n->slots[slot] = NULL; 1616 + nr_free++; 1617 + if (slot < next_slot) 1618 + next_slot = slot; 1619 + for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) { 1620 + struct assoc_array_ptr *p = child->slots[i]; 1621 + if (!p) 1622 + continue; 1623 + BUG_ON(assoc_array_ptr_is_meta(p)); 1624 + while (new_n->slots[next_slot]) 1625 + next_slot++; 1626 + BUG_ON(next_slot >= ASSOC_ARRAY_FAN_OUT); 1627 + new_n->slots[next_slot++] = p; 1628 + nr_free--; 1629 + } 1630 + kfree(child); 1631 + } else { 1632 + pr_devel("[%d] retain node %lu/%d [nx %d]\n", 1633 + slot, child->nr_leaves_on_branch, nr_free + 1, 1634 + next_slot); 1635 + } 1636 + } 1637 + 1638 + pr_devel("after: %lu\n", new_n->nr_leaves_on_branch); 1639 + 1640 + nr_leaves_on_tree = new_n->nr_leaves_on_branch; 1641 + 1642 + /* Excise this node if it is singly occupied by a shortcut */ 1643 + if (nr_free == ASSOC_ARRAY_FAN_OUT - 1) { 1644 + for (slot = 0; slot < ASSOC_ARRAY_FAN_OUT; slot++) 1645 + if ((ptr = new_n->slots[slot])) 1646 + break; 1647 + 1648 + if (assoc_array_ptr_is_meta(ptr) && 1649 + assoc_array_ptr_is_shortcut(ptr)) { 1650 + pr_devel("excise node %p with 1 shortcut\n", new_n); 1651 + new_s = assoc_array_ptr_to_shortcut(ptr); 1652 + new_parent = new_n->back_pointer; 1653 + slot = new_n->parent_slot; 1654 + kfree(new_n); 1655 + if (!new_parent) { 1656 + new_s->back_pointer = NULL; 1657 + new_s->parent_slot = 0; 1658 + new_root = ptr; 1659 + goto gc_complete; 1660 + } 1661 + 1662 + if (assoc_array_ptr_is_shortcut(new_parent)) { 1663 + /* We can discard any preceding shortcut also */ 1664 + struct assoc_array_shortcut *s = 1665 + assoc_array_ptr_to_shortcut(new_parent); 1666 + 1667 + pr_devel("excise preceding shortcut\n"); 1668 + 1669 + new_parent = new_s->back_pointer = s->back_pointer; 1670 + slot = new_s->parent_slot = s->parent_slot; 1671 + kfree(s); 1672 + if (!new_parent) { 1673 + new_s->back_pointer = NULL; 1674 + new_s->parent_slot = 0; 1675 + new_root = ptr; 1676 + goto gc_complete; 1677 + } 1678 + } 1679 + 1680 + new_s->back_pointer = new_parent; 1681 + new_s->parent_slot = slot; 1682 + new_n = assoc_array_ptr_to_node(new_parent); 1683 + new_n->slots[slot] = ptr; 1684 + goto ascend_old_tree; 1685 + } 1686 + } 1687 + 1688 + /* Excise any shortcuts we might encounter that point to nodes that 1689 + * only contain leaves. 1690 + */ 1691 + ptr = new_n->back_pointer; 1692 + if (!ptr) 1693 + goto gc_complete; 1694 + 1695 + if (assoc_array_ptr_is_shortcut(ptr)) { 1696 + new_s = assoc_array_ptr_to_shortcut(ptr); 1697 + new_parent = new_s->back_pointer; 1698 + slot = new_s->parent_slot; 1699 + 1700 + if (new_n->nr_leaves_on_branch <= ASSOC_ARRAY_FAN_OUT) { 1701 + struct assoc_array_node *n; 1702 + 1703 + pr_devel("excise shortcut\n"); 1704 + new_n->back_pointer = new_parent; 1705 + new_n->parent_slot = slot; 1706 + kfree(new_s); 1707 + if (!new_parent) { 1708 + new_root = assoc_array_node_to_ptr(new_n); 1709 + goto gc_complete; 1710 + } 1711 + 1712 + n = assoc_array_ptr_to_node(new_parent); 1713 + n->slots[slot] = assoc_array_node_to_ptr(new_n); 1714 + } 1715 + } else { 1716 + new_parent = ptr; 1717 + } 1718 + new_n = assoc_array_ptr_to_node(new_parent); 1719 + 1720 + ascend_old_tree: 1721 + ptr = node->back_pointer; 1722 + if (assoc_array_ptr_is_shortcut(ptr)) { 1723 + shortcut = assoc_array_ptr_to_shortcut(ptr); 1724 + slot = shortcut->parent_slot; 1725 + cursor = shortcut->back_pointer; 1726 + } else { 1727 + slot = node->parent_slot; 1728 + cursor = ptr; 1729 + } 1730 + BUG_ON(!ptr); 1731 + node = assoc_array_ptr_to_node(cursor); 1732 + slot++; 1733 + goto continue_node; 1734 + 1735 + gc_complete: 1736 + edit->set[0].to = new_root; 1737 + assoc_array_apply_edit(edit); 1738 + edit->array->nr_leaves_on_tree = nr_leaves_on_tree; 1739 + return 0; 1740 + 1741 + enomem: 1742 + pr_devel("enomem\n"); 1743 + assoc_array_destroy_subtree(new_root, edit->ops); 1744 + kfree(edit); 1745 + return -ENOMEM; 1746 + }
+3
lib/mpi/mpiutil.c
··· 121 121 kfree(a); 122 122 } 123 123 EXPORT_SYMBOL_GPL(mpi_free); 124 + 125 + MODULE_DESCRIPTION("Multiprecision maths library"); 126 + MODULE_LICENSE("GPL");
+2
scripts/asn1_compiler.c
··· 1353 1353 render_opcode(out, "ASN1_OP_END_SET_OF%s,\n", act); 1354 1354 render_opcode(out, "_jump_target(%u),\n", entry); 1355 1355 break; 1356 + default: 1357 + break; 1356 1358 } 1357 1359 if (e->action) 1358 1360 render_opcode(out, "_action(ACT_%s),\n",
-1
security/Makefile
··· 16 16 # Object file lists 17 17 obj-$(CONFIG_SECURITY) += security.o capability.o 18 18 obj-$(CONFIG_SECURITYFS) += inode.o 19 - # Must precede capability.o in order to stack properly. 20 19 obj-$(CONFIG_SECURITY_SELINUX) += selinux/built-in.o 21 20 obj-$(CONFIG_SECURITY_SMACK) += smack/built-in.o 22 21 obj-$(CONFIG_AUDIT) += lsm_audit.o
+1 -13
security/apparmor/audit.c
··· 111 111 static void audit_pre(struct audit_buffer *ab, void *ca) 112 112 { 113 113 struct common_audit_data *sa = ca; 114 - struct task_struct *tsk = sa->aad->tsk ? sa->aad->tsk : current; 115 114 116 115 if (aa_g_audit_header) { 117 116 audit_log_format(ab, "apparmor="); ··· 131 132 132 133 if (sa->aad->profile) { 133 134 struct aa_profile *profile = sa->aad->profile; 134 - pid_t pid; 135 - rcu_read_lock(); 136 - pid = rcu_dereference(tsk->real_parent)->pid; 137 - rcu_read_unlock(); 138 - audit_log_format(ab, " parent=%d", pid); 139 135 if (profile->ns != root_ns) { 140 136 audit_log_format(ab, " namespace="); 141 137 audit_log_untrustedstring(ab, profile->ns->base.hname); ··· 143 149 audit_log_format(ab, " name="); 144 150 audit_log_untrustedstring(ab, sa->aad->name); 145 151 } 146 - 147 - if (sa->aad->tsk) { 148 - audit_log_format(ab, " pid=%d comm=", tsk->pid); 149 - audit_log_untrustedstring(ab, tsk->comm); 150 - } 151 - 152 152 } 153 153 154 154 /** ··· 200 212 201 213 if (sa->aad->type == AUDIT_APPARMOR_KILL) 202 214 (void)send_sig_info(SIGKILL, NULL, 203 - sa->aad->tsk ? sa->aad->tsk : current); 215 + sa->u.tsk ? sa->u.tsk : current); 204 216 205 217 if (sa->aad->type == AUDIT_APPARMOR_ALLOWED) 206 218 return complain_error(sa->aad->error);
+5 -10
security/apparmor/capability.c
··· 53 53 54 54 /** 55 55 * audit_caps - audit a capability 56 - * @profile: profile confining task (NOT NULL) 57 - * @task: task capability test was performed against (NOT NULL) 56 + * @profile: profile being tested for confinement (NOT NULL) 58 57 * @cap: capability tested 59 58 * @error: error code returned by test 60 59 * ··· 62 63 * 63 64 * Returns: 0 or sa->error on success, error code on failure 64 65 */ 65 - static int audit_caps(struct aa_profile *profile, struct task_struct *task, 66 - int cap, int error) 66 + static int audit_caps(struct aa_profile *profile, int cap, int error) 67 67 { 68 68 struct audit_cache *ent; 69 69 int type = AUDIT_APPARMOR_AUTO; ··· 71 73 sa.type = LSM_AUDIT_DATA_CAP; 72 74 sa.aad = &aad; 73 75 sa.u.cap = cap; 74 - sa.aad->tsk = task; 75 76 sa.aad->op = OP_CAPABLE; 76 77 sa.aad->error = error; 77 78 ··· 121 124 122 125 /** 123 126 * aa_capable - test permission to use capability 124 - * @task: task doing capability test against (NOT NULL) 125 - * @profile: profile confining @task (NOT NULL) 127 + * @profile: profile being tested against (NOT NULL) 126 128 * @cap: capability to be tested 127 129 * @audit: whether an audit record should be generated 128 130 * ··· 129 133 * 130 134 * Returns: 0 on success, or else an error code. 131 135 */ 132 - int aa_capable(struct task_struct *task, struct aa_profile *profile, int cap, 133 - int audit) 136 + int aa_capable(struct aa_profile *profile, int cap, int audit) 134 137 { 135 138 int error = profile_capable(profile, cap); 136 139 ··· 139 144 return error; 140 145 } 141 146 142 - return audit_caps(profile, task, cap, error); 147 + return audit_caps(profile, cap, error); 143 148 }
+7 -9
security/apparmor/domain.c
··· 50 50 51 51 /** 52 52 * may_change_ptraced_domain - check if can change profile on ptraced task 53 - * @task: task we want to change profile of (NOT NULL) 54 53 * @to_profile: profile to change to (NOT NULL) 55 54 * 56 - * Check if the task is ptraced and if so if the tracing task is allowed 55 + * Check if current is ptraced and if so if the tracing task is allowed 57 56 * to trace the new domain 58 57 * 59 58 * Returns: %0 or error if change not allowed 60 59 */ 61 - static int may_change_ptraced_domain(struct task_struct *task, 62 - struct aa_profile *to_profile) 60 + static int may_change_ptraced_domain(struct aa_profile *to_profile) 63 61 { 64 62 struct task_struct *tracer; 65 63 struct aa_profile *tracerp = NULL; 66 64 int error = 0; 67 65 68 66 rcu_read_lock(); 69 - tracer = ptrace_parent(task); 67 + tracer = ptrace_parent(current); 70 68 if (tracer) 71 69 /* released below */ 72 70 tracerp = aa_get_task_profile(tracer); ··· 73 75 if (!tracer || unconfined(tracerp)) 74 76 goto out; 75 77 76 - error = aa_may_ptrace(tracer, tracerp, to_profile, PTRACE_MODE_ATTACH); 78 + error = aa_may_ptrace(tracerp, to_profile, PTRACE_MODE_ATTACH); 77 79 78 80 out: 79 81 rcu_read_unlock(); ··· 475 477 } 476 478 477 479 if (bprm->unsafe & (LSM_UNSAFE_PTRACE | LSM_UNSAFE_PTRACE_CAP)) { 478 - error = may_change_ptraced_domain(current, new_profile); 480 + error = may_change_ptraced_domain(new_profile); 479 481 if (error) { 480 482 aa_put_profile(new_profile); 481 483 goto audit; ··· 688 690 } 689 691 } 690 692 691 - error = may_change_ptraced_domain(current, hat); 693 + error = may_change_ptraced_domain(hat); 692 694 if (error) { 693 695 info = "ptraced"; 694 696 error = -EPERM; ··· 827 829 } 828 830 829 831 /* check if tracing task is allowed to trace target domain */ 830 - error = may_change_ptraced_domain(current, target); 832 + error = may_change_ptraced_domain(target); 831 833 if (error) { 832 834 info = "ptrace prevents transition"; 833 835 goto audit;
-1
security/apparmor/include/audit.h
··· 109 109 void *profile; 110 110 const char *name; 111 111 const char *info; 112 - struct task_struct *tsk; 113 112 union { 114 113 void *target; 115 114 struct {
+2 -3
security/apparmor/include/capability.h
··· 4 4 * This file contains AppArmor capability mediation definitions. 5 5 * 6 6 * Copyright (C) 1998-2008 Novell/SUSE 7 - * Copyright 2009-2010 Canonical Ltd. 7 + * Copyright 2009-2013 Canonical Ltd. 8 8 * 9 9 * This program is free software; you can redistribute it and/or 10 10 * modify it under the terms of the GNU General Public License as ··· 38 38 39 39 extern struct aa_fs_entry aa_fs_entry_caps[]; 40 40 41 - int aa_capable(struct task_struct *task, struct aa_profile *profile, int cap, 42 - int audit); 41 + int aa_capable(struct aa_profile *profile, int cap, int audit); 43 42 44 43 static inline void aa_free_cap_rules(struct aa_caps *caps) 45 44 {
+2 -2
security/apparmor/include/ipc.h
··· 19 19 20 20 struct aa_profile; 21 21 22 - int aa_may_ptrace(struct task_struct *tracer_task, struct aa_profile *tracer, 23 - struct aa_profile *tracee, unsigned int mode); 22 + int aa_may_ptrace(struct aa_profile *tracer, struct aa_profile *tracee, 23 + unsigned int mode); 24 24 25 25 int aa_ptrace(struct task_struct *tracer, struct task_struct *tracee, 26 26 unsigned int mode);
+4 -5
security/apparmor/ipc.c
··· 54 54 55 55 /** 56 56 * aa_may_ptrace - test if tracer task can trace the tracee 57 - * @tracer_task: task who will do the tracing (NOT NULL) 58 57 * @tracer: profile of the task doing the tracing (NOT NULL) 59 58 * @tracee: task to be traced 60 59 * @mode: whether PTRACE_MODE_READ || PTRACE_MODE_ATTACH 61 60 * 62 61 * Returns: %0 else error code if permission denied or error 63 62 */ 64 - int aa_may_ptrace(struct task_struct *tracer_task, struct aa_profile *tracer, 65 - struct aa_profile *tracee, unsigned int mode) 63 + int aa_may_ptrace(struct aa_profile *tracer, struct aa_profile *tracee, 64 + unsigned int mode) 66 65 { 67 66 /* TODO: currently only based on capability, not extended ptrace 68 67 * rules, ··· 71 72 if (unconfined(tracer) || tracer == tracee) 72 73 return 0; 73 74 /* log this capability request */ 74 - return aa_capable(tracer_task, tracer, CAP_SYS_PTRACE, 1); 75 + return aa_capable(tracer, CAP_SYS_PTRACE, 1); 75 76 } 76 77 77 78 /** ··· 100 101 if (!unconfined(tracer_p)) { 101 102 struct aa_profile *tracee_p = aa_get_task_profile(tracee); 102 103 103 - error = aa_may_ptrace(tracer, tracer_p, tracee_p, mode); 104 + error = aa_may_ptrace(tracer_p, tracee_p, mode); 104 105 error = aa_audit_ptrace(tracer_p, tracee_p, error); 105 106 106 107 aa_put_profile(tracee_p);
+1 -1
security/apparmor/lsm.c
··· 145 145 if (!error) { 146 146 profile = aa_cred_profile(cred); 147 147 if (!unconfined(profile)) 148 - error = aa_capable(current, profile, cap, audit); 148 + error = aa_capable(profile, cap, audit); 149 149 } 150 150 return error; 151 151 }
+11 -4
security/capability.c
··· 777 777 return 0; 778 778 } 779 779 780 - static int cap_xfrm_state_alloc_security(struct xfrm_state *x, 781 - struct xfrm_user_sec_ctx *sec_ctx, 782 - u32 secid) 780 + static int cap_xfrm_state_alloc(struct xfrm_state *x, 781 + struct xfrm_user_sec_ctx *sec_ctx) 782 + { 783 + return 0; 784 + } 785 + 786 + static int cap_xfrm_state_alloc_acquire(struct xfrm_state *x, 787 + struct xfrm_sec_ctx *polsec, 788 + u32 secid) 783 789 { 784 790 return 0; 785 791 } ··· 1107 1101 set_to_cap_if_null(ops, xfrm_policy_clone_security); 1108 1102 set_to_cap_if_null(ops, xfrm_policy_free_security); 1109 1103 set_to_cap_if_null(ops, xfrm_policy_delete_security); 1110 - set_to_cap_if_null(ops, xfrm_state_alloc_security); 1104 + set_to_cap_if_null(ops, xfrm_state_alloc); 1105 + set_to_cap_if_null(ops, xfrm_state_alloc_acquire); 1111 1106 set_to_cap_if_null(ops, xfrm_state_free_security); 1112 1107 set_to_cap_if_null(ops, xfrm_state_delete_security); 1113 1108 set_to_cap_if_null(ops, xfrm_policy_lookup);
+33 -4
security/integrity/digsig.c
··· 13 13 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt 14 14 15 15 #include <linux/err.h> 16 + #include <linux/sched.h> 16 17 #include <linux/rbtree.h> 18 + #include <linux/cred.h> 17 19 #include <linux/key-type.h> 18 20 #include <linux/digsig.h> 19 21 ··· 23 21 24 22 static struct key *keyring[INTEGRITY_KEYRING_MAX]; 25 23 24 + #ifdef CONFIG_IMA_TRUSTED_KEYRING 25 + static const char *keyring_name[INTEGRITY_KEYRING_MAX] = { 26 + ".evm", 27 + ".module", 28 + ".ima", 29 + }; 30 + #else 26 31 static const char *keyring_name[INTEGRITY_KEYRING_MAX] = { 27 32 "_evm", 28 33 "_module", 29 34 "_ima", 30 35 }; 36 + #endif 31 37 32 38 int integrity_digsig_verify(const unsigned int id, const char *sig, int siglen, 33 - const char *digest, int digestlen) 39 + const char *digest, int digestlen) 34 40 { 35 41 if (id >= INTEGRITY_KEYRING_MAX) 36 42 return -EINVAL; 37 43 38 44 if (!keyring[id]) { 39 45 keyring[id] = 40 - request_key(&key_type_keyring, keyring_name[id], NULL); 46 + request_key(&key_type_keyring, keyring_name[id], NULL); 41 47 if (IS_ERR(keyring[id])) { 42 48 int err = PTR_ERR(keyring[id]); 43 49 pr_err("no %s keyring: %d\n", keyring_name[id], err); ··· 54 44 } 55 45 } 56 46 57 - switch (sig[0]) { 47 + switch (sig[1]) { 58 48 case 1: 59 - return digsig_verify(keyring[id], sig, siglen, 49 + /* v1 API expect signature without xattr type */ 50 + return digsig_verify(keyring[id], sig + 1, siglen - 1, 60 51 digest, digestlen); 61 52 case 2: 62 53 return asymmetric_verify(keyring[id], sig, siglen, ··· 65 54 } 66 55 67 56 return -EOPNOTSUPP; 57 + } 58 + 59 + int integrity_init_keyring(const unsigned int id) 60 + { 61 + const struct cred *cred = current_cred(); 62 + const struct user_struct *user = cred->user; 63 + 64 + keyring[id] = keyring_alloc(keyring_name[id], KUIDT_INIT(0), 65 + KGIDT_INIT(0), cred, 66 + ((KEY_POS_ALL & ~KEY_POS_SETATTR) | 67 + KEY_USR_VIEW | KEY_USR_READ), 68 + KEY_ALLOC_NOT_IN_QUOTA, user->uid_keyring); 69 + if (!IS_ERR(keyring[id])) 70 + set_bit(KEY_FLAG_TRUSTED_ONLY, &keyring[id]->flags); 71 + else 72 + pr_info("Can't allocate %s keyring (%ld)\n", 73 + keyring_name[id], PTR_ERR(keyring[id])); 74 + return 0; 68 75 }
-11
security/integrity/digsig_asymmetric.c
··· 20 20 #include "integrity.h" 21 21 22 22 /* 23 - * signature format v2 - for using with asymmetric keys 24 - */ 25 - struct signature_v2_hdr { 26 - uint8_t version; /* signature format version */ 27 - uint8_t hash_algo; /* Digest algorithm [enum pkey_hash_algo] */ 28 - uint32_t keyid; /* IMA key identifier - not X509/PGP specific*/ 29 - uint16_t sig_size; /* signature size */ 30 - uint8_t sig[0]; /* signature payload */ 31 - } __packed; 32 - 33 - /* 34 23 * Request an asymmetric key. 35 24 */ 36 25 static struct key *request_asymmetric_key(struct key *keyring, uint32_t keyid)
+2 -2
security/integrity/evm/evm_main.c
··· 123 123 goto out; 124 124 } 125 125 126 - xattr_len = rc - 1; 126 + xattr_len = rc; 127 127 128 128 /* check value type */ 129 129 switch (xattr_data->type) { ··· 143 143 if (rc) 144 144 break; 145 145 rc = integrity_digsig_verify(INTEGRITY_KEYRING_EVM, 146 - xattr_data->digest, xattr_len, 146 + (const char *)xattr_data, xattr_len, 147 147 calc.digest, sizeof(calc.digest)); 148 148 if (!rc) { 149 149 /* we probably want to replace rsa with hmac here */
+2 -1
security/integrity/evm/evm_posix_acl.c
··· 11 11 12 12 #include <linux/module.h> 13 13 #include <linux/xattr.h> 14 + #include <linux/evm.h> 14 15 15 - int posix_xattr_acl(char *xattr) 16 + int posix_xattr_acl(const char *xattr) 16 17 { 17 18 int xattr_len = strlen(xattr); 18 19
+2
security/integrity/iint.c
··· 70 70 71 71 static void iint_free(struct integrity_iint_cache *iint) 72 72 { 73 + kfree(iint->ima_hash); 74 + iint->ima_hash = NULL; 73 75 iint->version = 0; 74 76 iint->flags = 0UL; 75 77 iint->ima_file_status = INTEGRITY_UNKNOWN;
+72
security/integrity/ima/Kconfig
··· 9 9 select CRYPTO_HMAC 10 10 select CRYPTO_MD5 11 11 select CRYPTO_SHA1 12 + select CRYPTO_HASH_INFO 12 13 select TCG_TPM if HAS_IOMEM && !UML 13 14 select TCG_TIS if TCG_TPM && X86 14 15 select TCG_IBMVTPM if TCG_TPM && PPC64 ··· 46 45 help 47 46 Disabling this option will disregard LSM based policy rules. 48 47 48 + choice 49 + prompt "Default template" 50 + default IMA_NG_TEMPLATE 51 + depends on IMA 52 + help 53 + Select the default IMA measurement template. 54 + 55 + The original 'ima' measurement list template contains a 56 + hash, defined as 20 bytes, and a null terminated pathname, 57 + limited to 255 characters. The 'ima-ng' measurement list 58 + template permits both larger hash digests and longer 59 + pathnames. 60 + 61 + config IMA_TEMPLATE 62 + bool "ima" 63 + config IMA_NG_TEMPLATE 64 + bool "ima-ng (default)" 65 + config IMA_SIG_TEMPLATE 66 + bool "ima-sig" 67 + endchoice 68 + 69 + config IMA_DEFAULT_TEMPLATE 70 + string 71 + depends on IMA 72 + default "ima" if IMA_TEMPLATE 73 + default "ima-ng" if IMA_NG_TEMPLATE 74 + default "ima-sig" if IMA_SIG_TEMPLATE 75 + 76 + choice 77 + prompt "Default integrity hash algorithm" 78 + default IMA_DEFAULT_HASH_SHA1 79 + depends on IMA 80 + help 81 + Select the default hash algorithm used for the measurement 82 + list, integrity appraisal and audit log. The compiled default 83 + hash algorithm can be overwritten using the kernel command 84 + line 'ima_hash=' option. 85 + 86 + config IMA_DEFAULT_HASH_SHA1 87 + bool "SHA1 (default)" 88 + depends on CRYPTO_SHA1 89 + 90 + config IMA_DEFAULT_HASH_SHA256 91 + bool "SHA256" 92 + depends on CRYPTO_SHA256 && !IMA_TEMPLATE 93 + 94 + config IMA_DEFAULT_HASH_SHA512 95 + bool "SHA512" 96 + depends on CRYPTO_SHA512 && !IMA_TEMPLATE 97 + 98 + config IMA_DEFAULT_HASH_WP512 99 + bool "WP512" 100 + depends on CRYPTO_WP512 && !IMA_TEMPLATE 101 + endchoice 102 + 103 + config IMA_DEFAULT_HASH 104 + string 105 + depends on IMA 106 + default "sha1" if IMA_DEFAULT_HASH_SHA1 107 + default "sha256" if IMA_DEFAULT_HASH_SHA256 108 + default "sha512" if IMA_DEFAULT_HASH_SHA512 109 + default "wp512" if IMA_DEFAULT_HASH_WP512 110 + 49 111 config IMA_APPRAISE 50 112 bool "Appraise integrity measurements" 51 113 depends on IMA ··· 123 59 For more information on integrity appraisal refer to: 124 60 <http://linux-ima.sourceforge.net> 125 61 If unsure, say N. 62 + 63 + config IMA_TRUSTED_KEYRING 64 + bool "Require all keys on the _ima keyring be signed" 65 + depends on IMA_APPRAISE && SYSTEM_TRUSTED_KEYRING 66 + default y 67 + help 68 + This option requires that all keys added to the _ima 69 + keyring be signed by a key on the system trusted keyring.
+1 -1
security/integrity/ima/Makefile
··· 6 6 obj-$(CONFIG_IMA) += ima.o 7 7 8 8 ima-y := ima_fs.o ima_queue.o ima_init.o ima_main.o ima_crypto.o ima_api.o \ 9 - ima_policy.o 9 + ima_policy.o ima_template.o ima_template_lib.o 10 10 ima-$(CONFIG_IMA_APPRAISE) += ima_appraise.o
+81 -20
security/integrity/ima/ima.h
··· 36 36 #define IMA_HASH_BITS 9 37 37 #define IMA_MEASURE_HTABLE_SIZE (1 << IMA_HASH_BITS) 38 38 39 + #define IMA_TEMPLATE_FIELD_ID_MAX_LEN 16 40 + #define IMA_TEMPLATE_NUM_FIELDS_MAX 15 41 + 42 + #define IMA_TEMPLATE_IMA_NAME "ima" 43 + #define IMA_TEMPLATE_IMA_FMT "d|n" 44 + 39 45 /* set during initialization */ 40 46 extern int ima_initialized; 41 47 extern int ima_used_chip; 42 - extern char *ima_hash; 48 + extern int ima_hash_algo; 43 49 extern int ima_appraise; 44 50 45 - /* IMA inode template definition */ 46 - struct ima_template_data { 47 - u8 digest[IMA_DIGEST_SIZE]; /* sha1/md5 measurement hash */ 48 - char file_name[IMA_EVENT_NAME_LEN_MAX + 1]; /* name + \0 */ 51 + /* IMA template field data definition */ 52 + struct ima_field_data { 53 + u8 *data; 54 + u32 len; 55 + }; 56 + 57 + /* IMA template field definition */ 58 + struct ima_template_field { 59 + const char field_id[IMA_TEMPLATE_FIELD_ID_MAX_LEN]; 60 + int (*field_init) (struct integrity_iint_cache *iint, struct file *file, 61 + const unsigned char *filename, 62 + struct evm_ima_xattr_data *xattr_value, 63 + int xattr_len, struct ima_field_data *field_data); 64 + void (*field_show) (struct seq_file *m, enum ima_show_type show, 65 + struct ima_field_data *field_data); 66 + }; 67 + 68 + /* IMA template descriptor definition */ 69 + struct ima_template_desc { 70 + char *name; 71 + char *fmt; 72 + int num_fields; 73 + struct ima_template_field **fields; 49 74 }; 50 75 51 76 struct ima_template_entry { 52 - u8 digest[IMA_DIGEST_SIZE]; /* sha1 or md5 measurement hash */ 53 - const char *template_name; 54 - int template_len; 55 - struct ima_template_data template; 77 + u8 digest[TPM_DIGEST_SIZE]; /* sha1 or md5 measurement hash */ 78 + struct ima_template_desc *template_desc; /* template descriptor */ 79 + u32 template_data_len; 80 + struct ima_field_data template_data[0]; /* template related data */ 56 81 }; 57 82 58 83 struct ima_queue_entry { ··· 94 69 void ima_fs_cleanup(void); 95 70 int ima_inode_alloc(struct inode *inode); 96 71 int ima_add_template_entry(struct ima_template_entry *entry, int violation, 97 - const char *op, struct inode *inode); 98 - int ima_calc_file_hash(struct file *file, char *digest); 99 - int ima_calc_buffer_hash(const void *data, int len, char *digest); 100 - int ima_calc_boot_aggregate(char *digest); 101 - void ima_add_violation(struct inode *inode, const unsigned char *filename, 72 + const char *op, struct inode *inode, 73 + const unsigned char *filename); 74 + int ima_calc_file_hash(struct file *file, struct ima_digest_data *hash); 75 + int ima_calc_field_array_hash(struct ima_field_data *field_data, int num_fields, 76 + struct ima_digest_data *hash); 77 + int __init ima_calc_boot_aggregate(struct ima_digest_data *hash); 78 + void ima_add_violation(struct file *file, const unsigned char *filename, 102 79 const char *op, const char *cause); 103 80 int ima_init_crypto(void); 81 + void ima_putc(struct seq_file *m, void *data, int datalen); 82 + void ima_print_digest(struct seq_file *m, u8 *digest, int size); 83 + struct ima_template_desc *ima_template_desc_current(void); 84 + int ima_init_template(void); 85 + 86 + int ima_init_template(void); 104 87 105 88 /* 106 89 * used to protect h_table and sha_table ··· 131 98 int ima_get_action(struct inode *inode, int mask, int function); 132 99 int ima_must_measure(struct inode *inode, int mask, int function); 133 100 int ima_collect_measurement(struct integrity_iint_cache *iint, 134 - struct file *file); 101 + struct file *file, 102 + struct evm_ima_xattr_data **xattr_value, 103 + int *xattr_len); 135 104 void ima_store_measurement(struct integrity_iint_cache *iint, struct file *file, 136 - const unsigned char *filename); 105 + const unsigned char *filename, 106 + struct evm_ima_xattr_data *xattr_value, 107 + int xattr_len); 137 108 void ima_audit_measurement(struct integrity_iint_cache *iint, 138 109 const unsigned char *filename); 110 + int ima_alloc_init_template(struct integrity_iint_cache *iint, 111 + struct file *file, const unsigned char *filename, 112 + struct evm_ima_xattr_data *xattr_value, 113 + int xattr_len, struct ima_template_entry **entry); 139 114 int ima_store_template(struct ima_template_entry *entry, int violation, 140 - struct inode *inode); 141 - void ima_template_show(struct seq_file *m, void *e, enum ima_show_type show); 115 + struct inode *inode, const unsigned char *filename); 142 116 const char *ima_d_path(struct path *path, char **pathbuf); 143 117 144 118 /* rbtree tree calls to lookup, insert, delete ··· 171 131 172 132 #ifdef CONFIG_IMA_APPRAISE 173 133 int ima_appraise_measurement(int func, struct integrity_iint_cache *iint, 174 - struct file *file, const unsigned char *filename); 134 + struct file *file, const unsigned char *filename, 135 + struct evm_ima_xattr_data *xattr_value, 136 + int xattr_len); 175 137 int ima_must_appraise(struct inode *inode, int mask, enum ima_hooks func); 176 138 void ima_update_xattr(struct integrity_iint_cache *iint, struct file *file); 177 139 enum integrity_status ima_get_cache_status(struct integrity_iint_cache *iint, 178 140 int func); 141 + void ima_get_hash_algo(struct evm_ima_xattr_data *xattr_value, int xattr_len, 142 + struct ima_digest_data *hash); 143 + int ima_read_xattr(struct dentry *dentry, 144 + struct evm_ima_xattr_data **xattr_value); 179 145 180 146 #else 181 147 static inline int ima_appraise_measurement(int func, 182 148 struct integrity_iint_cache *iint, 183 149 struct file *file, 184 - const unsigned char *filename) 150 + const unsigned char *filename, 151 + struct evm_ima_xattr_data *xattr_value, 152 + int xattr_len) 185 153 { 186 154 return INTEGRITY_UNKNOWN; 187 155 } ··· 210 162 { 211 163 return INTEGRITY_UNKNOWN; 212 164 } 165 + 166 + static inline void ima_get_hash_algo(struct evm_ima_xattr_data *xattr_value, 167 + int xattr_len, 168 + struct ima_digest_data *hash) 169 + { 170 + } 171 + 172 + static inline int ima_read_xattr(struct dentry *dentry, 173 + struct evm_ima_xattr_data **xattr_value) 174 + { 175 + return 0; 176 + } 177 + 213 178 #endif 214 179 215 180 /* LSM based policy rules require audit */
+101 -35
security/integrity/ima/ima_api.c
··· 18 18 #include <linux/fs.h> 19 19 #include <linux/xattr.h> 20 20 #include <linux/evm.h> 21 + #include <crypto/hash_info.h> 21 22 #include "ima.h" 22 23 23 - static const char *IMA_TEMPLATE_NAME = "ima"; 24 + /* 25 + * ima_alloc_init_template - create and initialize a new template entry 26 + */ 27 + int ima_alloc_init_template(struct integrity_iint_cache *iint, 28 + struct file *file, const unsigned char *filename, 29 + struct evm_ima_xattr_data *xattr_value, 30 + int xattr_len, struct ima_template_entry **entry) 31 + { 32 + struct ima_template_desc *template_desc = ima_template_desc_current(); 33 + int i, result = 0; 34 + 35 + *entry = kzalloc(sizeof(**entry) + template_desc->num_fields * 36 + sizeof(struct ima_field_data), GFP_NOFS); 37 + if (!*entry) 38 + return -ENOMEM; 39 + 40 + for (i = 0; i < template_desc->num_fields; i++) { 41 + struct ima_template_field *field = template_desc->fields[i]; 42 + u32 len; 43 + 44 + result = field->field_init(iint, file, filename, 45 + xattr_value, xattr_len, 46 + &((*entry)->template_data[i])); 47 + if (result != 0) 48 + goto out; 49 + 50 + len = (*entry)->template_data[i].len; 51 + (*entry)->template_data_len += sizeof(len); 52 + (*entry)->template_data_len += len; 53 + } 54 + (*entry)->template_desc = template_desc; 55 + return 0; 56 + out: 57 + kfree(*entry); 58 + *entry = NULL; 59 + return result; 60 + } 24 61 25 62 /* 26 63 * ima_store_template - store ima template measurements ··· 76 39 * Returns 0 on success, error code otherwise 77 40 */ 78 41 int ima_store_template(struct ima_template_entry *entry, 79 - int violation, struct inode *inode) 42 + int violation, struct inode *inode, 43 + const unsigned char *filename) 80 44 { 81 45 const char *op = "add_template_measure"; 82 46 const char *audit_cause = "hashing_error"; 47 + char *template_name = entry->template_desc->name; 83 48 int result; 84 - 85 - memset(entry->digest, 0, sizeof(entry->digest)); 86 - entry->template_name = IMA_TEMPLATE_NAME; 87 - entry->template_len = sizeof(entry->template); 49 + struct { 50 + struct ima_digest_data hdr; 51 + char digest[TPM_DIGEST_SIZE]; 52 + } hash; 88 53 89 54 if (!violation) { 90 - result = ima_calc_buffer_hash(&entry->template, 91 - entry->template_len, 92 - entry->digest); 55 + int num_fields = entry->template_desc->num_fields; 56 + 57 + /* this function uses default algo */ 58 + hash.hdr.algo = HASH_ALGO_SHA1; 59 + result = ima_calc_field_array_hash(&entry->template_data[0], 60 + num_fields, &hash.hdr); 93 61 if (result < 0) { 94 62 integrity_audit_msg(AUDIT_INTEGRITY_PCR, inode, 95 - entry->template_name, op, 63 + template_name, op, 96 64 audit_cause, result, 0); 97 65 return result; 98 66 } 67 + memcpy(entry->digest, hash.hdr.digest, hash.hdr.length); 99 68 } 100 - result = ima_add_template_entry(entry, violation, op, inode); 69 + result = ima_add_template_entry(entry, violation, op, inode, filename); 101 70 return result; 102 71 } 103 72 ··· 114 71 * By extending the PCR with 0xFF's instead of with zeroes, the PCR 115 72 * value is invalidated. 116 73 */ 117 - void ima_add_violation(struct inode *inode, const unsigned char *filename, 74 + void ima_add_violation(struct file *file, const unsigned char *filename, 118 75 const char *op, const char *cause) 119 76 { 120 77 struct ima_template_entry *entry; 78 + struct inode *inode = file->f_dentry->d_inode; 121 79 int violation = 1; 122 80 int result; 123 81 124 82 /* can overflow, only indicator */ 125 83 atomic_long_inc(&ima_htable.violations); 126 84 127 - entry = kmalloc(sizeof(*entry), GFP_KERNEL); 128 - if (!entry) { 85 + result = ima_alloc_init_template(NULL, file, filename, 86 + NULL, 0, &entry); 87 + if (result < 0) { 129 88 result = -ENOMEM; 130 89 goto err_out; 131 90 } 132 - memset(&entry->template, 0, sizeof(entry->template)); 133 - strncpy(entry->template.file_name, filename, IMA_EVENT_NAME_LEN_MAX); 134 - result = ima_store_template(entry, violation, inode); 91 + result = ima_store_template(entry, violation, inode, filename); 135 92 if (result < 0) 136 93 kfree(entry); 137 94 err_out: ··· 181 138 * Return 0 on success, error code otherwise 182 139 */ 183 140 int ima_collect_measurement(struct integrity_iint_cache *iint, 184 - struct file *file) 141 + struct file *file, 142 + struct evm_ima_xattr_data **xattr_value, 143 + int *xattr_len) 185 144 { 186 145 struct inode *inode = file_inode(file); 187 146 const char *filename = file->f_dentry->d_name.name; 188 147 int result = 0; 148 + struct { 149 + struct ima_digest_data hdr; 150 + char digest[IMA_MAX_DIGEST_SIZE]; 151 + } hash; 152 + 153 + if (xattr_value) 154 + *xattr_len = ima_read_xattr(file->f_dentry, xattr_value); 189 155 190 156 if (!(iint->flags & IMA_COLLECTED)) { 191 157 u64 i_version = file_inode(file)->i_version; 192 158 193 - iint->ima_xattr.type = IMA_XATTR_DIGEST; 194 - result = ima_calc_file_hash(file, iint->ima_xattr.digest); 159 + /* use default hash algorithm */ 160 + hash.hdr.algo = ima_hash_algo; 161 + 162 + if (xattr_value) 163 + ima_get_hash_algo(*xattr_value, *xattr_len, &hash.hdr); 164 + 165 + result = ima_calc_file_hash(file, &hash.hdr); 195 166 if (!result) { 196 - iint->version = i_version; 197 - iint->flags |= IMA_COLLECTED; 167 + int length = sizeof(hash.hdr) + hash.hdr.length; 168 + void *tmpbuf = krealloc(iint->ima_hash, length, 169 + GFP_NOFS); 170 + if (tmpbuf) { 171 + iint->ima_hash = tmpbuf; 172 + memcpy(iint->ima_hash, &hash, length); 173 + iint->version = i_version; 174 + iint->flags |= IMA_COLLECTED; 175 + } else 176 + result = -ENOMEM; 198 177 } 199 178 } 200 179 if (result) ··· 242 177 * Must be called with iint->mutex held. 243 178 */ 244 179 void ima_store_measurement(struct integrity_iint_cache *iint, 245 - struct file *file, const unsigned char *filename) 180 + struct file *file, const unsigned char *filename, 181 + struct evm_ima_xattr_data *xattr_value, 182 + int xattr_len) 246 183 { 247 184 const char *op = "add_template_measure"; 248 185 const char *audit_cause = "ENOMEM"; ··· 256 189 if (iint->flags & IMA_MEASURED) 257 190 return; 258 191 259 - entry = kmalloc(sizeof(*entry), GFP_KERNEL); 260 - if (!entry) { 192 + result = ima_alloc_init_template(iint, file, filename, 193 + xattr_value, xattr_len, &entry); 194 + if (result < 0) { 261 195 integrity_audit_msg(AUDIT_INTEGRITY_PCR, inode, filename, 262 196 op, audit_cause, result, 0); 263 197 return; 264 198 } 265 - memset(&entry->template, 0, sizeof(entry->template)); 266 - memcpy(entry->template.digest, iint->ima_xattr.digest, IMA_DIGEST_SIZE); 267 - strcpy(entry->template.file_name, 268 - (strlen(filename) > IMA_EVENT_NAME_LEN_MAX) ? 269 - file->f_dentry->d_name.name : filename); 270 199 271 - result = ima_store_template(entry, violation, inode); 200 + result = ima_store_template(entry, violation, inode, filename); 272 201 if (!result || result == -EEXIST) 273 202 iint->flags |= IMA_MEASURED; 274 203 if (result < 0) ··· 275 212 const unsigned char *filename) 276 213 { 277 214 struct audit_buffer *ab; 278 - char hash[(IMA_DIGEST_SIZE * 2) + 1]; 215 + char hash[(iint->ima_hash->length * 2) + 1]; 216 + const char *algo_name = hash_algo_name[iint->ima_hash->algo]; 217 + char algo_hash[sizeof(hash) + strlen(algo_name) + 2]; 279 218 int i; 280 219 281 220 if (iint->flags & IMA_AUDITED) 282 221 return; 283 222 284 - for (i = 0; i < IMA_DIGEST_SIZE; i++) 285 - hex_byte_pack(hash + (i * 2), iint->ima_xattr.digest[i]); 223 + for (i = 0; i < iint->ima_hash->length; i++) 224 + hex_byte_pack(hash + (i * 2), iint->ima_hash->digest[i]); 286 225 hash[i * 2] = '\0'; 287 226 288 227 ab = audit_log_start(current->audit_context, GFP_KERNEL, ··· 295 230 audit_log_format(ab, "file="); 296 231 audit_log_untrustedstring(ab, filename); 297 232 audit_log_format(ab, " hash="); 298 - audit_log_untrustedstring(ab, hash); 233 + snprintf(algo_hash, sizeof(algo_hash), "%s:%s", algo_name, hash); 234 + audit_log_untrustedstring(ab, algo_hash); 299 235 300 236 audit_log_task_info(ab, current); 301 237 audit_log_end(ab);
+97 -20
security/integrity/ima/ima_appraise.c
··· 15 15 #include <linux/magic.h> 16 16 #include <linux/ima.h> 17 17 #include <linux/evm.h> 18 + #include <crypto/hash_info.h> 18 19 19 20 #include "ima.h" 20 21 ··· 44 43 } 45 44 46 45 static int ima_fix_xattr(struct dentry *dentry, 47 - struct integrity_iint_cache *iint) 46 + struct integrity_iint_cache *iint) 48 47 { 49 - iint->ima_xattr.type = IMA_XATTR_DIGEST; 50 - return __vfs_setxattr_noperm(dentry, XATTR_NAME_IMA, 51 - (u8 *)&iint->ima_xattr, 52 - sizeof(iint->ima_xattr), 0); 48 + int rc, offset; 49 + u8 algo = iint->ima_hash->algo; 50 + 51 + if (algo <= HASH_ALGO_SHA1) { 52 + offset = 1; 53 + iint->ima_hash->xattr.sha1.type = IMA_XATTR_DIGEST; 54 + } else { 55 + offset = 0; 56 + iint->ima_hash->xattr.ng.type = IMA_XATTR_DIGEST_NG; 57 + iint->ima_hash->xattr.ng.algo = algo; 58 + } 59 + rc = __vfs_setxattr_noperm(dentry, XATTR_NAME_IMA, 60 + &iint->ima_hash->xattr.data[offset], 61 + (sizeof(iint->ima_hash->xattr) - offset) + 62 + iint->ima_hash->length, 0); 63 + return rc; 53 64 } 54 65 55 66 /* Return specific func appraised cached result */ 56 67 enum integrity_status ima_get_cache_status(struct integrity_iint_cache *iint, 57 68 int func) 58 69 { 59 - switch(func) { 70 + switch (func) { 60 71 case MMAP_CHECK: 61 72 return iint->ima_mmap_status; 62 73 case BPRM_CHECK: ··· 84 71 static void ima_set_cache_status(struct integrity_iint_cache *iint, 85 72 int func, enum integrity_status status) 86 73 { 87 - switch(func) { 74 + switch (func) { 88 75 case MMAP_CHECK: 89 76 iint->ima_mmap_status = status; 90 77 break; ··· 103 90 104 91 static void ima_cache_flags(struct integrity_iint_cache *iint, int func) 105 92 { 106 - switch(func) { 93 + switch (func) { 107 94 case MMAP_CHECK: 108 95 iint->flags |= (IMA_MMAP_APPRAISED | IMA_APPRAISED); 109 96 break; ··· 120 107 } 121 108 } 122 109 110 + void ima_get_hash_algo(struct evm_ima_xattr_data *xattr_value, int xattr_len, 111 + struct ima_digest_data *hash) 112 + { 113 + struct signature_v2_hdr *sig; 114 + 115 + if (!xattr_value || xattr_len < 2) 116 + return; 117 + 118 + switch (xattr_value->type) { 119 + case EVM_IMA_XATTR_DIGSIG: 120 + sig = (typeof(sig))xattr_value; 121 + if (sig->version != 2 || xattr_len <= sizeof(*sig)) 122 + return; 123 + hash->algo = sig->hash_algo; 124 + break; 125 + case IMA_XATTR_DIGEST_NG: 126 + hash->algo = xattr_value->digest[0]; 127 + break; 128 + case IMA_XATTR_DIGEST: 129 + /* this is for backward compatibility */ 130 + if (xattr_len == 21) { 131 + unsigned int zero = 0; 132 + if (!memcmp(&xattr_value->digest[16], &zero, 4)) 133 + hash->algo = HASH_ALGO_MD5; 134 + else 135 + hash->algo = HASH_ALGO_SHA1; 136 + } else if (xattr_len == 17) 137 + hash->algo = HASH_ALGO_MD5; 138 + break; 139 + } 140 + } 141 + 142 + int ima_read_xattr(struct dentry *dentry, 143 + struct evm_ima_xattr_data **xattr_value) 144 + { 145 + struct inode *inode = dentry->d_inode; 146 + 147 + if (!inode->i_op->getxattr) 148 + return 0; 149 + 150 + return vfs_getxattr_alloc(dentry, XATTR_NAME_IMA, (char **)xattr_value, 151 + 0, GFP_NOFS); 152 + } 153 + 123 154 /* 124 155 * ima_appraise_measurement - appraise file measurement 125 156 * ··· 173 116 * Return 0 on success, error code otherwise 174 117 */ 175 118 int ima_appraise_measurement(int func, struct integrity_iint_cache *iint, 176 - struct file *file, const unsigned char *filename) 119 + struct file *file, const unsigned char *filename, 120 + struct evm_ima_xattr_data *xattr_value, 121 + int xattr_len) 177 122 { 178 123 struct dentry *dentry = file->f_dentry; 179 124 struct inode *inode = dentry->d_inode; 180 - struct evm_ima_xattr_data *xattr_value = NULL; 181 125 enum integrity_status status = INTEGRITY_UNKNOWN; 182 126 const char *op = "appraise_data"; 183 127 char *cause = "unknown"; 184 - int rc; 128 + int rc = xattr_len, hash_start = 0; 185 129 186 130 if (!ima_appraise) 187 131 return 0; 188 132 if (!inode->i_op->getxattr) 189 133 return INTEGRITY_UNKNOWN; 190 134 191 - rc = vfs_getxattr_alloc(dentry, XATTR_NAME_IMA, (char **)&xattr_value, 192 - 0, GFP_NOFS); 193 135 if (rc <= 0) { 194 136 if (rc && rc != -ENODATA) 195 137 goto out; ··· 209 153 goto out; 210 154 } 211 155 switch (xattr_value->type) { 156 + case IMA_XATTR_DIGEST_NG: 157 + /* first byte contains algorithm id */ 158 + hash_start = 1; 212 159 case IMA_XATTR_DIGEST: 213 160 if (iint->flags & IMA_DIGSIG_REQUIRED) { 214 161 cause = "IMA signature required"; 215 162 status = INTEGRITY_FAIL; 216 163 break; 217 164 } 218 - rc = memcmp(xattr_value->digest, iint->ima_xattr.digest, 219 - IMA_DIGEST_SIZE); 165 + if (xattr_len - sizeof(xattr_value->type) - hash_start >= 166 + iint->ima_hash->length) 167 + /* xattr length may be longer. md5 hash in previous 168 + version occupied 20 bytes in xattr, instead of 16 169 + */ 170 + rc = memcmp(&xattr_value->digest[hash_start], 171 + iint->ima_hash->digest, 172 + iint->ima_hash->length); 173 + else 174 + rc = -EINVAL; 220 175 if (rc) { 221 176 cause = "invalid-hash"; 222 177 status = INTEGRITY_FAIL; ··· 238 171 case EVM_IMA_XATTR_DIGSIG: 239 172 iint->flags |= IMA_DIGSIG; 240 173 rc = integrity_digsig_verify(INTEGRITY_KEYRING_IMA, 241 - xattr_value->digest, rc - 1, 242 - iint->ima_xattr.digest, 243 - IMA_DIGEST_SIZE); 174 + (const char *)xattr_value, rc, 175 + iint->ima_hash->digest, 176 + iint->ima_hash->length); 244 177 if (rc == -EOPNOTSUPP) { 245 178 status = INTEGRITY_UNKNOWN; 246 179 } else if (rc) { ··· 270 203 ima_cache_flags(iint, func); 271 204 } 272 205 ima_set_cache_status(iint, func, status); 273 - kfree(xattr_value); 274 206 return status; 275 207 } 276 208 ··· 285 219 if (iint->flags & IMA_DIGSIG) 286 220 return; 287 221 288 - rc = ima_collect_measurement(iint, file); 222 + rc = ima_collect_measurement(iint, file, NULL, NULL); 289 223 if (rc < 0) 290 224 return; 291 225 ··· 381 315 } 382 316 return result; 383 317 } 318 + 319 + #ifdef CONFIG_IMA_TRUSTED_KEYRING 320 + static int __init init_ima_keyring(void) 321 + { 322 + int ret; 323 + 324 + ret = integrity_init_keyring(INTEGRITY_KEYRING_IMA); 325 + return 0; 326 + } 327 + late_initcall(init_ima_keyring); 328 + #endif
+118 -16
security/integrity/ima/ima_crypto.c
··· 20 20 #include <linux/err.h> 21 21 #include <linux/slab.h> 22 22 #include <crypto/hash.h> 23 + #include <crypto/hash_info.h> 23 24 #include "ima.h" 24 25 25 26 static struct crypto_shash *ima_shash_tfm; ··· 29 28 { 30 29 long rc; 31 30 32 - ima_shash_tfm = crypto_alloc_shash(ima_hash, 0, 0); 31 + ima_shash_tfm = crypto_alloc_shash(hash_algo_name[ima_hash_algo], 0, 0); 33 32 if (IS_ERR(ima_shash_tfm)) { 34 33 rc = PTR_ERR(ima_shash_tfm); 35 - pr_err("Can not allocate %s (reason: %ld)\n", ima_hash, rc); 34 + pr_err("Can not allocate %s (reason: %ld)\n", 35 + hash_algo_name[ima_hash_algo], rc); 36 36 return rc; 37 37 } 38 38 return 0; 39 39 } 40 40 41 + static struct crypto_shash *ima_alloc_tfm(enum hash_algo algo) 42 + { 43 + struct crypto_shash *tfm = ima_shash_tfm; 44 + int rc; 45 + 46 + if (algo != ima_hash_algo && algo < HASH_ALGO__LAST) { 47 + tfm = crypto_alloc_shash(hash_algo_name[algo], 0, 0); 48 + if (IS_ERR(tfm)) { 49 + rc = PTR_ERR(tfm); 50 + pr_err("Can not allocate %s (reason: %d)\n", 51 + hash_algo_name[algo], rc); 52 + } 53 + } 54 + return tfm; 55 + } 56 + 57 + static void ima_free_tfm(struct crypto_shash *tfm) 58 + { 59 + if (tfm != ima_shash_tfm) 60 + crypto_free_shash(tfm); 61 + } 62 + 41 63 /* 42 64 * Calculate the MD5/SHA1 file digest 43 65 */ 44 - int ima_calc_file_hash(struct file *file, char *digest) 66 + static int ima_calc_file_hash_tfm(struct file *file, 67 + struct ima_digest_data *hash, 68 + struct crypto_shash *tfm) 45 69 { 46 70 loff_t i_size, offset = 0; 47 71 char *rbuf; 48 72 int rc, read = 0; 49 73 struct { 50 74 struct shash_desc shash; 51 - char ctx[crypto_shash_descsize(ima_shash_tfm)]; 75 + char ctx[crypto_shash_descsize(tfm)]; 52 76 } desc; 53 77 54 - desc.shash.tfm = ima_shash_tfm; 78 + desc.shash.tfm = tfm; 55 79 desc.shash.flags = 0; 80 + 81 + hash->length = crypto_shash_digestsize(tfm); 56 82 57 83 rc = crypto_shash_init(&desc.shash); 58 84 if (rc != 0) ··· 113 85 } 114 86 kfree(rbuf); 115 87 if (!rc) 116 - rc = crypto_shash_final(&desc.shash, digest); 88 + rc = crypto_shash_final(&desc.shash, hash->digest); 117 89 if (read) 118 90 file->f_mode &= ~FMODE_READ; 119 91 out: 120 92 return rc; 121 93 } 122 94 95 + int ima_calc_file_hash(struct file *file, struct ima_digest_data *hash) 96 + { 97 + struct crypto_shash *tfm; 98 + int rc; 99 + 100 + tfm = ima_alloc_tfm(hash->algo); 101 + if (IS_ERR(tfm)) 102 + return PTR_ERR(tfm); 103 + 104 + rc = ima_calc_file_hash_tfm(file, hash, tfm); 105 + 106 + ima_free_tfm(tfm); 107 + 108 + return rc; 109 + } 110 + 123 111 /* 124 - * Calculate the hash of a given buffer 112 + * Calculate the hash of template data 125 113 */ 126 - int ima_calc_buffer_hash(const void *data, int len, char *digest) 114 + static int ima_calc_field_array_hash_tfm(struct ima_field_data *field_data, 115 + int num_fields, 116 + struct ima_digest_data *hash, 117 + struct crypto_shash *tfm) 127 118 { 128 119 struct { 129 120 struct shash_desc shash; 130 - char ctx[crypto_shash_descsize(ima_shash_tfm)]; 121 + char ctx[crypto_shash_descsize(tfm)]; 131 122 } desc; 123 + int rc, i; 132 124 133 - desc.shash.tfm = ima_shash_tfm; 125 + desc.shash.tfm = tfm; 134 126 desc.shash.flags = 0; 135 127 136 - return crypto_shash_digest(&desc.shash, data, len, digest); 128 + hash->length = crypto_shash_digestsize(tfm); 129 + 130 + rc = crypto_shash_init(&desc.shash); 131 + if (rc != 0) 132 + return rc; 133 + 134 + for (i = 0; i < num_fields; i++) { 135 + rc = crypto_shash_update(&desc.shash, 136 + (const u8 *) &field_data[i].len, 137 + sizeof(field_data[i].len)); 138 + rc = crypto_shash_update(&desc.shash, field_data[i].data, 139 + field_data[i].len); 140 + if (rc) 141 + break; 142 + } 143 + 144 + if (!rc) 145 + rc = crypto_shash_final(&desc.shash, hash->digest); 146 + 147 + return rc; 148 + } 149 + 150 + int ima_calc_field_array_hash(struct ima_field_data *field_data, int num_fields, 151 + struct ima_digest_data *hash) 152 + { 153 + struct crypto_shash *tfm; 154 + int rc; 155 + 156 + tfm = ima_alloc_tfm(hash->algo); 157 + if (IS_ERR(tfm)) 158 + return PTR_ERR(tfm); 159 + 160 + rc = ima_calc_field_array_hash_tfm(field_data, num_fields, hash, tfm); 161 + 162 + ima_free_tfm(tfm); 163 + 164 + return rc; 137 165 } 138 166 139 167 static void __init ima_pcrread(int idx, u8 *pcr) ··· 204 120 /* 205 121 * Calculate the boot aggregate hash 206 122 */ 207 - int __init ima_calc_boot_aggregate(char *digest) 123 + static int __init ima_calc_boot_aggregate_tfm(char *digest, 124 + struct crypto_shash *tfm) 208 125 { 209 - u8 pcr_i[IMA_DIGEST_SIZE]; 126 + u8 pcr_i[TPM_DIGEST_SIZE]; 210 127 int rc, i; 211 128 struct { 212 129 struct shash_desc shash; 213 - char ctx[crypto_shash_descsize(ima_shash_tfm)]; 130 + char ctx[crypto_shash_descsize(tfm)]; 214 131 } desc; 215 132 216 - desc.shash.tfm = ima_shash_tfm; 133 + desc.shash.tfm = tfm; 217 134 desc.shash.flags = 0; 218 135 219 136 rc = crypto_shash_init(&desc.shash); ··· 225 140 for (i = TPM_PCR0; i < TPM_PCR8; i++) { 226 141 ima_pcrread(i, pcr_i); 227 142 /* now accumulate with current aggregate */ 228 - rc = crypto_shash_update(&desc.shash, pcr_i, IMA_DIGEST_SIZE); 143 + rc = crypto_shash_update(&desc.shash, pcr_i, TPM_DIGEST_SIZE); 229 144 } 230 145 if (!rc) 231 146 crypto_shash_final(&desc.shash, digest); 147 + return rc; 148 + } 149 + 150 + int __init ima_calc_boot_aggregate(struct ima_digest_data *hash) 151 + { 152 + struct crypto_shash *tfm; 153 + int rc; 154 + 155 + tfm = ima_alloc_tfm(hash->algo); 156 + if (IS_ERR(tfm)) 157 + return PTR_ERR(tfm); 158 + 159 + hash->length = crypto_shash_digestsize(tfm); 160 + rc = ima_calc_boot_aggregate_tfm(hash->digest, tfm); 161 + 162 + ima_free_tfm(tfm); 163 + 232 164 return rc; 233 165 }
+31 -36
security/integrity/ima/ima_fs.c
··· 88 88 * against concurrent list-extension 89 89 */ 90 90 rcu_read_lock(); 91 - qe = list_entry_rcu(qe->later.next, 92 - struct ima_queue_entry, later); 91 + qe = list_entry_rcu(qe->later.next, struct ima_queue_entry, later); 93 92 rcu_read_unlock(); 94 93 (*pos)++; 95 94 ··· 99 100 { 100 101 } 101 102 102 - static void ima_putc(struct seq_file *m, void *data, int datalen) 103 + void ima_putc(struct seq_file *m, void *data, int datalen) 103 104 { 104 105 while (datalen--) 105 106 seq_putc(m, *(char *)data++); ··· 110 111 * char[20]=template digest 111 112 * 32bit-le=template name size 112 113 * char[n]=template name 114 + * [eventdata length] 113 115 * eventdata[n]=template specific data 114 116 */ 115 117 static int ima_measurements_show(struct seq_file *m, void *v) ··· 120 120 struct ima_template_entry *e; 121 121 int namelen; 122 122 u32 pcr = CONFIG_IMA_MEASURE_PCR_IDX; 123 + int i; 123 124 124 125 /* get entry */ 125 126 e = qe->entry; ··· 135 134 ima_putc(m, &pcr, sizeof pcr); 136 135 137 136 /* 2nd: template digest */ 138 - ima_putc(m, e->digest, IMA_DIGEST_SIZE); 137 + ima_putc(m, e->digest, TPM_DIGEST_SIZE); 139 138 140 139 /* 3rd: template name size */ 141 - namelen = strlen(e->template_name); 140 + namelen = strlen(e->template_desc->name); 142 141 ima_putc(m, &namelen, sizeof namelen); 143 142 144 143 /* 4th: template name */ 145 - ima_putc(m, (void *)e->template_name, namelen); 144 + ima_putc(m, e->template_desc->name, namelen); 146 145 147 - /* 5th: template specific data */ 148 - ima_template_show(m, (struct ima_template_data *)&e->template, 149 - IMA_SHOW_BINARY); 146 + /* 5th: template length (except for 'ima' template) */ 147 + if (strcmp(e->template_desc->name, IMA_TEMPLATE_IMA_NAME) != 0) 148 + ima_putc(m, &e->template_data_len, 149 + sizeof(e->template_data_len)); 150 + 151 + /* 6th: template specific data */ 152 + for (i = 0; i < e->template_desc->num_fields; i++) { 153 + e->template_desc->fields[i]->field_show(m, IMA_SHOW_BINARY, 154 + &e->template_data[i]); 155 + } 150 156 return 0; 151 157 } 152 158 ··· 176 168 .release = seq_release, 177 169 }; 178 170 179 - static void ima_print_digest(struct seq_file *m, u8 *digest) 171 + void ima_print_digest(struct seq_file *m, u8 *digest, int size) 180 172 { 181 173 int i; 182 174 183 - for (i = 0; i < IMA_DIGEST_SIZE; i++) 175 + for (i = 0; i < size; i++) 184 176 seq_printf(m, "%02x", *(digest + i)); 185 - } 186 - 187 - void ima_template_show(struct seq_file *m, void *e, enum ima_show_type show) 188 - { 189 - struct ima_template_data *entry = e; 190 - int namelen; 191 - 192 - switch (show) { 193 - case IMA_SHOW_ASCII: 194 - ima_print_digest(m, entry->digest); 195 - seq_printf(m, " %s\n", entry->file_name); 196 - break; 197 - case IMA_SHOW_BINARY: 198 - ima_putc(m, entry->digest, IMA_DIGEST_SIZE); 199 - 200 - namelen = strlen(entry->file_name); 201 - ima_putc(m, &namelen, sizeof namelen); 202 - ima_putc(m, entry->file_name, namelen); 203 - default: 204 - break; 205 - } 206 177 } 207 178 208 179 /* print in ascii */ ··· 190 203 /* the list never shrinks, so we don't need a lock here */ 191 204 struct ima_queue_entry *qe = v; 192 205 struct ima_template_entry *e; 206 + int i; 193 207 194 208 /* get entry */ 195 209 e = qe->entry; ··· 201 213 seq_printf(m, "%2d ", CONFIG_IMA_MEASURE_PCR_IDX); 202 214 203 215 /* 2nd: SHA1 template hash */ 204 - ima_print_digest(m, e->digest); 216 + ima_print_digest(m, e->digest, TPM_DIGEST_SIZE); 205 217 206 218 /* 3th: template name */ 207 - seq_printf(m, " %s ", e->template_name); 219 + seq_printf(m, " %s", e->template_desc->name); 208 220 209 221 /* 4th: template specific data */ 210 - ima_template_show(m, (struct ima_template_data *)&e->template, 211 - IMA_SHOW_ASCII); 222 + for (i = 0; i < e->template_desc->num_fields; i++) { 223 + seq_puts(m, " "); 224 + if (e->template_data[i].len == 0) 225 + continue; 226 + 227 + e->template_desc->fields[i]->field_show(m, IMA_SHOW_ASCII, 228 + &e->template_data[i]); 229 + } 230 + seq_puts(m, "\n"); 212 231 return 0; 213 232 } 214 233
+26 -11
security/integrity/ima/ima_init.c
··· 18 18 #include <linux/scatterlist.h> 19 19 #include <linux/slab.h> 20 20 #include <linux/err.h> 21 + #include <crypto/hash_info.h> 21 22 #include "ima.h" 22 23 23 24 /* name for boot aggregate entry */ ··· 43 42 static void __init ima_add_boot_aggregate(void) 44 43 { 45 44 struct ima_template_entry *entry; 45 + struct integrity_iint_cache tmp_iint, *iint = &tmp_iint; 46 46 const char *op = "add_boot_aggregate"; 47 47 const char *audit_cause = "ENOMEM"; 48 48 int result = -ENOMEM; 49 - int violation = 1; 49 + int violation = 0; 50 + struct { 51 + struct ima_digest_data hdr; 52 + char digest[TPM_DIGEST_SIZE]; 53 + } hash; 50 54 51 - entry = kmalloc(sizeof(*entry), GFP_KERNEL); 52 - if (!entry) 53 - goto err_out; 55 + memset(iint, 0, sizeof(*iint)); 56 + memset(&hash, 0, sizeof(hash)); 57 + iint->ima_hash = &hash.hdr; 58 + iint->ima_hash->algo = HASH_ALGO_SHA1; 59 + iint->ima_hash->length = SHA1_DIGEST_SIZE; 54 60 55 - memset(&entry->template, 0, sizeof(entry->template)); 56 - strncpy(entry->template.file_name, boot_aggregate_name, 57 - IMA_EVENT_NAME_LEN_MAX); 58 61 if (ima_used_chip) { 59 - violation = 0; 60 - result = ima_calc_boot_aggregate(entry->template.digest); 62 + result = ima_calc_boot_aggregate(&hash.hdr); 61 63 if (result < 0) { 62 64 audit_cause = "hashing_error"; 63 65 kfree(entry); 64 66 goto err_out; 65 67 } 66 68 } 67 - result = ima_store_template(entry, violation, NULL); 69 + 70 + result = ima_alloc_init_template(iint, NULL, boot_aggregate_name, 71 + NULL, 0, &entry); 72 + if (result < 0) 73 + return; 74 + 75 + result = ima_store_template(entry, violation, NULL, 76 + boot_aggregate_name); 68 77 if (result < 0) 69 78 kfree(entry); 70 79 return; ··· 85 74 86 75 int __init ima_init(void) 87 76 { 88 - u8 pcr_i[IMA_DIGEST_SIZE]; 77 + u8 pcr_i[TPM_DIGEST_SIZE]; 89 78 int rc; 90 79 91 80 ima_used_chip = 0; ··· 99 88 rc = ima_init_crypto(); 100 89 if (rc) 101 90 return rc; 91 + rc = ima_init_template(); 92 + if (rc != 0) 93 + return rc; 94 + 102 95 ima_add_boot_aggregate(); /* boot aggregate must be first entry */ 103 96 ima_init_policy(); 104 97
+49 -14
security/integrity/ima/ima_main.c
··· 24 24 #include <linux/slab.h> 25 25 #include <linux/xattr.h> 26 26 #include <linux/ima.h> 27 + #include <crypto/hash_info.h> 27 28 28 29 #include "ima.h" 29 30 ··· 36 35 int ima_appraise; 37 36 #endif 38 37 39 - char *ima_hash = "sha1"; 38 + int ima_hash_algo = HASH_ALGO_SHA1; 39 + static int hash_setup_done; 40 + 40 41 static int __init hash_setup(char *str) 41 42 { 42 - if (strncmp(str, "md5", 3) == 0) 43 - ima_hash = "md5"; 43 + struct ima_template_desc *template_desc = ima_template_desc_current(); 44 + int i; 45 + 46 + if (hash_setup_done) 47 + return 1; 48 + 49 + if (strcmp(template_desc->name, IMA_TEMPLATE_IMA_NAME) == 0) { 50 + if (strncmp(str, "sha1", 4) == 0) 51 + ima_hash_algo = HASH_ALGO_SHA1; 52 + else if (strncmp(str, "md5", 3) == 0) 53 + ima_hash_algo = HASH_ALGO_MD5; 54 + goto out; 55 + } 56 + 57 + for (i = 0; i < HASH_ALGO__LAST; i++) { 58 + if (strcmp(str, hash_algo_name[i]) == 0) { 59 + ima_hash_algo = i; 60 + break; 61 + } 62 + } 63 + out: 64 + hash_setup_done = 1; 44 65 return 1; 45 66 } 46 67 __setup("ima_hash=", hash_setup); ··· 115 92 pathname = dentry->d_name.name; 116 93 117 94 if (send_tomtou) 118 - ima_add_violation(inode, pathname, 119 - "invalid_pcr", "ToMToU"); 95 + ima_add_violation(file, pathname, "invalid_pcr", "ToMToU"); 120 96 if (send_writers) 121 - ima_add_violation(inode, pathname, 97 + ima_add_violation(file, pathname, 122 98 "invalid_pcr", "open_writers"); 123 99 kfree(pathbuf); 124 100 } ··· 166 144 { 167 145 struct inode *inode = file_inode(file); 168 146 struct integrity_iint_cache *iint; 147 + struct ima_template_desc *template_desc = ima_template_desc_current(); 169 148 char *pathbuf = NULL; 170 149 const char *pathname = NULL; 171 150 int rc = -ENOMEM, action, must_appraise, _func; 151 + struct evm_ima_xattr_data *xattr_value = NULL, **xattr_ptr = NULL; 152 + int xattr_len = 0; 172 153 173 154 if (!ima_initialized || !S_ISREG(inode->i_mode)) 174 155 return 0; ··· 210 185 goto out_digsig; 211 186 } 212 187 213 - rc = ima_collect_measurement(iint, file); 188 + if (strcmp(template_desc->name, IMA_TEMPLATE_IMA_NAME) == 0) { 189 + if (action & IMA_APPRAISE_SUBMASK) 190 + xattr_ptr = &xattr_value; 191 + } else 192 + xattr_ptr = &xattr_value; 193 + 194 + rc = ima_collect_measurement(iint, file, xattr_ptr, &xattr_len); 214 195 if (rc != 0) 215 196 goto out_digsig; 216 197 ··· 225 194 pathname = (const char *)file->f_dentry->d_name.name; 226 195 227 196 if (action & IMA_MEASURE) 228 - ima_store_measurement(iint, file, pathname); 197 + ima_store_measurement(iint, file, pathname, 198 + xattr_value, xattr_len); 229 199 if (action & IMA_APPRAISE_SUBMASK) 230 - rc = ima_appraise_measurement(_func, iint, file, pathname); 200 + rc = ima_appraise_measurement(_func, iint, file, pathname, 201 + xattr_value, xattr_len); 231 202 if (action & IMA_AUDIT) 232 203 ima_audit_measurement(iint, pathname); 233 204 kfree(pathbuf); ··· 238 205 rc = -EACCES; 239 206 out: 240 207 mutex_unlock(&inode->i_mutex); 208 + kfree(xattr_value); 241 209 if ((rc && must_appraise) && (ima_appraise & IMA_APPRAISE_ENFORCE)) 242 210 return -EACCES; 243 211 return 0; ··· 278 244 int ima_bprm_check(struct linux_binprm *bprm) 279 245 { 280 246 return process_measurement(bprm->file, 281 - (strcmp(bprm->filename, bprm->interp) == 0) ? 282 - bprm->filename : bprm->interp, 283 - MAY_EXEC, BPRM_CHECK); 247 + (strcmp(bprm->filename, bprm->interp) == 0) ? 248 + bprm->filename : bprm->interp, 249 + MAY_EXEC, BPRM_CHECK); 284 250 } 285 251 286 252 /** ··· 297 263 { 298 264 ima_rdwr_violation_check(file); 299 265 return process_measurement(file, NULL, 300 - mask & (MAY_READ | MAY_WRITE | MAY_EXEC), 301 - FILE_CHECK); 266 + mask & (MAY_READ | MAY_WRITE | MAY_EXEC), 267 + FILE_CHECK); 302 268 } 303 269 EXPORT_SYMBOL_GPL(ima_file_check); 304 270 ··· 328 294 { 329 295 int error; 330 296 297 + hash_setup(CONFIG_IMA_DEFAULT_HASH); 331 298 error = ima_init(); 332 299 if (!error) 333 300 ima_initialized = 1;
-1
security/integrity/ima/ima_policy.c
··· 73 73 {.action = DONT_MEASURE,.fsmagic = SYSFS_MAGIC,.flags = IMA_FSMAGIC}, 74 74 {.action = DONT_MEASURE,.fsmagic = DEBUGFS_MAGIC,.flags = IMA_FSMAGIC}, 75 75 {.action = DONT_MEASURE,.fsmagic = TMPFS_MAGIC,.flags = IMA_FSMAGIC}, 76 - {.action = DONT_MEASURE,.fsmagic = RAMFS_MAGIC,.flags = IMA_FSMAGIC}, 77 76 {.action = DONT_MEASURE,.fsmagic = DEVPTS_SUPER_MAGIC,.flags = IMA_FSMAGIC}, 78 77 {.action = DONT_MEASURE,.fsmagic = BINFMTFS_MAGIC,.flags = IMA_FSMAGIC}, 79 78 {.action = DONT_MEASURE,.fsmagic = SECURITYFS_MAGIC,.flags = IMA_FSMAGIC},
+5 -5
security/integrity/ima/ima_queue.c
··· 50 50 key = ima_hash_key(digest_value); 51 51 rcu_read_lock(); 52 52 hlist_for_each_entry_rcu(qe, &ima_htable.queue[key], hnext) { 53 - rc = memcmp(qe->entry->digest, digest_value, IMA_DIGEST_SIZE); 53 + rc = memcmp(qe->entry->digest, digest_value, TPM_DIGEST_SIZE); 54 54 if (rc == 0) { 55 55 ret = qe; 56 56 break; ··· 104 104 * and extend the pcr. 105 105 */ 106 106 int ima_add_template_entry(struct ima_template_entry *entry, int violation, 107 - const char *op, struct inode *inode) 107 + const char *op, struct inode *inode, 108 + const unsigned char *filename) 108 109 { 109 - u8 digest[IMA_DIGEST_SIZE]; 110 + u8 digest[TPM_DIGEST_SIZE]; 110 111 const char *audit_cause = "hash_added"; 111 112 char tpm_audit_cause[AUDIT_CAUSE_LEN_MAX]; 112 113 int audit_info = 1; ··· 142 141 } 143 142 out: 144 143 mutex_unlock(&ima_extend_list_mutex); 145 - integrity_audit_msg(AUDIT_INTEGRITY_PCR, inode, 146 - entry->template.file_name, 144 + integrity_audit_msg(AUDIT_INTEGRITY_PCR, inode, filename, 147 145 op, audit_cause, result, audit_info); 148 146 return result; 149 147 }
+178
security/integrity/ima/ima_template.c
··· 1 + /* 2 + * Copyright (C) 2013 Politecnico di Torino, Italy 3 + * TORSEC group -- http://security.polito.it 4 + * 5 + * Author: Roberto Sassu <roberto.sassu@polito.it> 6 + * 7 + * This program is free software; you can redistribute it and/or 8 + * modify it under the terms of the GNU General Public License as 9 + * published by the Free Software Foundation, version 2 of the 10 + * License. 11 + * 12 + * File: ima_template.c 13 + * Helpers to manage template descriptors. 14 + */ 15 + #include <crypto/hash_info.h> 16 + 17 + #include "ima.h" 18 + #include "ima_template_lib.h" 19 + 20 + static struct ima_template_desc defined_templates[] = { 21 + {.name = IMA_TEMPLATE_IMA_NAME, .fmt = IMA_TEMPLATE_IMA_FMT}, 22 + {.name = "ima-ng",.fmt = "d-ng|n-ng"}, 23 + {.name = "ima-sig",.fmt = "d-ng|n-ng|sig"}, 24 + }; 25 + 26 + static struct ima_template_field supported_fields[] = { 27 + {.field_id = "d",.field_init = ima_eventdigest_init, 28 + .field_show = ima_show_template_digest}, 29 + {.field_id = "n",.field_init = ima_eventname_init, 30 + .field_show = ima_show_template_string}, 31 + {.field_id = "d-ng",.field_init = ima_eventdigest_ng_init, 32 + .field_show = ima_show_template_digest_ng}, 33 + {.field_id = "n-ng",.field_init = ima_eventname_ng_init, 34 + .field_show = ima_show_template_string}, 35 + {.field_id = "sig",.field_init = ima_eventsig_init, 36 + .field_show = ima_show_template_sig}, 37 + }; 38 + 39 + static struct ima_template_desc *ima_template; 40 + static struct ima_template_desc *lookup_template_desc(const char *name); 41 + 42 + static int __init ima_template_setup(char *str) 43 + { 44 + struct ima_template_desc *template_desc; 45 + int template_len = strlen(str); 46 + 47 + /* 48 + * Verify that a template with the supplied name exists. 49 + * If not, use CONFIG_IMA_DEFAULT_TEMPLATE. 50 + */ 51 + template_desc = lookup_template_desc(str); 52 + if (!template_desc) 53 + return 1; 54 + 55 + /* 56 + * Verify whether the current hash algorithm is supported 57 + * by the 'ima' template. 58 + */ 59 + if (template_len == 3 && strcmp(str, IMA_TEMPLATE_IMA_NAME) == 0 && 60 + ima_hash_algo != HASH_ALGO_SHA1 && ima_hash_algo != HASH_ALGO_MD5) { 61 + pr_err("IMA: template does not support hash alg\n"); 62 + return 1; 63 + } 64 + 65 + ima_template = template_desc; 66 + return 1; 67 + } 68 + __setup("ima_template=", ima_template_setup); 69 + 70 + static struct ima_template_desc *lookup_template_desc(const char *name) 71 + { 72 + int i; 73 + 74 + for (i = 0; i < ARRAY_SIZE(defined_templates); i++) { 75 + if (strcmp(defined_templates[i].name, name) == 0) 76 + return defined_templates + i; 77 + } 78 + 79 + return NULL; 80 + } 81 + 82 + static struct ima_template_field *lookup_template_field(const char *field_id) 83 + { 84 + int i; 85 + 86 + for (i = 0; i < ARRAY_SIZE(supported_fields); i++) 87 + if (strncmp(supported_fields[i].field_id, field_id, 88 + IMA_TEMPLATE_FIELD_ID_MAX_LEN) == 0) 89 + return &supported_fields[i]; 90 + return NULL; 91 + } 92 + 93 + static int template_fmt_size(char *template_fmt) 94 + { 95 + char c; 96 + int template_fmt_len = strlen(template_fmt); 97 + int i = 0, j = 0; 98 + 99 + while (i < template_fmt_len) { 100 + c = template_fmt[i]; 101 + if (c == '|') 102 + j++; 103 + i++; 104 + } 105 + 106 + return j + 1; 107 + } 108 + 109 + static int template_desc_init_fields(char *template_fmt, 110 + struct ima_template_field ***fields, 111 + int *num_fields) 112 + { 113 + char *c, *template_fmt_ptr = template_fmt; 114 + int template_num_fields = template_fmt_size(template_fmt); 115 + int i, result = 0; 116 + 117 + if (template_num_fields > IMA_TEMPLATE_NUM_FIELDS_MAX) 118 + return -EINVAL; 119 + 120 + *fields = kzalloc(template_num_fields * sizeof(*fields), GFP_KERNEL); 121 + if (*fields == NULL) { 122 + result = -ENOMEM; 123 + goto out; 124 + } 125 + for (i = 0; (c = strsep(&template_fmt_ptr, "|")) != NULL && 126 + i < template_num_fields; i++) { 127 + struct ima_template_field *f = lookup_template_field(c); 128 + 129 + if (!f) { 130 + result = -ENOENT; 131 + goto out; 132 + } 133 + (*fields)[i] = f; 134 + } 135 + *num_fields = i; 136 + return 0; 137 + out: 138 + kfree(*fields); 139 + *fields = NULL; 140 + return result; 141 + } 142 + 143 + static int init_defined_templates(void) 144 + { 145 + int i = 0; 146 + int result = 0; 147 + 148 + /* Init defined templates. */ 149 + for (i = 0; i < ARRAY_SIZE(defined_templates); i++) { 150 + struct ima_template_desc *template = &defined_templates[i]; 151 + 152 + result = template_desc_init_fields(template->fmt, 153 + &(template->fields), 154 + &(template->num_fields)); 155 + if (result < 0) 156 + return result; 157 + } 158 + return result; 159 + } 160 + 161 + struct ima_template_desc *ima_template_desc_current(void) 162 + { 163 + if (!ima_template) 164 + ima_template = 165 + lookup_template_desc(CONFIG_IMA_DEFAULT_TEMPLATE); 166 + return ima_template; 167 + } 168 + 169 + int ima_init_template(void) 170 + { 171 + int result; 172 + 173 + result = init_defined_templates(); 174 + if (result < 0) 175 + return result; 176 + 177 + return 0; 178 + }
+347
security/integrity/ima/ima_template_lib.c
··· 1 + /* 2 + * Copyright (C) 2013 Politecnico di Torino, Italy 3 + * TORSEC group -- http://security.polito.it 4 + * 5 + * Author: Roberto Sassu <roberto.sassu@polito.it> 6 + * 7 + * This program is free software; you can redistribute it and/or 8 + * modify it under the terms of the GNU General Public License as 9 + * published by the Free Software Foundation, version 2 of the 10 + * License. 11 + * 12 + * File: ima_template_lib.c 13 + * Library of supported template fields. 14 + */ 15 + #include <crypto/hash_info.h> 16 + 17 + #include "ima_template_lib.h" 18 + 19 + static bool ima_template_hash_algo_allowed(u8 algo) 20 + { 21 + if (algo == HASH_ALGO_SHA1 || algo == HASH_ALGO_MD5) 22 + return true; 23 + 24 + return false; 25 + } 26 + 27 + enum data_formats { 28 + DATA_FMT_DIGEST = 0, 29 + DATA_FMT_DIGEST_WITH_ALGO, 30 + DATA_FMT_EVENT_NAME, 31 + DATA_FMT_STRING, 32 + DATA_FMT_HEX 33 + }; 34 + 35 + static int ima_write_template_field_data(const void *data, const u32 datalen, 36 + enum data_formats datafmt, 37 + struct ima_field_data *field_data) 38 + { 39 + u8 *buf, *buf_ptr; 40 + u32 buflen; 41 + 42 + switch (datafmt) { 43 + case DATA_FMT_EVENT_NAME: 44 + buflen = IMA_EVENT_NAME_LEN_MAX + 1; 45 + break; 46 + case DATA_FMT_STRING: 47 + buflen = datalen + 1; 48 + break; 49 + default: 50 + buflen = datalen; 51 + } 52 + 53 + buf = kzalloc(buflen, GFP_KERNEL); 54 + if (!buf) 55 + return -ENOMEM; 56 + 57 + memcpy(buf, data, datalen); 58 + 59 + /* 60 + * Replace all space characters with underscore for event names and 61 + * strings. This avoid that, during the parsing of a measurements list, 62 + * filenames with spaces or that end with the suffix ' (deleted)' are 63 + * split into multiple template fields (the space is the delimitator 64 + * character for measurements lists in ASCII format). 65 + */ 66 + if (datafmt == DATA_FMT_EVENT_NAME || datafmt == DATA_FMT_STRING) { 67 + for (buf_ptr = buf; buf_ptr - buf < datalen; buf_ptr++) 68 + if (*buf_ptr == ' ') 69 + *buf_ptr = '_'; 70 + } 71 + 72 + field_data->data = buf; 73 + field_data->len = buflen; 74 + return 0; 75 + } 76 + 77 + static void ima_show_template_data_ascii(struct seq_file *m, 78 + enum ima_show_type show, 79 + enum data_formats datafmt, 80 + struct ima_field_data *field_data) 81 + { 82 + u8 *buf_ptr = field_data->data, buflen = field_data->len; 83 + 84 + switch (datafmt) { 85 + case DATA_FMT_DIGEST_WITH_ALGO: 86 + buf_ptr = strnchr(field_data->data, buflen, ':'); 87 + if (buf_ptr != field_data->data) 88 + seq_printf(m, "%s", field_data->data); 89 + 90 + /* skip ':' and '\0' */ 91 + buf_ptr += 2; 92 + buflen -= buf_ptr - field_data->data; 93 + case DATA_FMT_DIGEST: 94 + case DATA_FMT_HEX: 95 + if (!buflen) 96 + break; 97 + ima_print_digest(m, buf_ptr, buflen); 98 + break; 99 + case DATA_FMT_STRING: 100 + seq_printf(m, "%s", buf_ptr); 101 + break; 102 + default: 103 + break; 104 + } 105 + } 106 + 107 + static void ima_show_template_data_binary(struct seq_file *m, 108 + enum ima_show_type show, 109 + enum data_formats datafmt, 110 + struct ima_field_data *field_data) 111 + { 112 + ima_putc(m, &field_data->len, sizeof(u32)); 113 + if (!field_data->len) 114 + return; 115 + ima_putc(m, field_data->data, field_data->len); 116 + } 117 + 118 + static void ima_show_template_field_data(struct seq_file *m, 119 + enum ima_show_type show, 120 + enum data_formats datafmt, 121 + struct ima_field_data *field_data) 122 + { 123 + switch (show) { 124 + case IMA_SHOW_ASCII: 125 + ima_show_template_data_ascii(m, show, datafmt, field_data); 126 + break; 127 + case IMA_SHOW_BINARY: 128 + ima_show_template_data_binary(m, show, datafmt, field_data); 129 + break; 130 + default: 131 + break; 132 + } 133 + } 134 + 135 + void ima_show_template_digest(struct seq_file *m, enum ima_show_type show, 136 + struct ima_field_data *field_data) 137 + { 138 + ima_show_template_field_data(m, show, DATA_FMT_DIGEST, field_data); 139 + } 140 + 141 + void ima_show_template_digest_ng(struct seq_file *m, enum ima_show_type show, 142 + struct ima_field_data *field_data) 143 + { 144 + ima_show_template_field_data(m, show, DATA_FMT_DIGEST_WITH_ALGO, 145 + field_data); 146 + } 147 + 148 + void ima_show_template_string(struct seq_file *m, enum ima_show_type show, 149 + struct ima_field_data *field_data) 150 + { 151 + ima_show_template_field_data(m, show, DATA_FMT_STRING, field_data); 152 + } 153 + 154 + void ima_show_template_sig(struct seq_file *m, enum ima_show_type show, 155 + struct ima_field_data *field_data) 156 + { 157 + ima_show_template_field_data(m, show, DATA_FMT_HEX, field_data); 158 + } 159 + 160 + static int ima_eventdigest_init_common(u8 *digest, u32 digestsize, u8 hash_algo, 161 + struct ima_field_data *field_data, 162 + bool size_limit) 163 + { 164 + /* 165 + * digest formats: 166 + * - DATA_FMT_DIGEST: digest 167 + * - DATA_FMT_DIGEST_WITH_ALGO: [<hash algo>] + ':' + '\0' + digest, 168 + * where <hash algo> is provided if the hash algoritm is not 169 + * SHA1 or MD5 170 + */ 171 + u8 buffer[CRYPTO_MAX_ALG_NAME + 2 + IMA_MAX_DIGEST_SIZE] = { 0 }; 172 + enum data_formats fmt = DATA_FMT_DIGEST; 173 + u32 offset = 0; 174 + 175 + if (!size_limit) { 176 + fmt = DATA_FMT_DIGEST_WITH_ALGO; 177 + if (hash_algo < HASH_ALGO__LAST) 178 + offset += snprintf(buffer, CRYPTO_MAX_ALG_NAME + 1, 179 + "%s", hash_algo_name[hash_algo]); 180 + buffer[offset] = ':'; 181 + offset += 2; 182 + } 183 + 184 + if (digest) 185 + memcpy(buffer + offset, digest, digestsize); 186 + else 187 + /* 188 + * If digest is NULL, the event being recorded is a violation. 189 + * Make room for the digest by increasing the offset of 190 + * IMA_DIGEST_SIZE. 191 + */ 192 + offset += IMA_DIGEST_SIZE; 193 + 194 + return ima_write_template_field_data(buffer, offset + digestsize, 195 + fmt, field_data); 196 + } 197 + 198 + /* 199 + * This function writes the digest of an event (with size limit). 200 + */ 201 + int ima_eventdigest_init(struct integrity_iint_cache *iint, struct file *file, 202 + const unsigned char *filename, 203 + struct evm_ima_xattr_data *xattr_value, int xattr_len, 204 + struct ima_field_data *field_data) 205 + { 206 + struct { 207 + struct ima_digest_data hdr; 208 + char digest[IMA_MAX_DIGEST_SIZE]; 209 + } hash; 210 + u8 *cur_digest = NULL; 211 + u32 cur_digestsize = 0; 212 + struct inode *inode; 213 + int result; 214 + 215 + memset(&hash, 0, sizeof(hash)); 216 + 217 + if (!iint) /* recording a violation. */ 218 + goto out; 219 + 220 + if (ima_template_hash_algo_allowed(iint->ima_hash->algo)) { 221 + cur_digest = iint->ima_hash->digest; 222 + cur_digestsize = iint->ima_hash->length; 223 + goto out; 224 + } 225 + 226 + if (!file) /* missing info to re-calculate the digest */ 227 + return -EINVAL; 228 + 229 + inode = file_inode(file); 230 + hash.hdr.algo = ima_template_hash_algo_allowed(ima_hash_algo) ? 231 + ima_hash_algo : HASH_ALGO_SHA1; 232 + result = ima_calc_file_hash(file, &hash.hdr); 233 + if (result) { 234 + integrity_audit_msg(AUDIT_INTEGRITY_DATA, inode, 235 + filename, "collect_data", 236 + "failed", result, 0); 237 + return result; 238 + } 239 + cur_digest = hash.hdr.digest; 240 + cur_digestsize = hash.hdr.length; 241 + out: 242 + return ima_eventdigest_init_common(cur_digest, cur_digestsize, -1, 243 + field_data, true); 244 + } 245 + 246 + /* 247 + * This function writes the digest of an event (without size limit). 248 + */ 249 + int ima_eventdigest_ng_init(struct integrity_iint_cache *iint, 250 + struct file *file, const unsigned char *filename, 251 + struct evm_ima_xattr_data *xattr_value, 252 + int xattr_len, struct ima_field_data *field_data) 253 + { 254 + u8 *cur_digest = NULL, hash_algo = HASH_ALGO__LAST; 255 + u32 cur_digestsize = 0; 256 + 257 + /* If iint is NULL, we are recording a violation. */ 258 + if (!iint) 259 + goto out; 260 + 261 + cur_digest = iint->ima_hash->digest; 262 + cur_digestsize = iint->ima_hash->length; 263 + 264 + hash_algo = iint->ima_hash->algo; 265 + out: 266 + return ima_eventdigest_init_common(cur_digest, cur_digestsize, 267 + hash_algo, field_data, false); 268 + } 269 + 270 + static int ima_eventname_init_common(struct integrity_iint_cache *iint, 271 + struct file *file, 272 + const unsigned char *filename, 273 + struct ima_field_data *field_data, 274 + bool size_limit) 275 + { 276 + const char *cur_filename = NULL; 277 + u32 cur_filename_len = 0; 278 + enum data_formats fmt = size_limit ? 279 + DATA_FMT_EVENT_NAME : DATA_FMT_STRING; 280 + 281 + BUG_ON(filename == NULL && file == NULL); 282 + 283 + if (filename) { 284 + cur_filename = filename; 285 + cur_filename_len = strlen(filename); 286 + 287 + if (!size_limit || cur_filename_len <= IMA_EVENT_NAME_LEN_MAX) 288 + goto out; 289 + } 290 + 291 + if (file) { 292 + cur_filename = file->f_dentry->d_name.name; 293 + cur_filename_len = strlen(cur_filename); 294 + } else 295 + /* 296 + * Truncate filename if the latter is too long and 297 + * the file descriptor is not available. 298 + */ 299 + cur_filename_len = IMA_EVENT_NAME_LEN_MAX; 300 + out: 301 + return ima_write_template_field_data(cur_filename, cur_filename_len, 302 + fmt, field_data); 303 + } 304 + 305 + /* 306 + * This function writes the name of an event (with size limit). 307 + */ 308 + int ima_eventname_init(struct integrity_iint_cache *iint, struct file *file, 309 + const unsigned char *filename, 310 + struct evm_ima_xattr_data *xattr_value, int xattr_len, 311 + struct ima_field_data *field_data) 312 + { 313 + return ima_eventname_init_common(iint, file, filename, 314 + field_data, true); 315 + } 316 + 317 + /* 318 + * This function writes the name of an event (without size limit). 319 + */ 320 + int ima_eventname_ng_init(struct integrity_iint_cache *iint, struct file *file, 321 + const unsigned char *filename, 322 + struct evm_ima_xattr_data *xattr_value, int xattr_len, 323 + struct ima_field_data *field_data) 324 + { 325 + return ima_eventname_init_common(iint, file, filename, 326 + field_data, false); 327 + } 328 + 329 + /* 330 + * ima_eventsig_init - include the file signature as part of the template data 331 + */ 332 + int ima_eventsig_init(struct integrity_iint_cache *iint, struct file *file, 333 + const unsigned char *filename, 334 + struct evm_ima_xattr_data *xattr_value, int xattr_len, 335 + struct ima_field_data *field_data) 336 + { 337 + enum data_formats fmt = DATA_FMT_HEX; 338 + int rc = 0; 339 + 340 + if ((!xattr_value) || (xattr_value->type != EVM_IMA_XATTR_DIGSIG)) 341 + goto out; 342 + 343 + rc = ima_write_template_field_data(xattr_value, xattr_len, fmt, 344 + field_data); 345 + out: 346 + return rc; 347 + }
+49
security/integrity/ima/ima_template_lib.h
··· 1 + /* 2 + * Copyright (C) 2013 Politecnico di Torino, Italy 3 + * TORSEC group -- http://security.polito.it 4 + * 5 + * Author: Roberto Sassu <roberto.sassu@polito.it> 6 + * 7 + * This program is free software; you can redistribute it and/or 8 + * modify it under the terms of the GNU General Public License as 9 + * published by the Free Software Foundation, version 2 of the 10 + * License. 11 + * 12 + * File: ima_template_lib.h 13 + * Header for the library of supported template fields. 14 + */ 15 + #ifndef __LINUX_IMA_TEMPLATE_LIB_H 16 + #define __LINUX_IMA_TEMPLATE_LIB_H 17 + 18 + #include <linux/seq_file.h> 19 + #include "ima.h" 20 + 21 + void ima_show_template_digest(struct seq_file *m, enum ima_show_type show, 22 + struct ima_field_data *field_data); 23 + void ima_show_template_digest_ng(struct seq_file *m, enum ima_show_type show, 24 + struct ima_field_data *field_data); 25 + void ima_show_template_string(struct seq_file *m, enum ima_show_type show, 26 + struct ima_field_data *field_data); 27 + void ima_show_template_sig(struct seq_file *m, enum ima_show_type show, 28 + struct ima_field_data *field_data); 29 + int ima_eventdigest_init(struct integrity_iint_cache *iint, struct file *file, 30 + const unsigned char *filename, 31 + struct evm_ima_xattr_data *xattr_value, int xattr_len, 32 + struct ima_field_data *field_data); 33 + int ima_eventname_init(struct integrity_iint_cache *iint, struct file *file, 34 + const unsigned char *filename, 35 + struct evm_ima_xattr_data *xattr_value, int xattr_len, 36 + struct ima_field_data *field_data); 37 + int ima_eventdigest_ng_init(struct integrity_iint_cache *iint, 38 + struct file *file, const unsigned char *filename, 39 + struct evm_ima_xattr_data *xattr_value, 40 + int xattr_len, struct ima_field_data *field_data); 41 + int ima_eventname_ng_init(struct integrity_iint_cache *iint, struct file *file, 42 + const unsigned char *filename, 43 + struct evm_ima_xattr_data *xattr_value, int xattr_len, 44 + struct ima_field_data *field_data); 45 + int ima_eventsig_init(struct integrity_iint_cache *iint, struct file *file, 46 + const unsigned char *filename, 47 + struct evm_ima_xattr_data *xattr_value, int xattr_len, 48 + struct ima_field_data *field_data); 49 + #endif /* __LINUX_IMA_TEMPLATE_LIB_H */
+43 -4
security/integrity/integrity.h
··· 54 54 IMA_XATTR_DIGEST = 0x01, 55 55 EVM_XATTR_HMAC, 56 56 EVM_IMA_XATTR_DIGSIG, 57 + IMA_XATTR_DIGEST_NG, 57 58 }; 58 59 59 60 struct evm_ima_xattr_data { 60 61 u8 type; 61 62 u8 digest[SHA1_DIGEST_SIZE]; 62 - } __attribute__((packed)); 63 + } __packed; 64 + 65 + #define IMA_MAX_DIGEST_SIZE 64 66 + 67 + struct ima_digest_data { 68 + u8 algo; 69 + u8 length; 70 + union { 71 + struct { 72 + u8 unused; 73 + u8 type; 74 + } sha1; 75 + struct { 76 + u8 type; 77 + u8 algo; 78 + } ng; 79 + u8 data[2]; 80 + } xattr; 81 + u8 digest[0]; 82 + } __packed; 83 + 84 + /* 85 + * signature format v2 - for using with asymmetric keys 86 + */ 87 + struct signature_v2_hdr { 88 + uint8_t type; /* xattr type */ 89 + uint8_t version; /* signature format version */ 90 + uint8_t hash_algo; /* Digest algorithm [enum pkey_hash_algo] */ 91 + uint32_t keyid; /* IMA key identifier - not X509/PGP specific */ 92 + uint16_t sig_size; /* signature size */ 93 + uint8_t sig[0]; /* signature payload */ 94 + } __packed; 63 95 64 96 /* integrity data associated with an inode */ 65 97 struct integrity_iint_cache { 66 - struct rb_node rb_node; /* rooted in integrity_iint_tree */ 98 + struct rb_node rb_node; /* rooted in integrity_iint_tree */ 67 99 struct inode *inode; /* back pointer to inode in question */ 68 100 u64 version; /* track inode changes */ 69 101 unsigned long flags; 70 - struct evm_ima_xattr_data ima_xattr; 71 102 enum integrity_status ima_file_status:4; 72 103 enum integrity_status ima_mmap_status:4; 73 104 enum integrity_status ima_bprm_status:4; 74 105 enum integrity_status ima_module_status:4; 75 106 enum integrity_status evm_status:4; 107 + struct ima_digest_data *ima_hash; 76 108 }; 77 109 78 110 /* rbtree tree calls to lookup, insert, delete ··· 121 89 #ifdef CONFIG_INTEGRITY_SIGNATURE 122 90 123 91 int integrity_digsig_verify(const unsigned int id, const char *sig, int siglen, 124 - const char *digest, int digestlen); 92 + const char *digest, int digestlen); 125 93 126 94 #else 127 95 ··· 137 105 #ifdef CONFIG_INTEGRITY_ASYMMETRIC_KEYS 138 106 int asymmetric_verify(struct key *keyring, const char *sig, 139 107 int siglen, const char *data, int datalen); 108 + 109 + int integrity_init_keyring(const unsigned int id); 140 110 #else 141 111 static inline int asymmetric_verify(struct key *keyring, const char *sig, 142 112 int siglen, const char *data, int datalen) 143 113 { 144 114 return -EOPNOTSUPP; 115 + } 116 + 117 + static int integrity_init_keyring(const unsigned int id) 118 + { 119 + return 0; 145 120 } 146 121 #endif 147 122
+29
security/keys/Kconfig
··· 4 4 5 5 config KEYS 6 6 bool "Enable access key retention support" 7 + select ASSOCIATIVE_ARRAY 7 8 help 8 9 This option provides support for retaining authentication tokens and 9 10 access keys in the kernel. ··· 17 16 a searchable sequence of keys. Each process is equipped with access 18 17 to five standard keyrings: UID-specific, GID-specific, session, 19 18 process and thread. 19 + 20 + If you are unsure as to whether this is required, answer N. 21 + 22 + config PERSISTENT_KEYRINGS 23 + bool "Enable register of persistent per-UID keyrings" 24 + depends on KEYS 25 + help 26 + This option provides a register of persistent per-UID keyrings, 27 + primarily aimed at Kerberos key storage. The keyrings are persistent 28 + in the sense that they stay around after all processes of that UID 29 + have exited, not that they survive the machine being rebooted. 30 + 31 + A particular keyring may be accessed by either the user whose keyring 32 + it is or by a process with administrative privileges. The active 33 + LSMs gets to rule on which admin-level processes get to access the 34 + cache. 35 + 36 + Keyrings are created and added into the register upon demand and get 37 + removed if they expire (a default timeout is set upon creation). 38 + 39 + config BIG_KEYS 40 + bool "Large payload keys" 41 + depends on KEYS 42 + depends on TMPFS 43 + help 44 + This option provides support for holding large keys within the kernel 45 + (for example Kerberos ticket caches). The data may be stored out to 46 + swapspace by tmpfs. 20 47 21 48 If you are unsure as to whether this is required, answer N. 22 49
+2
security/keys/Makefile
··· 18 18 obj-$(CONFIG_KEYS_COMPAT) += compat.o 19 19 obj-$(CONFIG_PROC_FS) += proc.o 20 20 obj-$(CONFIG_SYSCTL) += sysctl.o 21 + obj-$(CONFIG_PERSISTENT_KEYRINGS) += persistent.o 21 22 22 23 # 23 24 # Key types 24 25 # 26 + obj-$(CONFIG_BIG_KEYS) += big_key.o 25 27 obj-$(CONFIG_TRUSTED_KEYS) += trusted.o 26 28 obj-$(CONFIG_ENCRYPTED_KEYS) += encrypted-keys/
+207
security/keys/big_key.c
··· 1 + /* Large capacity key type 2 + * 3 + * Copyright (C) 2013 Red Hat, Inc. All Rights Reserved. 4 + * Written by David Howells (dhowells@redhat.com) 5 + * 6 + * This program is free software; you can redistribute it and/or 7 + * modify it under the terms of the GNU General Public Licence 8 + * as published by the Free Software Foundation; either version 9 + * 2 of the Licence, or (at your option) any later version. 10 + */ 11 + 12 + #include <linux/module.h> 13 + #include <linux/init.h> 14 + #include <linux/seq_file.h> 15 + #include <linux/file.h> 16 + #include <linux/shmem_fs.h> 17 + #include <linux/err.h> 18 + #include <keys/user-type.h> 19 + #include <keys/big_key-type.h> 20 + 21 + MODULE_LICENSE("GPL"); 22 + 23 + /* 24 + * If the data is under this limit, there's no point creating a shm file to 25 + * hold it as the permanently resident metadata for the shmem fs will be at 26 + * least as large as the data. 27 + */ 28 + #define BIG_KEY_FILE_THRESHOLD (sizeof(struct inode) + sizeof(struct dentry)) 29 + 30 + /* 31 + * big_key defined keys take an arbitrary string as the description and an 32 + * arbitrary blob of data as the payload 33 + */ 34 + struct key_type key_type_big_key = { 35 + .name = "big_key", 36 + .def_lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT, 37 + .instantiate = big_key_instantiate, 38 + .match = user_match, 39 + .revoke = big_key_revoke, 40 + .destroy = big_key_destroy, 41 + .describe = big_key_describe, 42 + .read = big_key_read, 43 + }; 44 + 45 + /* 46 + * Instantiate a big key 47 + */ 48 + int big_key_instantiate(struct key *key, struct key_preparsed_payload *prep) 49 + { 50 + struct path *path = (struct path *)&key->payload.data2; 51 + struct file *file; 52 + ssize_t written; 53 + size_t datalen = prep->datalen; 54 + int ret; 55 + 56 + ret = -EINVAL; 57 + if (datalen <= 0 || datalen > 1024 * 1024 || !prep->data) 58 + goto error; 59 + 60 + /* Set an arbitrary quota */ 61 + ret = key_payload_reserve(key, 16); 62 + if (ret < 0) 63 + goto error; 64 + 65 + key->type_data.x[1] = datalen; 66 + 67 + if (datalen > BIG_KEY_FILE_THRESHOLD) { 68 + /* Create a shmem file to store the data in. This will permit the data 69 + * to be swapped out if needed. 70 + * 71 + * TODO: Encrypt the stored data with a temporary key. 72 + */ 73 + file = shmem_file_setup("", datalen, 0); 74 + if (IS_ERR(file)) { 75 + ret = PTR_ERR(file); 76 + goto err_quota; 77 + } 78 + 79 + written = kernel_write(file, prep->data, prep->datalen, 0); 80 + if (written != datalen) { 81 + ret = written; 82 + if (written >= 0) 83 + ret = -ENOMEM; 84 + goto err_fput; 85 + } 86 + 87 + /* Pin the mount and dentry to the key so that we can open it again 88 + * later 89 + */ 90 + *path = file->f_path; 91 + path_get(path); 92 + fput(file); 93 + } else { 94 + /* Just store the data in a buffer */ 95 + void *data = kmalloc(datalen, GFP_KERNEL); 96 + if (!data) { 97 + ret = -ENOMEM; 98 + goto err_quota; 99 + } 100 + 101 + key->payload.data = memcpy(data, prep->data, prep->datalen); 102 + } 103 + return 0; 104 + 105 + err_fput: 106 + fput(file); 107 + err_quota: 108 + key_payload_reserve(key, 0); 109 + error: 110 + return ret; 111 + } 112 + 113 + /* 114 + * dispose of the links from a revoked keyring 115 + * - called with the key sem write-locked 116 + */ 117 + void big_key_revoke(struct key *key) 118 + { 119 + struct path *path = (struct path *)&key->payload.data2; 120 + 121 + /* clear the quota */ 122 + key_payload_reserve(key, 0); 123 + if (key_is_instantiated(key) && key->type_data.x[1] > BIG_KEY_FILE_THRESHOLD) 124 + vfs_truncate(path, 0); 125 + } 126 + 127 + /* 128 + * dispose of the data dangling from the corpse of a big_key key 129 + */ 130 + void big_key_destroy(struct key *key) 131 + { 132 + if (key->type_data.x[1] > BIG_KEY_FILE_THRESHOLD) { 133 + struct path *path = (struct path *)&key->payload.data2; 134 + path_put(path); 135 + path->mnt = NULL; 136 + path->dentry = NULL; 137 + } else { 138 + kfree(key->payload.data); 139 + key->payload.data = NULL; 140 + } 141 + } 142 + 143 + /* 144 + * describe the big_key key 145 + */ 146 + void big_key_describe(const struct key *key, struct seq_file *m) 147 + { 148 + unsigned long datalen = key->type_data.x[1]; 149 + 150 + seq_puts(m, key->description); 151 + 152 + if (key_is_instantiated(key)) 153 + seq_printf(m, ": %lu [%s]", 154 + datalen, 155 + datalen > BIG_KEY_FILE_THRESHOLD ? "file" : "buff"); 156 + } 157 + 158 + /* 159 + * read the key data 160 + * - the key's semaphore is read-locked 161 + */ 162 + long big_key_read(const struct key *key, char __user *buffer, size_t buflen) 163 + { 164 + unsigned long datalen = key->type_data.x[1]; 165 + long ret; 166 + 167 + if (!buffer || buflen < datalen) 168 + return datalen; 169 + 170 + if (datalen > BIG_KEY_FILE_THRESHOLD) { 171 + struct path *path = (struct path *)&key->payload.data2; 172 + struct file *file; 173 + loff_t pos; 174 + 175 + file = dentry_open(path, O_RDONLY, current_cred()); 176 + if (IS_ERR(file)) 177 + return PTR_ERR(file); 178 + 179 + pos = 0; 180 + ret = vfs_read(file, buffer, datalen, &pos); 181 + fput(file); 182 + if (ret >= 0 && ret != datalen) 183 + ret = -EIO; 184 + } else { 185 + ret = datalen; 186 + if (copy_to_user(buffer, key->payload.data, datalen) != 0) 187 + ret = -EFAULT; 188 + } 189 + 190 + return ret; 191 + } 192 + 193 + /* 194 + * Module stuff 195 + */ 196 + static int __init big_key_init(void) 197 + { 198 + return register_key_type(&key_type_big_key); 199 + } 200 + 201 + static void __exit big_key_cleanup(void) 202 + { 203 + unregister_key_type(&key_type_big_key); 204 + } 205 + 206 + module_init(big_key_init); 207 + module_exit(big_key_cleanup);
+3
security/keys/compat.c
··· 138 138 case KEYCTL_INVALIDATE: 139 139 return keyctl_invalidate_key(arg2); 140 140 141 + case KEYCTL_GET_PERSISTENT: 142 + return keyctl_get_persistent(arg2, arg3); 143 + 141 144 default: 142 145 return -EOPNOTSUPP; 143 146 }
+1 -46
security/keys/gc.c
··· 131 131 } 132 132 133 133 /* 134 - * Garbage collect pointers from a keyring. 135 - * 136 - * Not called with any locks held. The keyring's key struct will not be 137 - * deallocated under us as only our caller may deallocate it. 138 - */ 139 - static void key_gc_keyring(struct key *keyring, time_t limit) 140 - { 141 - struct keyring_list *klist; 142 - int loop; 143 - 144 - kenter("%x", key_serial(keyring)); 145 - 146 - if (keyring->flags & ((1 << KEY_FLAG_INVALIDATED) | 147 - (1 << KEY_FLAG_REVOKED))) 148 - goto dont_gc; 149 - 150 - /* scan the keyring looking for dead keys */ 151 - rcu_read_lock(); 152 - klist = rcu_dereference(keyring->payload.subscriptions); 153 - if (!klist) 154 - goto unlock_dont_gc; 155 - 156 - loop = klist->nkeys; 157 - smp_rmb(); 158 - for (loop--; loop >= 0; loop--) { 159 - struct key *key = rcu_dereference(klist->keys[loop]); 160 - if (key_is_dead(key, limit)) 161 - goto do_gc; 162 - } 163 - 164 - unlock_dont_gc: 165 - rcu_read_unlock(); 166 - dont_gc: 167 - kleave(" [no gc]"); 168 - return; 169 - 170 - do_gc: 171 - rcu_read_unlock(); 172 - 173 - keyring_gc(keyring, limit); 174 - kleave(" [gc]"); 175 - } 176 - 177 - /* 178 134 * Garbage collect a list of unreferenced, detached keys 179 135 */ 180 136 static noinline void key_gc_unused_keys(struct list_head *keys) ··· 348 392 */ 349 393 found_keyring: 350 394 spin_unlock(&key_serial_lock); 351 - kdebug("scan keyring %d", key->serial); 352 - key_gc_keyring(key, limit); 395 + keyring_gc(key, limit); 353 396 goto maybe_resched; 354 397 355 398 /* We found a dead key that is still referenced. Reset its type and
+47 -27
security/keys/internal.h
··· 89 89 extern void key_type_put(struct key_type *ktype); 90 90 91 91 extern int __key_link_begin(struct key *keyring, 92 - const struct key_type *type, 93 - const char *description, 94 - unsigned long *_prealloc); 92 + const struct keyring_index_key *index_key, 93 + struct assoc_array_edit **_edit); 95 94 extern int __key_link_check_live_key(struct key *keyring, struct key *key); 96 - extern void __key_link(struct key *keyring, struct key *key, 97 - unsigned long *_prealloc); 95 + extern void __key_link(struct key *key, struct assoc_array_edit **_edit); 98 96 extern void __key_link_end(struct key *keyring, 99 - struct key_type *type, 100 - unsigned long prealloc); 97 + const struct keyring_index_key *index_key, 98 + struct assoc_array_edit *edit); 101 99 102 - extern key_ref_t __keyring_search_one(key_ref_t keyring_ref, 103 - const struct key_type *type, 104 - const char *description, 105 - key_perm_t perm); 100 + extern key_ref_t find_key_to_update(key_ref_t keyring_ref, 101 + const struct keyring_index_key *index_key); 106 102 107 103 extern struct key *keyring_search_instkey(struct key *keyring, 108 104 key_serial_t target_id); 109 105 106 + extern int iterate_over_keyring(const struct key *keyring, 107 + int (*func)(const struct key *key, void *data), 108 + void *data); 109 + 110 110 typedef int (*key_match_func_t)(const struct key *, const void *); 111 111 112 - extern key_ref_t keyring_search_aux(key_ref_t keyring_ref, 113 - const struct cred *cred, 114 - struct key_type *type, 115 - const void *description, 116 - key_match_func_t match, 117 - bool no_state_check); 112 + struct keyring_search_context { 113 + struct keyring_index_key index_key; 114 + const struct cred *cred; 115 + key_match_func_t match; 116 + const void *match_data; 117 + unsigned flags; 118 + #define KEYRING_SEARCH_LOOKUP_TYPE 0x0001 /* [as type->def_lookup_type] */ 119 + #define KEYRING_SEARCH_NO_STATE_CHECK 0x0002 /* Skip state checks */ 120 + #define KEYRING_SEARCH_DO_STATE_CHECK 0x0004 /* Override NO_STATE_CHECK */ 121 + #define KEYRING_SEARCH_NO_UPDATE_TIME 0x0008 /* Don't update times */ 122 + #define KEYRING_SEARCH_NO_CHECK_PERM 0x0010 /* Don't check permissions */ 123 + #define KEYRING_SEARCH_DETECT_TOO_DEEP 0x0020 /* Give an error on excessive depth */ 118 124 119 - extern key_ref_t search_my_process_keyrings(struct key_type *type, 120 - const void *description, 121 - key_match_func_t match, 122 - bool no_state_check, 123 - const struct cred *cred); 124 - extern key_ref_t search_process_keyrings(struct key_type *type, 125 - const void *description, 126 - key_match_func_t match, 127 - const struct cred *cred); 125 + int (*iterator)(const void *object, void *iterator_data); 126 + 127 + /* Internal stuff */ 128 + int skipped_ret; 129 + bool possessed; 130 + key_ref_t result; 131 + struct timespec now; 132 + }; 133 + 134 + extern key_ref_t keyring_search_aux(key_ref_t keyring_ref, 135 + struct keyring_search_context *ctx); 136 + 137 + extern key_ref_t search_my_process_keyrings(struct keyring_search_context *ctx); 138 + extern key_ref_t search_process_keyrings(struct keyring_search_context *ctx); 128 139 129 140 extern struct key *find_keyring_by_name(const char *name, bool skip_perm_check); 130 141 ··· 213 202 /* 214 203 * Determine whether a key is dead. 215 204 */ 216 - static inline bool key_is_dead(struct key *key, time_t limit) 205 + static inline bool key_is_dead(const struct key *key, time_t limit) 217 206 { 218 207 return 219 208 key->flags & ((1 << KEY_FLAG_DEAD) | ··· 255 244 extern long keyctl_instantiate_key_common(key_serial_t, 256 245 const struct iovec *, 257 246 unsigned, size_t, key_serial_t); 247 + #ifdef CONFIG_PERSISTENT_KEYRINGS 248 + extern long keyctl_get_persistent(uid_t, key_serial_t); 249 + extern unsigned persistent_keyring_expiry; 250 + #else 251 + static inline long keyctl_get_persistent(uid_t uid, key_serial_t destring) 252 + { 253 + return -EOPNOTSUPP; 254 + } 255 + #endif 258 256 259 257 /* 260 258 * Debugging key validation
+56 -46
security/keys/key.c
··· 242 242 } 243 243 } 244 244 245 - desclen = strlen(desc) + 1; 246 - quotalen = desclen + type->def_datalen; 245 + desclen = strlen(desc); 246 + quotalen = desclen + 1 + type->def_datalen; 247 247 248 248 /* get hold of the key tracking for this user */ 249 249 user = key_user_lookup(uid); ··· 277 277 goto no_memory_2; 278 278 279 279 if (desc) { 280 - key->description = kmemdup(desc, desclen, GFP_KERNEL); 280 + key->index_key.desc_len = desclen; 281 + key->index_key.description = kmemdup(desc, desclen + 1, GFP_KERNEL); 281 282 if (!key->description) 282 283 goto no_memory_3; 283 284 } ··· 286 285 atomic_set(&key->usage, 1); 287 286 init_rwsem(&key->sem); 288 287 lockdep_set_class(&key->sem, &type->lock_class); 289 - key->type = type; 288 + key->index_key.type = type; 290 289 key->user = user; 291 290 key->quotalen = quotalen; 292 291 key->datalen = type->def_datalen; ··· 300 299 301 300 if (!(flags & KEY_ALLOC_NOT_IN_QUOTA)) 302 301 key->flags |= 1 << KEY_FLAG_IN_QUOTA; 302 + if (flags & KEY_ALLOC_TRUSTED) 303 + key->flags |= 1 << KEY_FLAG_TRUSTED; 303 304 304 305 memset(&key->type_data, 0, sizeof(key->type_data)); 305 306 ··· 411 408 struct key_preparsed_payload *prep, 412 409 struct key *keyring, 413 410 struct key *authkey, 414 - unsigned long *_prealloc) 411 + struct assoc_array_edit **_edit) 415 412 { 416 413 int ret, awaken; 417 414 ··· 438 435 439 436 /* and link it into the destination keyring */ 440 437 if (keyring) 441 - __key_link(keyring, key, _prealloc); 438 + __key_link(key, _edit); 442 439 443 440 /* disable the authorisation key */ 444 441 if (authkey) ··· 478 475 struct key *authkey) 479 476 { 480 477 struct key_preparsed_payload prep; 481 - unsigned long prealloc; 478 + struct assoc_array_edit *edit; 482 479 int ret; 483 480 484 481 memset(&prep, 0, sizeof(prep)); ··· 492 489 } 493 490 494 491 if (keyring) { 495 - ret = __key_link_begin(keyring, key->type, key->description, 496 - &prealloc); 492 + ret = __key_link_begin(keyring, &key->index_key, &edit); 497 493 if (ret < 0) 498 494 goto error_free_preparse; 499 495 } 500 496 501 - ret = __key_instantiate_and_link(key, &prep, keyring, authkey, 502 - &prealloc); 497 + ret = __key_instantiate_and_link(key, &prep, keyring, authkey, &edit); 503 498 504 499 if (keyring) 505 - __key_link_end(keyring, key->type, prealloc); 500 + __key_link_end(keyring, &key->index_key, edit); 506 501 507 502 error_free_preparse: 508 503 if (key->type->preparse) ··· 538 537 struct key *keyring, 539 538 struct key *authkey) 540 539 { 541 - unsigned long prealloc; 540 + struct assoc_array_edit *edit; 542 541 struct timespec now; 543 542 int ret, awaken, link_ret = 0; 544 543 ··· 549 548 ret = -EBUSY; 550 549 551 550 if (keyring) 552 - link_ret = __key_link_begin(keyring, key->type, 553 - key->description, &prealloc); 551 + link_ret = __key_link_begin(keyring, &key->index_key, &edit); 554 552 555 553 mutex_lock(&key_construction_mutex); 556 554 ··· 557 557 if (!test_bit(KEY_FLAG_INSTANTIATED, &key->flags)) { 558 558 /* mark the key as being negatively instantiated */ 559 559 atomic_inc(&key->user->nikeys); 560 + key->type_data.reject_error = -error; 561 + smp_wmb(); 560 562 set_bit(KEY_FLAG_NEGATIVE, &key->flags); 561 563 set_bit(KEY_FLAG_INSTANTIATED, &key->flags); 562 - key->type_data.reject_error = -error; 563 564 now = current_kernel_time(); 564 565 key->expiry = now.tv_sec + timeout; 565 566 key_schedule_gc(key->expiry + key_gc_delay); ··· 572 571 573 572 /* and link it into the destination keyring */ 574 573 if (keyring && link_ret == 0) 575 - __key_link(keyring, key, &prealloc); 574 + __key_link(key, &edit); 576 575 577 576 /* disable the authorisation key */ 578 577 if (authkey) ··· 582 581 mutex_unlock(&key_construction_mutex); 583 582 584 583 if (keyring) 585 - __key_link_end(keyring, key->type, prealloc); 584 + __key_link_end(keyring, &key->index_key, edit); 586 585 587 586 /* wake up anyone waiting for a key to be constructed */ 588 587 if (awaken) ··· 646 645 /* this races with key_put(), but that doesn't matter since key_put() 647 646 * doesn't actually change the key 648 647 */ 649 - atomic_inc(&key->usage); 648 + __key_get(key); 650 649 651 650 error: 652 651 spin_unlock(&key_serial_lock); ··· 781 780 key_perm_t perm, 782 781 unsigned long flags) 783 782 { 784 - unsigned long prealloc; 783 + struct keyring_index_key index_key = { 784 + .description = description, 785 + }; 785 786 struct key_preparsed_payload prep; 787 + struct assoc_array_edit *edit; 786 788 const struct cred *cred = current_cred(); 787 - struct key_type *ktype; 788 789 struct key *keyring, *key = NULL; 789 790 key_ref_t key_ref; 790 791 int ret; 791 792 792 793 /* look up the key type to see if it's one of the registered kernel 793 794 * types */ 794 - ktype = key_type_lookup(type); 795 - if (IS_ERR(ktype)) { 795 + index_key.type = key_type_lookup(type); 796 + if (IS_ERR(index_key.type)) { 796 797 key_ref = ERR_PTR(-ENODEV); 797 798 goto error; 798 799 } 799 800 800 801 key_ref = ERR_PTR(-EINVAL); 801 - if (!ktype->match || !ktype->instantiate || 802 - (!description && !ktype->preparse)) 802 + if (!index_key.type->match || !index_key.type->instantiate || 803 + (!index_key.description && !index_key.type->preparse)) 803 804 goto error_put_type; 804 805 805 806 keyring = key_ref_to_ptr(keyring_ref); ··· 815 812 memset(&prep, 0, sizeof(prep)); 816 813 prep.data = payload; 817 814 prep.datalen = plen; 818 - prep.quotalen = ktype->def_datalen; 819 - if (ktype->preparse) { 820 - ret = ktype->preparse(&prep); 815 + prep.quotalen = index_key.type->def_datalen; 816 + prep.trusted = flags & KEY_ALLOC_TRUSTED; 817 + if (index_key.type->preparse) { 818 + ret = index_key.type->preparse(&prep); 821 819 if (ret < 0) { 822 820 key_ref = ERR_PTR(ret); 823 821 goto error_put_type; 824 822 } 825 - if (!description) 826 - description = prep.description; 823 + if (!index_key.description) 824 + index_key.description = prep.description; 827 825 key_ref = ERR_PTR(-EINVAL); 828 - if (!description) 826 + if (!index_key.description) 829 827 goto error_free_prep; 830 828 } 829 + index_key.desc_len = strlen(index_key.description); 831 830 832 - ret = __key_link_begin(keyring, ktype, description, &prealloc); 831 + key_ref = ERR_PTR(-EPERM); 832 + if (!prep.trusted && test_bit(KEY_FLAG_TRUSTED_ONLY, &keyring->flags)) 833 + goto error_free_prep; 834 + flags |= prep.trusted ? KEY_ALLOC_TRUSTED : 0; 835 + 836 + ret = __key_link_begin(keyring, &index_key, &edit); 833 837 if (ret < 0) { 834 838 key_ref = ERR_PTR(ret); 835 839 goto error_free_prep; ··· 854 844 * key of the same type and description in the destination keyring and 855 845 * update that instead if possible 856 846 */ 857 - if (ktype->update) { 858 - key_ref = __keyring_search_one(keyring_ref, ktype, description, 859 - 0); 860 - if (!IS_ERR(key_ref)) 847 + if (index_key.type->update) { 848 + key_ref = find_key_to_update(keyring_ref, &index_key); 849 + if (key_ref) 861 850 goto found_matching_key; 862 851 } 863 852 ··· 865 856 perm = KEY_POS_VIEW | KEY_POS_SEARCH | KEY_POS_LINK | KEY_POS_SETATTR; 866 857 perm |= KEY_USR_VIEW; 867 858 868 - if (ktype->read) 859 + if (index_key.type->read) 869 860 perm |= KEY_POS_READ; 870 861 871 - if (ktype == &key_type_keyring || ktype->update) 862 + if (index_key.type == &key_type_keyring || 863 + index_key.type->update) 872 864 perm |= KEY_POS_WRITE; 873 865 } 874 866 875 867 /* allocate a new key */ 876 - key = key_alloc(ktype, description, cred->fsuid, cred->fsgid, cred, 877 - perm, flags); 868 + key = key_alloc(index_key.type, index_key.description, 869 + cred->fsuid, cred->fsgid, cred, perm, flags); 878 870 if (IS_ERR(key)) { 879 871 key_ref = ERR_CAST(key); 880 872 goto error_link_end; 881 873 } 882 874 883 875 /* instantiate it and link it into the target keyring */ 884 - ret = __key_instantiate_and_link(key, &prep, keyring, NULL, &prealloc); 876 + ret = __key_instantiate_and_link(key, &prep, keyring, NULL, &edit); 885 877 if (ret < 0) { 886 878 key_put(key); 887 879 key_ref = ERR_PTR(ret); ··· 892 882 key_ref = make_key_ref(key, is_key_possessed(keyring_ref)); 893 883 894 884 error_link_end: 895 - __key_link_end(keyring, ktype, prealloc); 885 + __key_link_end(keyring, &index_key, edit); 896 886 error_free_prep: 897 - if (ktype->preparse) 898 - ktype->free_preparse(&prep); 887 + if (index_key.type->preparse) 888 + index_key.type->free_preparse(&prep); 899 889 error_put_type: 900 - key_type_put(ktype); 890 + key_type_put(index_key.type); 901 891 error: 902 892 return key_ref; 903 893 ··· 905 895 /* we found a matching key, so we're going to try to update it 906 896 * - we can drop the locks first as we have the key pinned 907 897 */ 908 - __key_link_end(keyring, ktype, prealloc); 898 + __key_link_end(keyring, &index_key, edit); 909 899 910 900 key_ref = __key_update(key_ref, &prep); 911 901 goto error_free_prep;
+3
security/keys/keyctl.c
··· 1667 1667 case KEYCTL_INVALIDATE: 1668 1668 return keyctl_invalidate_key((key_serial_t) arg2); 1669 1669 1670 + case KEYCTL_GET_PERSISTENT: 1671 + return keyctl_get_persistent((uid_t)arg2, (key_serial_t)arg3); 1672 + 1670 1673 default: 1671 1674 return -EOPNOTSUPP; 1672 1675 }
+814 -732
security/keys/keyring.c
··· 1 1 /* Keyring handling 2 2 * 3 - * Copyright (C) 2004-2005, 2008 Red Hat, Inc. All Rights Reserved. 3 + * Copyright (C) 2004-2005, 2008, 2013 Red Hat, Inc. All Rights Reserved. 4 4 * Written by David Howells (dhowells@redhat.com) 5 5 * 6 6 * This program is free software; you can redistribute it and/or ··· 17 17 #include <linux/seq_file.h> 18 18 #include <linux/err.h> 19 19 #include <keys/keyring-type.h> 20 + #include <keys/user-type.h> 21 + #include <linux/assoc_array_priv.h> 20 22 #include <linux/uaccess.h> 21 23 #include "internal.h" 22 - 23 - #define rcu_dereference_locked_keyring(keyring) \ 24 - (rcu_dereference_protected( \ 25 - (keyring)->payload.subscriptions, \ 26 - rwsem_is_locked((struct rw_semaphore *)&(keyring)->sem))) 27 - 28 - #define rcu_deref_link_locked(klist, index, keyring) \ 29 - (rcu_dereference_protected( \ 30 - (klist)->keys[index], \ 31 - rwsem_is_locked((struct rw_semaphore *)&(keyring)->sem))) 32 - 33 - #define MAX_KEYRING_LINKS \ 34 - min_t(size_t, USHRT_MAX - 1, \ 35 - ((PAGE_SIZE - sizeof(struct keyring_list)) / sizeof(struct key *))) 36 - 37 - #define KEY_LINK_FIXQUOTA 1UL 38 24 39 25 /* 40 26 * When plumbing the depths of the key tree, this sets a hard limit ··· 32 46 * We keep all named keyrings in a hash to speed looking them up. 33 47 */ 34 48 #define KEYRING_NAME_HASH_SIZE (1 << 5) 49 + 50 + /* 51 + * We mark pointers we pass to the associative array with bit 1 set if 52 + * they're keyrings and clear otherwise. 53 + */ 54 + #define KEYRING_PTR_SUBTYPE 0x2UL 55 + 56 + static inline bool keyring_ptr_is_keyring(const struct assoc_array_ptr *x) 57 + { 58 + return (unsigned long)x & KEYRING_PTR_SUBTYPE; 59 + } 60 + static inline struct key *keyring_ptr_to_key(const struct assoc_array_ptr *x) 61 + { 62 + void *object = assoc_array_ptr_to_leaf(x); 63 + return (struct key *)((unsigned long)object & ~KEYRING_PTR_SUBTYPE); 64 + } 65 + static inline void *keyring_key_to_ptr(struct key *key) 66 + { 67 + if (key->type == &key_type_keyring) 68 + return (void *)((unsigned long)key | KEYRING_PTR_SUBTYPE); 69 + return key; 70 + } 35 71 36 72 static struct list_head keyring_name_hash[KEYRING_NAME_HASH_SIZE]; 37 73 static DEFINE_RWLOCK(keyring_name_lock); ··· 75 67 */ 76 68 static int keyring_instantiate(struct key *keyring, 77 69 struct key_preparsed_payload *prep); 78 - static int keyring_match(const struct key *keyring, const void *criterion); 79 70 static void keyring_revoke(struct key *keyring); 80 71 static void keyring_destroy(struct key *keyring); 81 72 static void keyring_describe(const struct key *keyring, struct seq_file *m); ··· 83 76 84 77 struct key_type key_type_keyring = { 85 78 .name = "keyring", 86 - .def_datalen = sizeof(struct keyring_list), 79 + .def_datalen = 0, 87 80 .instantiate = keyring_instantiate, 88 - .match = keyring_match, 81 + .match = user_match, 89 82 .revoke = keyring_revoke, 90 83 .destroy = keyring_destroy, 91 84 .describe = keyring_describe, ··· 134 127 135 128 ret = -EINVAL; 136 129 if (prep->datalen == 0) { 130 + assoc_array_init(&keyring->keys); 137 131 /* make the keyring available by name if it has one */ 138 132 keyring_publish_name(keyring); 139 133 ret = 0; ··· 144 136 } 145 137 146 138 /* 147 - * Match keyrings on their name 139 + * Multiply 64-bits by 32-bits to 96-bits and fold back to 64-bit. Ideally we'd 140 + * fold the carry back too, but that requires inline asm. 148 141 */ 149 - static int keyring_match(const struct key *keyring, const void *description) 142 + static u64 mult_64x32_and_fold(u64 x, u32 y) 150 143 { 151 - return keyring->description && 152 - strcmp(keyring->description, description) == 0; 144 + u64 hi = (u64)(u32)(x >> 32) * y; 145 + u64 lo = (u64)(u32)(x) * y; 146 + return lo + ((u64)(u32)hi << 32) + (u32)(hi >> 32); 153 147 } 148 + 149 + /* 150 + * Hash a key type and description. 151 + */ 152 + static unsigned long hash_key_type_and_desc(const struct keyring_index_key *index_key) 153 + { 154 + const unsigned level_shift = ASSOC_ARRAY_LEVEL_STEP; 155 + const unsigned long level_mask = ASSOC_ARRAY_LEVEL_STEP_MASK; 156 + const char *description = index_key->description; 157 + unsigned long hash, type; 158 + u32 piece; 159 + u64 acc; 160 + int n, desc_len = index_key->desc_len; 161 + 162 + type = (unsigned long)index_key->type; 163 + 164 + acc = mult_64x32_and_fold(type, desc_len + 13); 165 + acc = mult_64x32_and_fold(acc, 9207); 166 + for (;;) { 167 + n = desc_len; 168 + if (n <= 0) 169 + break; 170 + if (n > 4) 171 + n = 4; 172 + piece = 0; 173 + memcpy(&piece, description, n); 174 + description += n; 175 + desc_len -= n; 176 + acc = mult_64x32_and_fold(acc, piece); 177 + acc = mult_64x32_and_fold(acc, 9207); 178 + } 179 + 180 + /* Fold the hash down to 32 bits if need be. */ 181 + hash = acc; 182 + if (ASSOC_ARRAY_KEY_CHUNK_SIZE == 32) 183 + hash ^= acc >> 32; 184 + 185 + /* Squidge all the keyrings into a separate part of the tree to 186 + * ordinary keys by making sure the lowest level segment in the hash is 187 + * zero for keyrings and non-zero otherwise. 188 + */ 189 + if (index_key->type != &key_type_keyring && (hash & level_mask) == 0) 190 + return hash | (hash >> (ASSOC_ARRAY_KEY_CHUNK_SIZE - level_shift)) | 1; 191 + if (index_key->type == &key_type_keyring && (hash & level_mask) != 0) 192 + return (hash + (hash << level_shift)) & ~level_mask; 193 + return hash; 194 + } 195 + 196 + /* 197 + * Build the next index key chunk. 198 + * 199 + * On 32-bit systems the index key is laid out as: 200 + * 201 + * 0 4 5 9... 202 + * hash desclen typeptr desc[] 203 + * 204 + * On 64-bit systems: 205 + * 206 + * 0 8 9 17... 207 + * hash desclen typeptr desc[] 208 + * 209 + * We return it one word-sized chunk at a time. 210 + */ 211 + static unsigned long keyring_get_key_chunk(const void *data, int level) 212 + { 213 + const struct keyring_index_key *index_key = data; 214 + unsigned long chunk = 0; 215 + long offset = 0; 216 + int desc_len = index_key->desc_len, n = sizeof(chunk); 217 + 218 + level /= ASSOC_ARRAY_KEY_CHUNK_SIZE; 219 + switch (level) { 220 + case 0: 221 + return hash_key_type_and_desc(index_key); 222 + case 1: 223 + return ((unsigned long)index_key->type << 8) | desc_len; 224 + case 2: 225 + if (desc_len == 0) 226 + return (u8)((unsigned long)index_key->type >> 227 + (ASSOC_ARRAY_KEY_CHUNK_SIZE - 8)); 228 + n--; 229 + offset = 1; 230 + default: 231 + offset += sizeof(chunk) - 1; 232 + offset += (level - 3) * sizeof(chunk); 233 + if (offset >= desc_len) 234 + return 0; 235 + desc_len -= offset; 236 + if (desc_len > n) 237 + desc_len = n; 238 + offset += desc_len; 239 + do { 240 + chunk <<= 8; 241 + chunk |= ((u8*)index_key->description)[--offset]; 242 + } while (--desc_len > 0); 243 + 244 + if (level == 2) { 245 + chunk <<= 8; 246 + chunk |= (u8)((unsigned long)index_key->type >> 247 + (ASSOC_ARRAY_KEY_CHUNK_SIZE - 8)); 248 + } 249 + return chunk; 250 + } 251 + } 252 + 253 + static unsigned long keyring_get_object_key_chunk(const void *object, int level) 254 + { 255 + const struct key *key = keyring_ptr_to_key(object); 256 + return keyring_get_key_chunk(&key->index_key, level); 257 + } 258 + 259 + static bool keyring_compare_object(const void *object, const void *data) 260 + { 261 + const struct keyring_index_key *index_key = data; 262 + const struct key *key = keyring_ptr_to_key(object); 263 + 264 + return key->index_key.type == index_key->type && 265 + key->index_key.desc_len == index_key->desc_len && 266 + memcmp(key->index_key.description, index_key->description, 267 + index_key->desc_len) == 0; 268 + } 269 + 270 + /* 271 + * Compare the index keys of a pair of objects and determine the bit position 272 + * at which they differ - if they differ. 273 + */ 274 + static int keyring_diff_objects(const void *_a, const void *_b) 275 + { 276 + const struct key *key_a = keyring_ptr_to_key(_a); 277 + const struct key *key_b = keyring_ptr_to_key(_b); 278 + const struct keyring_index_key *a = &key_a->index_key; 279 + const struct keyring_index_key *b = &key_b->index_key; 280 + unsigned long seg_a, seg_b; 281 + int level, i; 282 + 283 + level = 0; 284 + seg_a = hash_key_type_and_desc(a); 285 + seg_b = hash_key_type_and_desc(b); 286 + if ((seg_a ^ seg_b) != 0) 287 + goto differ; 288 + 289 + /* The number of bits contributed by the hash is controlled by a 290 + * constant in the assoc_array headers. Everything else thereafter we 291 + * can deal with as being machine word-size dependent. 292 + */ 293 + level += ASSOC_ARRAY_KEY_CHUNK_SIZE / 8; 294 + seg_a = a->desc_len; 295 + seg_b = b->desc_len; 296 + if ((seg_a ^ seg_b) != 0) 297 + goto differ; 298 + 299 + /* The next bit may not work on big endian */ 300 + level++; 301 + seg_a = (unsigned long)a->type; 302 + seg_b = (unsigned long)b->type; 303 + if ((seg_a ^ seg_b) != 0) 304 + goto differ; 305 + 306 + level += sizeof(unsigned long); 307 + if (a->desc_len == 0) 308 + goto same; 309 + 310 + i = 0; 311 + if (((unsigned long)a->description | (unsigned long)b->description) & 312 + (sizeof(unsigned long) - 1)) { 313 + do { 314 + seg_a = *(unsigned long *)(a->description + i); 315 + seg_b = *(unsigned long *)(b->description + i); 316 + if ((seg_a ^ seg_b) != 0) 317 + goto differ_plus_i; 318 + i += sizeof(unsigned long); 319 + } while (i < (a->desc_len & (sizeof(unsigned long) - 1))); 320 + } 321 + 322 + for (; i < a->desc_len; i++) { 323 + seg_a = *(unsigned char *)(a->description + i); 324 + seg_b = *(unsigned char *)(b->description + i); 325 + if ((seg_a ^ seg_b) != 0) 326 + goto differ_plus_i; 327 + } 328 + 329 + same: 330 + return -1; 331 + 332 + differ_plus_i: 333 + level += i; 334 + differ: 335 + i = level * 8 + __ffs(seg_a ^ seg_b); 336 + return i; 337 + } 338 + 339 + /* 340 + * Free an object after stripping the keyring flag off of the pointer. 341 + */ 342 + static void keyring_free_object(void *object) 343 + { 344 + key_put(keyring_ptr_to_key(object)); 345 + } 346 + 347 + /* 348 + * Operations for keyring management by the index-tree routines. 349 + */ 350 + static const struct assoc_array_ops keyring_assoc_array_ops = { 351 + .get_key_chunk = keyring_get_key_chunk, 352 + .get_object_key_chunk = keyring_get_object_key_chunk, 353 + .compare_object = keyring_compare_object, 354 + .diff_objects = keyring_diff_objects, 355 + .free_object = keyring_free_object, 356 + }; 154 357 155 358 /* 156 359 * Clean up a keyring when it is destroyed. Unpublish its name if it had one ··· 374 155 */ 375 156 static void keyring_destroy(struct key *keyring) 376 157 { 377 - struct keyring_list *klist; 378 - int loop; 379 - 380 158 if (keyring->description) { 381 159 write_lock(&keyring_name_lock); 382 160 ··· 384 168 write_unlock(&keyring_name_lock); 385 169 } 386 170 387 - klist = rcu_access_pointer(keyring->payload.subscriptions); 388 - if (klist) { 389 - for (loop = klist->nkeys - 1; loop >= 0; loop--) 390 - key_put(rcu_access_pointer(klist->keys[loop])); 391 - kfree(klist); 392 - } 171 + assoc_array_destroy(&keyring->keys, &keyring_assoc_array_ops); 393 172 } 394 173 395 174 /* ··· 392 181 */ 393 182 static void keyring_describe(const struct key *keyring, struct seq_file *m) 394 183 { 395 - struct keyring_list *klist; 396 - 397 184 if (keyring->description) 398 185 seq_puts(m, keyring->description); 399 186 else 400 187 seq_puts(m, "[anon]"); 401 188 402 189 if (key_is_instantiated(keyring)) { 403 - rcu_read_lock(); 404 - klist = rcu_dereference(keyring->payload.subscriptions); 405 - if (klist) 406 - seq_printf(m, ": %u/%u", klist->nkeys, klist->maxkeys); 190 + if (keyring->keys.nr_leaves_on_tree != 0) 191 + seq_printf(m, ": %lu", keyring->keys.nr_leaves_on_tree); 407 192 else 408 193 seq_puts(m, ": empty"); 409 - rcu_read_unlock(); 410 194 } 195 + } 196 + 197 + struct keyring_read_iterator_context { 198 + size_t qty; 199 + size_t count; 200 + key_serial_t __user *buffer; 201 + }; 202 + 203 + static int keyring_read_iterator(const void *object, void *data) 204 + { 205 + struct keyring_read_iterator_context *ctx = data; 206 + const struct key *key = keyring_ptr_to_key(object); 207 + int ret; 208 + 209 + kenter("{%s,%d},,{%zu/%zu}", 210 + key->type->name, key->serial, ctx->count, ctx->qty); 211 + 212 + if (ctx->count >= ctx->qty) 213 + return 1; 214 + 215 + ret = put_user(key->serial, ctx->buffer); 216 + if (ret < 0) 217 + return ret; 218 + ctx->buffer++; 219 + ctx->count += sizeof(key->serial); 220 + return 0; 411 221 } 412 222 413 223 /* 414 224 * Read a list of key IDs from the keyring's contents in binary form 415 225 * 416 - * The keyring's semaphore is read-locked by the caller. 226 + * The keyring's semaphore is read-locked by the caller. This prevents someone 227 + * from modifying it under us - which could cause us to read key IDs multiple 228 + * times. 417 229 */ 418 230 static long keyring_read(const struct key *keyring, 419 231 char __user *buffer, size_t buflen) 420 232 { 421 - struct keyring_list *klist; 422 - struct key *key; 423 - size_t qty, tmp; 424 - int loop, ret; 233 + struct keyring_read_iterator_context ctx; 234 + unsigned long nr_keys; 235 + int ret; 425 236 426 - ret = 0; 427 - klist = rcu_dereference_locked_keyring(keyring); 428 - if (klist) { 429 - /* calculate how much data we could return */ 430 - qty = klist->nkeys * sizeof(key_serial_t); 237 + kenter("{%d},,%zu", key_serial(keyring), buflen); 431 238 432 - if (buffer && buflen > 0) { 433 - if (buflen > qty) 434 - buflen = qty; 239 + if (buflen & (sizeof(key_serial_t) - 1)) 240 + return -EINVAL; 435 241 436 - /* copy the IDs of the subscribed keys into the 437 - * buffer */ 438 - ret = -EFAULT; 242 + nr_keys = keyring->keys.nr_leaves_on_tree; 243 + if (nr_keys == 0) 244 + return 0; 439 245 440 - for (loop = 0; loop < klist->nkeys; loop++) { 441 - key = rcu_deref_link_locked(klist, loop, 442 - keyring); 246 + /* Calculate how much data we could return */ 247 + ctx.qty = nr_keys * sizeof(key_serial_t); 443 248 444 - tmp = sizeof(key_serial_t); 445 - if (tmp > buflen) 446 - tmp = buflen; 249 + if (!buffer || !buflen) 250 + return ctx.qty; 447 251 448 - if (copy_to_user(buffer, 449 - &key->serial, 450 - tmp) != 0) 451 - goto error; 252 + if (buflen > ctx.qty) 253 + ctx.qty = buflen; 452 254 453 - buflen -= tmp; 454 - if (buflen == 0) 455 - break; 456 - buffer += tmp; 457 - } 458 - } 459 - 460 - ret = qty; 255 + /* Copy the IDs of the subscribed keys into the buffer */ 256 + ctx.buffer = (key_serial_t __user *)buffer; 257 + ctx.count = 0; 258 + ret = assoc_array_iterate(&keyring->keys, keyring_read_iterator, &ctx); 259 + if (ret < 0) { 260 + kleave(" = %d [iterate]", ret); 261 + return ret; 461 262 } 462 263 463 - error: 464 - return ret; 264 + kleave(" = %zu [ok]", ctx.count); 265 + return ctx.count; 465 266 } 466 267 467 268 /* ··· 500 277 } 501 278 EXPORT_SYMBOL(keyring_alloc); 502 279 280 + /* 281 + * Iteration function to consider each key found. 282 + */ 283 + static int keyring_search_iterator(const void *object, void *iterator_data) 284 + { 285 + struct keyring_search_context *ctx = iterator_data; 286 + const struct key *key = keyring_ptr_to_key(object); 287 + unsigned long kflags = key->flags; 288 + 289 + kenter("{%d}", key->serial); 290 + 291 + /* ignore keys not of this type */ 292 + if (key->type != ctx->index_key.type) { 293 + kleave(" = 0 [!type]"); 294 + return 0; 295 + } 296 + 297 + /* skip invalidated, revoked and expired keys */ 298 + if (ctx->flags & KEYRING_SEARCH_DO_STATE_CHECK) { 299 + if (kflags & ((1 << KEY_FLAG_INVALIDATED) | 300 + (1 << KEY_FLAG_REVOKED))) { 301 + ctx->result = ERR_PTR(-EKEYREVOKED); 302 + kleave(" = %d [invrev]", ctx->skipped_ret); 303 + goto skipped; 304 + } 305 + 306 + if (key->expiry && ctx->now.tv_sec >= key->expiry) { 307 + ctx->result = ERR_PTR(-EKEYEXPIRED); 308 + kleave(" = %d [expire]", ctx->skipped_ret); 309 + goto skipped; 310 + } 311 + } 312 + 313 + /* keys that don't match */ 314 + if (!ctx->match(key, ctx->match_data)) { 315 + kleave(" = 0 [!match]"); 316 + return 0; 317 + } 318 + 319 + /* key must have search permissions */ 320 + if (!(ctx->flags & KEYRING_SEARCH_NO_CHECK_PERM) && 321 + key_task_permission(make_key_ref(key, ctx->possessed), 322 + ctx->cred, KEY_SEARCH) < 0) { 323 + ctx->result = ERR_PTR(-EACCES); 324 + kleave(" = %d [!perm]", ctx->skipped_ret); 325 + goto skipped; 326 + } 327 + 328 + if (ctx->flags & KEYRING_SEARCH_DO_STATE_CHECK) { 329 + /* we set a different error code if we pass a negative key */ 330 + if (kflags & (1 << KEY_FLAG_NEGATIVE)) { 331 + smp_rmb(); 332 + ctx->result = ERR_PTR(key->type_data.reject_error); 333 + kleave(" = %d [neg]", ctx->skipped_ret); 334 + goto skipped; 335 + } 336 + } 337 + 338 + /* Found */ 339 + ctx->result = make_key_ref(key, ctx->possessed); 340 + kleave(" = 1 [found]"); 341 + return 1; 342 + 343 + skipped: 344 + return ctx->skipped_ret; 345 + } 346 + 347 + /* 348 + * Search inside a keyring for a key. We can search by walking to it 349 + * directly based on its index-key or we can iterate over the entire 350 + * tree looking for it, based on the match function. 351 + */ 352 + static int search_keyring(struct key *keyring, struct keyring_search_context *ctx) 353 + { 354 + if ((ctx->flags & KEYRING_SEARCH_LOOKUP_TYPE) == 355 + KEYRING_SEARCH_LOOKUP_DIRECT) { 356 + const void *object; 357 + 358 + object = assoc_array_find(&keyring->keys, 359 + &keyring_assoc_array_ops, 360 + &ctx->index_key); 361 + return object ? ctx->iterator(object, ctx) : 0; 362 + } 363 + return assoc_array_iterate(&keyring->keys, ctx->iterator, ctx); 364 + } 365 + 366 + /* 367 + * Search a tree of keyrings that point to other keyrings up to the maximum 368 + * depth. 369 + */ 370 + static bool search_nested_keyrings(struct key *keyring, 371 + struct keyring_search_context *ctx) 372 + { 373 + struct { 374 + struct key *keyring; 375 + struct assoc_array_node *node; 376 + int slot; 377 + } stack[KEYRING_SEARCH_MAX_DEPTH]; 378 + 379 + struct assoc_array_shortcut *shortcut; 380 + struct assoc_array_node *node; 381 + struct assoc_array_ptr *ptr; 382 + struct key *key; 383 + int sp = 0, slot; 384 + 385 + kenter("{%d},{%s,%s}", 386 + keyring->serial, 387 + ctx->index_key.type->name, 388 + ctx->index_key.description); 389 + 390 + if (ctx->index_key.description) 391 + ctx->index_key.desc_len = strlen(ctx->index_key.description); 392 + 393 + /* Check to see if this top-level keyring is what we are looking for 394 + * and whether it is valid or not. 395 + */ 396 + if (ctx->flags & KEYRING_SEARCH_LOOKUP_ITERATE || 397 + keyring_compare_object(keyring, &ctx->index_key)) { 398 + ctx->skipped_ret = 2; 399 + ctx->flags |= KEYRING_SEARCH_DO_STATE_CHECK; 400 + switch (ctx->iterator(keyring_key_to_ptr(keyring), ctx)) { 401 + case 1: 402 + goto found; 403 + case 2: 404 + return false; 405 + default: 406 + break; 407 + } 408 + } 409 + 410 + ctx->skipped_ret = 0; 411 + if (ctx->flags & KEYRING_SEARCH_NO_STATE_CHECK) 412 + ctx->flags &= ~KEYRING_SEARCH_DO_STATE_CHECK; 413 + 414 + /* Start processing a new keyring */ 415 + descend_to_keyring: 416 + kdebug("descend to %d", keyring->serial); 417 + if (keyring->flags & ((1 << KEY_FLAG_INVALIDATED) | 418 + (1 << KEY_FLAG_REVOKED))) 419 + goto not_this_keyring; 420 + 421 + /* Search through the keys in this keyring before its searching its 422 + * subtrees. 423 + */ 424 + if (search_keyring(keyring, ctx)) 425 + goto found; 426 + 427 + /* Then manually iterate through the keyrings nested in this one. 428 + * 429 + * Start from the root node of the index tree. Because of the way the 430 + * hash function has been set up, keyrings cluster on the leftmost 431 + * branch of the root node (root slot 0) or in the root node itself. 432 + * Non-keyrings avoid the leftmost branch of the root entirely (root 433 + * slots 1-15). 434 + */ 435 + ptr = ACCESS_ONCE(keyring->keys.root); 436 + if (!ptr) 437 + goto not_this_keyring; 438 + 439 + if (assoc_array_ptr_is_shortcut(ptr)) { 440 + /* If the root is a shortcut, either the keyring only contains 441 + * keyring pointers (everything clusters behind root slot 0) or 442 + * doesn't contain any keyring pointers. 443 + */ 444 + shortcut = assoc_array_ptr_to_shortcut(ptr); 445 + smp_read_barrier_depends(); 446 + if ((shortcut->index_key[0] & ASSOC_ARRAY_FAN_MASK) != 0) 447 + goto not_this_keyring; 448 + 449 + ptr = ACCESS_ONCE(shortcut->next_node); 450 + node = assoc_array_ptr_to_node(ptr); 451 + goto begin_node; 452 + } 453 + 454 + node = assoc_array_ptr_to_node(ptr); 455 + smp_read_barrier_depends(); 456 + 457 + ptr = node->slots[0]; 458 + if (!assoc_array_ptr_is_meta(ptr)) 459 + goto begin_node; 460 + 461 + descend_to_node: 462 + /* Descend to a more distal node in this keyring's content tree and go 463 + * through that. 464 + */ 465 + kdebug("descend"); 466 + if (assoc_array_ptr_is_shortcut(ptr)) { 467 + shortcut = assoc_array_ptr_to_shortcut(ptr); 468 + smp_read_barrier_depends(); 469 + ptr = ACCESS_ONCE(shortcut->next_node); 470 + BUG_ON(!assoc_array_ptr_is_node(ptr)); 471 + node = assoc_array_ptr_to_node(ptr); 472 + } 473 + 474 + begin_node: 475 + kdebug("begin_node"); 476 + smp_read_barrier_depends(); 477 + slot = 0; 478 + ascend_to_node: 479 + /* Go through the slots in a node */ 480 + for (; slot < ASSOC_ARRAY_FAN_OUT; slot++) { 481 + ptr = ACCESS_ONCE(node->slots[slot]); 482 + 483 + if (assoc_array_ptr_is_meta(ptr) && node->back_pointer) 484 + goto descend_to_node; 485 + 486 + if (!keyring_ptr_is_keyring(ptr)) 487 + continue; 488 + 489 + key = keyring_ptr_to_key(ptr); 490 + 491 + if (sp >= KEYRING_SEARCH_MAX_DEPTH) { 492 + if (ctx->flags & KEYRING_SEARCH_DETECT_TOO_DEEP) { 493 + ctx->result = ERR_PTR(-ELOOP); 494 + return false; 495 + } 496 + goto not_this_keyring; 497 + } 498 + 499 + /* Search a nested keyring */ 500 + if (!(ctx->flags & KEYRING_SEARCH_NO_CHECK_PERM) && 501 + key_task_permission(make_key_ref(key, ctx->possessed), 502 + ctx->cred, KEY_SEARCH) < 0) 503 + continue; 504 + 505 + /* stack the current position */ 506 + stack[sp].keyring = keyring; 507 + stack[sp].node = node; 508 + stack[sp].slot = slot; 509 + sp++; 510 + 511 + /* begin again with the new keyring */ 512 + keyring = key; 513 + goto descend_to_keyring; 514 + } 515 + 516 + /* We've dealt with all the slots in the current node, so now we need 517 + * to ascend to the parent and continue processing there. 518 + */ 519 + ptr = ACCESS_ONCE(node->back_pointer); 520 + slot = node->parent_slot; 521 + 522 + if (ptr && assoc_array_ptr_is_shortcut(ptr)) { 523 + shortcut = assoc_array_ptr_to_shortcut(ptr); 524 + smp_read_barrier_depends(); 525 + ptr = ACCESS_ONCE(shortcut->back_pointer); 526 + slot = shortcut->parent_slot; 527 + } 528 + if (!ptr) 529 + goto not_this_keyring; 530 + node = assoc_array_ptr_to_node(ptr); 531 + smp_read_barrier_depends(); 532 + slot++; 533 + 534 + /* If we've ascended to the root (zero backpointer), we must have just 535 + * finished processing the leftmost branch rather than the root slots - 536 + * so there can't be any more keyrings for us to find. 537 + */ 538 + if (node->back_pointer) { 539 + kdebug("ascend %d", slot); 540 + goto ascend_to_node; 541 + } 542 + 543 + /* The keyring we're looking at was disqualified or didn't contain a 544 + * matching key. 545 + */ 546 + not_this_keyring: 547 + kdebug("not_this_keyring %d", sp); 548 + if (sp <= 0) { 549 + kleave(" = false"); 550 + return false; 551 + } 552 + 553 + /* Resume the processing of a keyring higher up in the tree */ 554 + sp--; 555 + keyring = stack[sp].keyring; 556 + node = stack[sp].node; 557 + slot = stack[sp].slot + 1; 558 + kdebug("ascend to %d [%d]", keyring->serial, slot); 559 + goto ascend_to_node; 560 + 561 + /* We found a viable match */ 562 + found: 563 + key = key_ref_to_ptr(ctx->result); 564 + key_check(key); 565 + if (!(ctx->flags & KEYRING_SEARCH_NO_UPDATE_TIME)) { 566 + key->last_used_at = ctx->now.tv_sec; 567 + keyring->last_used_at = ctx->now.tv_sec; 568 + while (sp > 0) 569 + stack[--sp].keyring->last_used_at = ctx->now.tv_sec; 570 + } 571 + kleave(" = true"); 572 + return true; 573 + } 574 + 503 575 /** 504 576 * keyring_search_aux - Search a keyring tree for a key matching some criteria 505 577 * @keyring_ref: A pointer to the keyring with possession indicator. 506 - * @cred: The credentials to use for permissions checks. 507 - * @type: The type of key to search for. 508 - * @description: Parameter for @match. 509 - * @match: Function to rule on whether or not a key is the one required. 510 - * @no_state_check: Don't check if a matching key is bad 578 + * @ctx: The keyring search context. 511 579 * 512 580 * Search the supplied keyring tree for a key that matches the criteria given. 513 581 * The root keyring and any linked keyrings must grant Search permission to the ··· 816 302 * determine the match. Normally the match function from the key type would be 817 303 * used. 818 304 * 819 - * RCU is used to prevent the keyring key lists from disappearing without the 820 - * need to take lots of locks. 305 + * RCU can be used to prevent the keyring key lists from disappearing without 306 + * the need to take lots of locks. 821 307 * 822 308 * Returns a pointer to the found key and increments the key usage count if 823 309 * successful; -EAGAIN if no matching keys were found, or if expired or revoked ··· 828 314 * @keyring_ref is propagated to the returned key reference. 829 315 */ 830 316 key_ref_t keyring_search_aux(key_ref_t keyring_ref, 831 - const struct cred *cred, 832 - struct key_type *type, 833 - const void *description, 834 - key_match_func_t match, 835 - bool no_state_check) 317 + struct keyring_search_context *ctx) 836 318 { 837 - struct { 838 - /* Need a separate keylist pointer for RCU purposes */ 839 - struct key *keyring; 840 - struct keyring_list *keylist; 841 - int kix; 842 - } stack[KEYRING_SEARCH_MAX_DEPTH]; 843 - 844 - struct keyring_list *keylist; 845 - struct timespec now; 846 - unsigned long possessed, kflags; 847 - struct key *keyring, *key; 848 - key_ref_t key_ref; 319 + struct key *keyring; 849 320 long err; 850 - int sp, nkeys, kix; 321 + 322 + ctx->iterator = keyring_search_iterator; 323 + ctx->possessed = is_key_possessed(keyring_ref); 324 + ctx->result = ERR_PTR(-EAGAIN); 851 325 852 326 keyring = key_ref_to_ptr(keyring_ref); 853 - possessed = is_key_possessed(keyring_ref); 854 327 key_check(keyring); 855 328 856 - /* top keyring must have search permission to begin the search */ 857 - err = key_task_permission(keyring_ref, cred, KEY_SEARCH); 858 - if (err < 0) { 859 - key_ref = ERR_PTR(err); 860 - goto error; 861 - } 862 - 863 - key_ref = ERR_PTR(-ENOTDIR); 864 329 if (keyring->type != &key_type_keyring) 865 - goto error; 330 + return ERR_PTR(-ENOTDIR); 331 + 332 + if (!(ctx->flags & KEYRING_SEARCH_NO_CHECK_PERM)) { 333 + err = key_task_permission(keyring_ref, ctx->cred, KEY_SEARCH); 334 + if (err < 0) 335 + return ERR_PTR(err); 336 + } 866 337 867 338 rcu_read_lock(); 868 - 869 - now = current_kernel_time(); 870 - err = -EAGAIN; 871 - sp = 0; 872 - 873 - /* firstly we should check to see if this top-level keyring is what we 874 - * are looking for */ 875 - key_ref = ERR_PTR(-EAGAIN); 876 - kflags = keyring->flags; 877 - if (keyring->type == type && match(keyring, description)) { 878 - key = keyring; 879 - if (no_state_check) 880 - goto found; 881 - 882 - /* check it isn't negative and hasn't expired or been 883 - * revoked */ 884 - if (kflags & (1 << KEY_FLAG_REVOKED)) 885 - goto error_2; 886 - if (key->expiry && now.tv_sec >= key->expiry) 887 - goto error_2; 888 - key_ref = ERR_PTR(key->type_data.reject_error); 889 - if (kflags & (1 << KEY_FLAG_NEGATIVE)) 890 - goto error_2; 891 - goto found; 892 - } 893 - 894 - /* otherwise, the top keyring must not be revoked, expired, or 895 - * negatively instantiated if we are to search it */ 896 - key_ref = ERR_PTR(-EAGAIN); 897 - if (kflags & ((1 << KEY_FLAG_INVALIDATED) | 898 - (1 << KEY_FLAG_REVOKED) | 899 - (1 << KEY_FLAG_NEGATIVE)) || 900 - (keyring->expiry && now.tv_sec >= keyring->expiry)) 901 - goto error_2; 902 - 903 - /* start processing a new keyring */ 904 - descend: 905 - kflags = keyring->flags; 906 - if (kflags & ((1 << KEY_FLAG_INVALIDATED) | 907 - (1 << KEY_FLAG_REVOKED))) 908 - goto not_this_keyring; 909 - 910 - keylist = rcu_dereference(keyring->payload.subscriptions); 911 - if (!keylist) 912 - goto not_this_keyring; 913 - 914 - /* iterate through the keys in this keyring first */ 915 - nkeys = keylist->nkeys; 916 - smp_rmb(); 917 - for (kix = 0; kix < nkeys; kix++) { 918 - key = rcu_dereference(keylist->keys[kix]); 919 - kflags = key->flags; 920 - 921 - /* ignore keys not of this type */ 922 - if (key->type != type) 923 - continue; 924 - 925 - /* skip invalidated, revoked and expired keys */ 926 - if (!no_state_check) { 927 - if (kflags & ((1 << KEY_FLAG_INVALIDATED) | 928 - (1 << KEY_FLAG_REVOKED))) 929 - continue; 930 - 931 - if (key->expiry && now.tv_sec >= key->expiry) 932 - continue; 933 - } 934 - 935 - /* keys that don't match */ 936 - if (!match(key, description)) 937 - continue; 938 - 939 - /* key must have search permissions */ 940 - if (key_task_permission(make_key_ref(key, possessed), 941 - cred, KEY_SEARCH) < 0) 942 - continue; 943 - 944 - if (no_state_check) 945 - goto found; 946 - 947 - /* we set a different error code if we pass a negative key */ 948 - if (kflags & (1 << KEY_FLAG_NEGATIVE)) { 949 - err = key->type_data.reject_error; 950 - continue; 951 - } 952 - 953 - goto found; 954 - } 955 - 956 - /* search through the keyrings nested in this one */ 957 - kix = 0; 958 - ascend: 959 - nkeys = keylist->nkeys; 960 - smp_rmb(); 961 - for (; kix < nkeys; kix++) { 962 - key = rcu_dereference(keylist->keys[kix]); 963 - if (key->type != &key_type_keyring) 964 - continue; 965 - 966 - /* recursively search nested keyrings 967 - * - only search keyrings for which we have search permission 968 - */ 969 - if (sp >= KEYRING_SEARCH_MAX_DEPTH) 970 - continue; 971 - 972 - if (key_task_permission(make_key_ref(key, possessed), 973 - cred, KEY_SEARCH) < 0) 974 - continue; 975 - 976 - /* stack the current position */ 977 - stack[sp].keyring = keyring; 978 - stack[sp].keylist = keylist; 979 - stack[sp].kix = kix; 980 - sp++; 981 - 982 - /* begin again with the new keyring */ 983 - keyring = key; 984 - goto descend; 985 - } 986 - 987 - /* the keyring we're looking at was disqualified or didn't contain a 988 - * matching key */ 989 - not_this_keyring: 990 - if (sp > 0) { 991 - /* resume the processing of a keyring higher up in the tree */ 992 - sp--; 993 - keyring = stack[sp].keyring; 994 - keylist = stack[sp].keylist; 995 - kix = stack[sp].kix + 1; 996 - goto ascend; 997 - } 998 - 999 - key_ref = ERR_PTR(err); 1000 - goto error_2; 1001 - 1002 - /* we found a viable match */ 1003 - found: 1004 - atomic_inc(&key->usage); 1005 - key->last_used_at = now.tv_sec; 1006 - keyring->last_used_at = now.tv_sec; 1007 - while (sp > 0) 1008 - stack[--sp].keyring->last_used_at = now.tv_sec; 1009 - key_check(key); 1010 - key_ref = make_key_ref(key, possessed); 1011 - error_2: 339 + ctx->now = current_kernel_time(); 340 + if (search_nested_keyrings(keyring, ctx)) 341 + __key_get(key_ref_to_ptr(ctx->result)); 1012 342 rcu_read_unlock(); 1013 - error: 1014 - return key_ref; 343 + return ctx->result; 1015 344 } 1016 345 1017 346 /** ··· 864 507 * @description: The name of the keyring we want to find. 865 508 * 866 509 * As keyring_search_aux() above, but using the current task's credentials and 867 - * type's default matching function. 510 + * type's default matching function and preferred search method. 868 511 */ 869 512 key_ref_t keyring_search(key_ref_t keyring, 870 513 struct key_type *type, 871 514 const char *description) 872 515 { 873 - if (!type->match) 516 + struct keyring_search_context ctx = { 517 + .index_key.type = type, 518 + .index_key.description = description, 519 + .cred = current_cred(), 520 + .match = type->match, 521 + .match_data = description, 522 + .flags = (type->def_lookup_type | 523 + KEYRING_SEARCH_DO_STATE_CHECK), 524 + }; 525 + 526 + if (!ctx.match) 874 527 return ERR_PTR(-ENOKEY); 875 528 876 - return keyring_search_aux(keyring, current->cred, 877 - type, description, type->match, false); 529 + return keyring_search_aux(keyring, &ctx); 878 530 } 879 531 EXPORT_SYMBOL(keyring_search); 880 532 881 533 /* 882 - * Search the given keyring only (no recursion). 534 + * Search the given keyring for a key that might be updated. 883 535 * 884 536 * The caller must guarantee that the keyring is a keyring and that the 885 - * permission is granted to search the keyring as no check is made here. 886 - * 887 - * RCU is used to make it unnecessary to lock the keyring key list here. 537 + * permission is granted to modify the keyring as no check is made here. The 538 + * caller must also hold a lock on the keyring semaphore. 888 539 * 889 540 * Returns a pointer to the found key with usage count incremented if 890 - * successful and returns -ENOKEY if not found. Revoked keys and keys not 891 - * providing the requested permission are skipped over. 541 + * successful and returns NULL if not found. Revoked and invalidated keys are 542 + * skipped over. 892 543 * 893 544 * If successful, the possession indicator is propagated from the keyring ref 894 545 * to the returned key reference. 895 546 */ 896 - key_ref_t __keyring_search_one(key_ref_t keyring_ref, 897 - const struct key_type *ktype, 898 - const char *description, 899 - key_perm_t perm) 547 + key_ref_t find_key_to_update(key_ref_t keyring_ref, 548 + const struct keyring_index_key *index_key) 900 549 { 901 - struct keyring_list *klist; 902 - unsigned long possessed; 903 550 struct key *keyring, *key; 904 - int nkeys, loop; 551 + const void *object; 905 552 906 553 keyring = key_ref_to_ptr(keyring_ref); 907 - possessed = is_key_possessed(keyring_ref); 908 554 909 - rcu_read_lock(); 555 + kenter("{%d},{%s,%s}", 556 + keyring->serial, index_key->type->name, index_key->description); 910 557 911 - klist = rcu_dereference(keyring->payload.subscriptions); 912 - if (klist) { 913 - nkeys = klist->nkeys; 914 - smp_rmb(); 915 - for (loop = 0; loop < nkeys ; loop++) { 916 - key = rcu_dereference(klist->keys[loop]); 917 - if (key->type == ktype && 918 - (!key->type->match || 919 - key->type->match(key, description)) && 920 - key_permission(make_key_ref(key, possessed), 921 - perm) == 0 && 922 - !(key->flags & ((1 << KEY_FLAG_INVALIDATED) | 923 - (1 << KEY_FLAG_REVOKED))) 924 - ) 925 - goto found; 926 - } 927 - } 558 + object = assoc_array_find(&keyring->keys, &keyring_assoc_array_ops, 559 + index_key); 928 560 929 - rcu_read_unlock(); 930 - return ERR_PTR(-ENOKEY); 561 + if (object) 562 + goto found; 563 + 564 + kleave(" = NULL"); 565 + return NULL; 931 566 932 567 found: 933 - atomic_inc(&key->usage); 934 - keyring->last_used_at = key->last_used_at = 935 - current_kernel_time().tv_sec; 936 - rcu_read_unlock(); 937 - return make_key_ref(key, possessed); 568 + key = keyring_ptr_to_key(object); 569 + if (key->flags & ((1 << KEY_FLAG_INVALIDATED) | 570 + (1 << KEY_FLAG_REVOKED))) { 571 + kleave(" = NULL [x]"); 572 + return NULL; 573 + } 574 + __key_get(key); 575 + kleave(" = {%d}", key->serial); 576 + return make_key_ref(key, is_key_possessed(keyring_ref)); 938 577 } 939 578 940 579 /* ··· 993 640 return keyring; 994 641 } 995 642 643 + static int keyring_detect_cycle_iterator(const void *object, 644 + void *iterator_data) 645 + { 646 + struct keyring_search_context *ctx = iterator_data; 647 + const struct key *key = keyring_ptr_to_key(object); 648 + 649 + kenter("{%d}", key->serial); 650 + 651 + BUG_ON(key != ctx->match_data); 652 + ctx->result = ERR_PTR(-EDEADLK); 653 + return 1; 654 + } 655 + 996 656 /* 997 657 * See if a cycle will will be created by inserting acyclic tree B in acyclic 998 658 * tree A at the topmost level (ie: as a direct child of A). ··· 1015 649 */ 1016 650 static int keyring_detect_cycle(struct key *A, struct key *B) 1017 651 { 1018 - struct { 1019 - struct keyring_list *keylist; 1020 - int kix; 1021 - } stack[KEYRING_SEARCH_MAX_DEPTH]; 1022 - 1023 - struct keyring_list *keylist; 1024 - struct key *subtree, *key; 1025 - int sp, nkeys, kix, ret; 652 + struct keyring_search_context ctx = { 653 + .index_key = A->index_key, 654 + .match_data = A, 655 + .iterator = keyring_detect_cycle_iterator, 656 + .flags = (KEYRING_SEARCH_LOOKUP_DIRECT | 657 + KEYRING_SEARCH_NO_STATE_CHECK | 658 + KEYRING_SEARCH_NO_UPDATE_TIME | 659 + KEYRING_SEARCH_NO_CHECK_PERM | 660 + KEYRING_SEARCH_DETECT_TOO_DEEP), 661 + }; 1026 662 1027 663 rcu_read_lock(); 1028 - 1029 - ret = -EDEADLK; 1030 - if (A == B) 1031 - goto cycle_detected; 1032 - 1033 - subtree = B; 1034 - sp = 0; 1035 - 1036 - /* start processing a new keyring */ 1037 - descend: 1038 - if (test_bit(KEY_FLAG_REVOKED, &subtree->flags)) 1039 - goto not_this_keyring; 1040 - 1041 - keylist = rcu_dereference(subtree->payload.subscriptions); 1042 - if (!keylist) 1043 - goto not_this_keyring; 1044 - kix = 0; 1045 - 1046 - ascend: 1047 - /* iterate through the remaining keys in this keyring */ 1048 - nkeys = keylist->nkeys; 1049 - smp_rmb(); 1050 - for (; kix < nkeys; kix++) { 1051 - key = rcu_dereference(keylist->keys[kix]); 1052 - 1053 - if (key == A) 1054 - goto cycle_detected; 1055 - 1056 - /* recursively check nested keyrings */ 1057 - if (key->type == &key_type_keyring) { 1058 - if (sp >= KEYRING_SEARCH_MAX_DEPTH) 1059 - goto too_deep; 1060 - 1061 - /* stack the current position */ 1062 - stack[sp].keylist = keylist; 1063 - stack[sp].kix = kix; 1064 - sp++; 1065 - 1066 - /* begin again with the new keyring */ 1067 - subtree = key; 1068 - goto descend; 1069 - } 1070 - } 1071 - 1072 - /* the keyring we're looking at was disqualified or didn't contain a 1073 - * matching key */ 1074 - not_this_keyring: 1075 - if (sp > 0) { 1076 - /* resume the checking of a keyring higher up in the tree */ 1077 - sp--; 1078 - keylist = stack[sp].keylist; 1079 - kix = stack[sp].kix + 1; 1080 - goto ascend; 1081 - } 1082 - 1083 - ret = 0; /* no cycles detected */ 1084 - 1085 - error: 664 + search_nested_keyrings(B, &ctx); 1086 665 rcu_read_unlock(); 1087 - return ret; 1088 - 1089 - too_deep: 1090 - ret = -ELOOP; 1091 - goto error; 1092 - 1093 - cycle_detected: 1094 - ret = -EDEADLK; 1095 - goto error; 1096 - } 1097 - 1098 - /* 1099 - * Dispose of a keyring list after the RCU grace period, freeing the unlinked 1100 - * key 1101 - */ 1102 - static void keyring_unlink_rcu_disposal(struct rcu_head *rcu) 1103 - { 1104 - struct keyring_list *klist = 1105 - container_of(rcu, struct keyring_list, rcu); 1106 - 1107 - if (klist->delkey != USHRT_MAX) 1108 - key_put(rcu_access_pointer(klist->keys[klist->delkey])); 1109 - kfree(klist); 666 + return PTR_ERR(ctx.result) == -EAGAIN ? 0 : PTR_ERR(ctx.result); 1110 667 } 1111 668 1112 669 /* 1113 670 * Preallocate memory so that a key can be linked into to a keyring. 1114 671 */ 1115 - int __key_link_begin(struct key *keyring, const struct key_type *type, 1116 - const char *description, unsigned long *_prealloc) 672 + int __key_link_begin(struct key *keyring, 673 + const struct keyring_index_key *index_key, 674 + struct assoc_array_edit **_edit) 1117 675 __acquires(&keyring->sem) 1118 676 __acquires(&keyring_serialise_link_sem) 1119 677 { 1120 - struct keyring_list *klist, *nklist; 1121 - unsigned long prealloc; 1122 - unsigned max; 1123 - time_t lowest_lru; 1124 - size_t size; 1125 - int loop, lru, ret; 678 + struct assoc_array_edit *edit; 679 + int ret; 1126 680 1127 - kenter("%d,%s,%s,", key_serial(keyring), type->name, description); 681 + kenter("%d,%s,%s,", 682 + keyring->serial, index_key->type->name, index_key->description); 683 + 684 + BUG_ON(index_key->desc_len == 0); 1128 685 1129 686 if (keyring->type != &key_type_keyring) 1130 687 return -ENOTDIR; ··· 1060 771 1061 772 /* serialise link/link calls to prevent parallel calls causing a cycle 1062 773 * when linking two keyring in opposite orders */ 1063 - if (type == &key_type_keyring) 774 + if (index_key->type == &key_type_keyring) 1064 775 down_write(&keyring_serialise_link_sem); 1065 776 1066 - klist = rcu_dereference_locked_keyring(keyring); 1067 - 1068 - /* see if there's a matching key we can displace */ 1069 - lru = -1; 1070 - if (klist && klist->nkeys > 0) { 1071 - lowest_lru = TIME_T_MAX; 1072 - for (loop = klist->nkeys - 1; loop >= 0; loop--) { 1073 - struct key *key = rcu_deref_link_locked(klist, loop, 1074 - keyring); 1075 - if (key->type == type && 1076 - strcmp(key->description, description) == 0) { 1077 - /* Found a match - we'll replace the link with 1078 - * one to the new key. We record the slot 1079 - * position. 1080 - */ 1081 - klist->delkey = loop; 1082 - prealloc = 0; 1083 - goto done; 1084 - } 1085 - if (key->last_used_at < lowest_lru) { 1086 - lowest_lru = key->last_used_at; 1087 - lru = loop; 1088 - } 1089 - } 1090 - } 1091 - 1092 - /* If the keyring is full then do an LRU discard */ 1093 - if (klist && 1094 - klist->nkeys == klist->maxkeys && 1095 - klist->maxkeys >= MAX_KEYRING_LINKS) { 1096 - kdebug("LRU discard %d\n", lru); 1097 - klist->delkey = lru; 1098 - prealloc = 0; 1099 - goto done; 1100 - } 1101 - 1102 - /* check that we aren't going to overrun the user's quota */ 1103 - ret = key_payload_reserve(keyring, 1104 - keyring->datalen + KEYQUOTA_LINK_BYTES); 1105 - if (ret < 0) 777 + /* Create an edit script that will insert/replace the key in the 778 + * keyring tree. 779 + */ 780 + edit = assoc_array_insert(&keyring->keys, 781 + &keyring_assoc_array_ops, 782 + index_key, 783 + NULL); 784 + if (IS_ERR(edit)) { 785 + ret = PTR_ERR(edit); 1106 786 goto error_sem; 1107 - 1108 - if (klist && klist->nkeys < klist->maxkeys) { 1109 - /* there's sufficient slack space to append directly */ 1110 - klist->delkey = klist->nkeys; 1111 - prealloc = KEY_LINK_FIXQUOTA; 1112 - } else { 1113 - /* grow the key list */ 1114 - max = 4; 1115 - if (klist) { 1116 - max += klist->maxkeys; 1117 - if (max > MAX_KEYRING_LINKS) 1118 - max = MAX_KEYRING_LINKS; 1119 - BUG_ON(max <= klist->maxkeys); 1120 - } 1121 - 1122 - size = sizeof(*klist) + sizeof(struct key *) * max; 1123 - 1124 - ret = -ENOMEM; 1125 - nklist = kmalloc(size, GFP_KERNEL); 1126 - if (!nklist) 1127 - goto error_quota; 1128 - 1129 - nklist->maxkeys = max; 1130 - if (klist) { 1131 - memcpy(nklist->keys, klist->keys, 1132 - sizeof(struct key *) * klist->nkeys); 1133 - nklist->delkey = klist->nkeys; 1134 - nklist->nkeys = klist->nkeys + 1; 1135 - klist->delkey = USHRT_MAX; 1136 - } else { 1137 - nklist->nkeys = 1; 1138 - nklist->delkey = 0; 1139 - } 1140 - 1141 - /* add the key into the new space */ 1142 - RCU_INIT_POINTER(nklist->keys[nklist->delkey], NULL); 1143 - prealloc = (unsigned long)nklist | KEY_LINK_FIXQUOTA; 1144 787 } 1145 788 1146 - done: 1147 - *_prealloc = prealloc; 789 + /* If we're not replacing a link in-place then we're going to need some 790 + * extra quota. 791 + */ 792 + if (!edit->dead_leaf) { 793 + ret = key_payload_reserve(keyring, 794 + keyring->datalen + KEYQUOTA_LINK_BYTES); 795 + if (ret < 0) 796 + goto error_cancel; 797 + } 798 + 799 + *_edit = edit; 1148 800 kleave(" = 0"); 1149 801 return 0; 1150 802 1151 - error_quota: 1152 - /* undo the quota changes */ 1153 - key_payload_reserve(keyring, 1154 - keyring->datalen - KEYQUOTA_LINK_BYTES); 803 + error_cancel: 804 + assoc_array_cancel_edit(edit); 1155 805 error_sem: 1156 - if (type == &key_type_keyring) 806 + if (index_key->type == &key_type_keyring) 1157 807 up_write(&keyring_serialise_link_sem); 1158 808 error_krsem: 1159 809 up_write(&keyring->sem); ··· 1123 895 * holds at most one link to any given key of a particular type+description 1124 896 * combination. 1125 897 */ 1126 - void __key_link(struct key *keyring, struct key *key, 1127 - unsigned long *_prealloc) 898 + void __key_link(struct key *key, struct assoc_array_edit **_edit) 1128 899 { 1129 - struct keyring_list *klist, *nklist; 1130 - struct key *discard; 1131 - 1132 - nklist = (struct keyring_list *)(*_prealloc & ~KEY_LINK_FIXQUOTA); 1133 - *_prealloc = 0; 1134 - 1135 - kenter("%d,%d,%p", keyring->serial, key->serial, nklist); 1136 - 1137 - klist = rcu_dereference_locked_keyring(keyring); 1138 - 1139 - atomic_inc(&key->usage); 1140 - keyring->last_used_at = key->last_used_at = 1141 - current_kernel_time().tv_sec; 1142 - 1143 - /* there's a matching key we can displace or an empty slot in a newly 1144 - * allocated list we can fill */ 1145 - if (nklist) { 1146 - kdebug("reissue %hu/%hu/%hu", 1147 - nklist->delkey, nklist->nkeys, nklist->maxkeys); 1148 - 1149 - RCU_INIT_POINTER(nklist->keys[nklist->delkey], key); 1150 - 1151 - rcu_assign_pointer(keyring->payload.subscriptions, nklist); 1152 - 1153 - /* dispose of the old keyring list and, if there was one, the 1154 - * displaced key */ 1155 - if (klist) { 1156 - kdebug("dispose %hu/%hu/%hu", 1157 - klist->delkey, klist->nkeys, klist->maxkeys); 1158 - call_rcu(&klist->rcu, keyring_unlink_rcu_disposal); 1159 - } 1160 - } else if (klist->delkey < klist->nkeys) { 1161 - kdebug("replace %hu/%hu/%hu", 1162 - klist->delkey, klist->nkeys, klist->maxkeys); 1163 - 1164 - discard = rcu_dereference_protected( 1165 - klist->keys[klist->delkey], 1166 - rwsem_is_locked(&keyring->sem)); 1167 - rcu_assign_pointer(klist->keys[klist->delkey], key); 1168 - /* The garbage collector will take care of RCU 1169 - * synchronisation */ 1170 - key_put(discard); 1171 - } else { 1172 - /* there's sufficient slack space to append directly */ 1173 - kdebug("append %hu/%hu/%hu", 1174 - klist->delkey, klist->nkeys, klist->maxkeys); 1175 - 1176 - RCU_INIT_POINTER(klist->keys[klist->delkey], key); 1177 - smp_wmb(); 1178 - klist->nkeys++; 1179 - } 900 + __key_get(key); 901 + assoc_array_insert_set_object(*_edit, keyring_key_to_ptr(key)); 902 + assoc_array_apply_edit(*_edit); 903 + *_edit = NULL; 1180 904 } 1181 905 1182 906 /* ··· 1136 956 * 1137 957 * Must be called with __key_link_begin() having being called. 1138 958 */ 1139 - void __key_link_end(struct key *keyring, struct key_type *type, 1140 - unsigned long prealloc) 959 + void __key_link_end(struct key *keyring, 960 + const struct keyring_index_key *index_key, 961 + struct assoc_array_edit *edit) 1141 962 __releases(&keyring->sem) 1142 963 __releases(&keyring_serialise_link_sem) 1143 964 { 1144 - BUG_ON(type == NULL); 1145 - BUG_ON(type->name == NULL); 1146 - kenter("%d,%s,%lx", keyring->serial, type->name, prealloc); 965 + BUG_ON(index_key->type == NULL); 966 + kenter("%d,%s,", keyring->serial, index_key->type->name); 1147 967 1148 - if (type == &key_type_keyring) 968 + if (index_key->type == &key_type_keyring) 1149 969 up_write(&keyring_serialise_link_sem); 1150 970 1151 - if (prealloc) { 1152 - if (prealloc & KEY_LINK_FIXQUOTA) 1153 - key_payload_reserve(keyring, 1154 - keyring->datalen - 1155 - KEYQUOTA_LINK_BYTES); 1156 - kfree((struct keyring_list *)(prealloc & ~KEY_LINK_FIXQUOTA)); 971 + if (edit && !edit->dead_leaf) { 972 + key_payload_reserve(keyring, 973 + keyring->datalen - KEYQUOTA_LINK_BYTES); 974 + assoc_array_cancel_edit(edit); 1157 975 } 1158 976 up_write(&keyring->sem); 1159 977 } ··· 1178 1000 */ 1179 1001 int key_link(struct key *keyring, struct key *key) 1180 1002 { 1181 - unsigned long prealloc; 1003 + struct assoc_array_edit *edit; 1182 1004 int ret; 1005 + 1006 + kenter("{%d,%d}", keyring->serial, atomic_read(&keyring->usage)); 1183 1007 1184 1008 key_check(keyring); 1185 1009 key_check(key); 1186 1010 1187 - ret = __key_link_begin(keyring, key->type, key->description, &prealloc); 1011 + if (test_bit(KEY_FLAG_TRUSTED_ONLY, &keyring->flags) && 1012 + !test_bit(KEY_FLAG_TRUSTED, &key->flags)) 1013 + return -EPERM; 1014 + 1015 + ret = __key_link_begin(keyring, &key->index_key, &edit); 1188 1016 if (ret == 0) { 1017 + kdebug("begun {%d,%d}", keyring->serial, atomic_read(&keyring->usage)); 1189 1018 ret = __key_link_check_live_key(keyring, key); 1190 1019 if (ret == 0) 1191 - __key_link(keyring, key, &prealloc); 1192 - __key_link_end(keyring, key->type, prealloc); 1020 + __key_link(key, &edit); 1021 + __key_link_end(keyring, &key->index_key, edit); 1193 1022 } 1194 1023 1024 + kleave(" = %d {%d,%d}", ret, keyring->serial, atomic_read(&keyring->usage)); 1195 1025 return ret; 1196 1026 } 1197 1027 EXPORT_SYMBOL(key_link); ··· 1223 1037 */ 1224 1038 int key_unlink(struct key *keyring, struct key *key) 1225 1039 { 1226 - struct keyring_list *klist, *nklist; 1227 - int loop, ret; 1040 + struct assoc_array_edit *edit; 1041 + int ret; 1228 1042 1229 1043 key_check(keyring); 1230 1044 key_check(key); 1231 1045 1232 - ret = -ENOTDIR; 1233 1046 if (keyring->type != &key_type_keyring) 1234 - goto error; 1047 + return -ENOTDIR; 1235 1048 1236 1049 down_write(&keyring->sem); 1237 1050 1238 - klist = rcu_dereference_locked_keyring(keyring); 1239 - if (klist) { 1240 - /* search the keyring for the key */ 1241 - for (loop = 0; loop < klist->nkeys; loop++) 1242 - if (rcu_access_pointer(klist->keys[loop]) == key) 1243 - goto key_is_present; 1051 + edit = assoc_array_delete(&keyring->keys, &keyring_assoc_array_ops, 1052 + &key->index_key); 1053 + if (IS_ERR(edit)) { 1054 + ret = PTR_ERR(edit); 1055 + goto error; 1244 1056 } 1245 - 1246 - up_write(&keyring->sem); 1247 1057 ret = -ENOENT; 1248 - goto error; 1058 + if (edit == NULL) 1059 + goto error; 1249 1060 1250 - key_is_present: 1251 - /* we need to copy the key list for RCU purposes */ 1252 - nklist = kmalloc(sizeof(*klist) + 1253 - sizeof(struct key *) * klist->maxkeys, 1254 - GFP_KERNEL); 1255 - if (!nklist) 1256 - goto nomem; 1257 - nklist->maxkeys = klist->maxkeys; 1258 - nklist->nkeys = klist->nkeys - 1; 1259 - 1260 - if (loop > 0) 1261 - memcpy(&nklist->keys[0], 1262 - &klist->keys[0], 1263 - loop * sizeof(struct key *)); 1264 - 1265 - if (loop < nklist->nkeys) 1266 - memcpy(&nklist->keys[loop], 1267 - &klist->keys[loop + 1], 1268 - (nklist->nkeys - loop) * sizeof(struct key *)); 1269 - 1270 - /* adjust the user's quota */ 1271 - key_payload_reserve(keyring, 1272 - keyring->datalen - KEYQUOTA_LINK_BYTES); 1273 - 1274 - rcu_assign_pointer(keyring->payload.subscriptions, nklist); 1275 - 1276 - up_write(&keyring->sem); 1277 - 1278 - /* schedule for later cleanup */ 1279 - klist->delkey = loop; 1280 - call_rcu(&klist->rcu, keyring_unlink_rcu_disposal); 1281 - 1061 + assoc_array_apply_edit(edit); 1062 + key_payload_reserve(keyring, keyring->datalen - KEYQUOTA_LINK_BYTES); 1282 1063 ret = 0; 1283 1064 1284 1065 error: 1285 - return ret; 1286 - nomem: 1287 - ret = -ENOMEM; 1288 1066 up_write(&keyring->sem); 1289 - goto error; 1067 + return ret; 1290 1068 } 1291 1069 EXPORT_SYMBOL(key_unlink); 1292 - 1293 - /* 1294 - * Dispose of a keyring list after the RCU grace period, releasing the keys it 1295 - * links to. 1296 - */ 1297 - static void keyring_clear_rcu_disposal(struct rcu_head *rcu) 1298 - { 1299 - struct keyring_list *klist; 1300 - int loop; 1301 - 1302 - klist = container_of(rcu, struct keyring_list, rcu); 1303 - 1304 - for (loop = klist->nkeys - 1; loop >= 0; loop--) 1305 - key_put(rcu_access_pointer(klist->keys[loop])); 1306 - 1307 - kfree(klist); 1308 - } 1309 1070 1310 1071 /** 1311 1072 * keyring_clear - Clear a keyring ··· 1264 1131 */ 1265 1132 int keyring_clear(struct key *keyring) 1266 1133 { 1267 - struct keyring_list *klist; 1134 + struct assoc_array_edit *edit; 1268 1135 int ret; 1269 1136 1270 - ret = -ENOTDIR; 1271 - if (keyring->type == &key_type_keyring) { 1272 - /* detach the pointer block with the locks held */ 1273 - down_write(&keyring->sem); 1137 + if (keyring->type != &key_type_keyring) 1138 + return -ENOTDIR; 1274 1139 1275 - klist = rcu_dereference_locked_keyring(keyring); 1276 - if (klist) { 1277 - /* adjust the quota */ 1278 - key_payload_reserve(keyring, 1279 - sizeof(struct keyring_list)); 1140 + down_write(&keyring->sem); 1280 1141 1281 - rcu_assign_pointer(keyring->payload.subscriptions, 1282 - NULL); 1283 - } 1284 - 1285 - up_write(&keyring->sem); 1286 - 1287 - /* free the keys after the locks have been dropped */ 1288 - if (klist) 1289 - call_rcu(&klist->rcu, keyring_clear_rcu_disposal); 1290 - 1142 + edit = assoc_array_clear(&keyring->keys, &keyring_assoc_array_ops); 1143 + if (IS_ERR(edit)) { 1144 + ret = PTR_ERR(edit); 1145 + } else { 1146 + if (edit) 1147 + assoc_array_apply_edit(edit); 1148 + key_payload_reserve(keyring, 0); 1291 1149 ret = 0; 1292 1150 } 1293 1151 1152 + up_write(&keyring->sem); 1294 1153 return ret; 1295 1154 } 1296 1155 EXPORT_SYMBOL(keyring_clear); ··· 1294 1169 */ 1295 1170 static void keyring_revoke(struct key *keyring) 1296 1171 { 1297 - struct keyring_list *klist; 1172 + struct assoc_array_edit *edit; 1298 1173 1299 - klist = rcu_dereference_locked_keyring(keyring); 1300 - 1301 - /* adjust the quota */ 1302 - key_payload_reserve(keyring, 0); 1303 - 1304 - if (klist) { 1305 - rcu_assign_pointer(keyring->payload.subscriptions, NULL); 1306 - call_rcu(&klist->rcu, keyring_clear_rcu_disposal); 1174 + edit = assoc_array_clear(&keyring->keys, &keyring_assoc_array_ops); 1175 + if (!IS_ERR(edit)) { 1176 + if (edit) 1177 + assoc_array_apply_edit(edit); 1178 + key_payload_reserve(keyring, 0); 1307 1179 } 1308 1180 } 1309 1181 1182 + static bool keyring_gc_select_iterator(void *object, void *iterator_data) 1183 + { 1184 + struct key *key = keyring_ptr_to_key(object); 1185 + time_t *limit = iterator_data; 1186 + 1187 + if (key_is_dead(key, *limit)) 1188 + return false; 1189 + key_get(key); 1190 + return true; 1191 + } 1192 + 1193 + static int keyring_gc_check_iterator(const void *object, void *iterator_data) 1194 + { 1195 + const struct key *key = keyring_ptr_to_key(object); 1196 + time_t *limit = iterator_data; 1197 + 1198 + key_check(key); 1199 + return key_is_dead(key, *limit); 1200 + } 1201 + 1310 1202 /* 1311 - * Collect garbage from the contents of a keyring, replacing the old list with 1312 - * a new one with the pointers all shuffled down. 1203 + * Garbage collect pointers from a keyring. 1313 1204 * 1314 - * Dead keys are classed as oned that are flagged as being dead or are revoked, 1315 - * expired or negative keys that were revoked or expired before the specified 1316 - * limit. 1205 + * Not called with any locks held. The keyring's key struct will not be 1206 + * deallocated under us as only our caller may deallocate it. 1317 1207 */ 1318 1208 void keyring_gc(struct key *keyring, time_t limit) 1319 1209 { 1320 - struct keyring_list *klist, *new; 1321 - struct key *key; 1322 - int loop, keep, max; 1210 + int result; 1323 1211 1324 - kenter("{%x,%s}", key_serial(keyring), keyring->description); 1212 + kenter("%x{%s}", keyring->serial, keyring->description ?: ""); 1325 1213 1214 + if (keyring->flags & ((1 << KEY_FLAG_INVALIDATED) | 1215 + (1 << KEY_FLAG_REVOKED))) 1216 + goto dont_gc; 1217 + 1218 + /* scan the keyring looking for dead keys */ 1219 + rcu_read_lock(); 1220 + result = assoc_array_iterate(&keyring->keys, 1221 + keyring_gc_check_iterator, &limit); 1222 + rcu_read_unlock(); 1223 + if (result == true) 1224 + goto do_gc; 1225 + 1226 + dont_gc: 1227 + kleave(" [no gc]"); 1228 + return; 1229 + 1230 + do_gc: 1326 1231 down_write(&keyring->sem); 1327 - 1328 - klist = rcu_dereference_locked_keyring(keyring); 1329 - if (!klist) 1330 - goto no_klist; 1331 - 1332 - /* work out how many subscriptions we're keeping */ 1333 - keep = 0; 1334 - for (loop = klist->nkeys - 1; loop >= 0; loop--) 1335 - if (!key_is_dead(rcu_deref_link_locked(klist, loop, keyring), 1336 - limit)) 1337 - keep++; 1338 - 1339 - if (keep == klist->nkeys) 1340 - goto just_return; 1341 - 1342 - /* allocate a new keyring payload */ 1343 - max = roundup(keep, 4); 1344 - new = kmalloc(sizeof(struct keyring_list) + max * sizeof(struct key *), 1345 - GFP_KERNEL); 1346 - if (!new) 1347 - goto nomem; 1348 - new->maxkeys = max; 1349 - new->nkeys = 0; 1350 - new->delkey = 0; 1351 - 1352 - /* install the live keys 1353 - * - must take care as expired keys may be updated back to life 1354 - */ 1355 - keep = 0; 1356 - for (loop = klist->nkeys - 1; loop >= 0; loop--) { 1357 - key = rcu_deref_link_locked(klist, loop, keyring); 1358 - if (!key_is_dead(key, limit)) { 1359 - if (keep >= max) 1360 - goto discard_new; 1361 - RCU_INIT_POINTER(new->keys[keep++], key_get(key)); 1362 - } 1363 - } 1364 - new->nkeys = keep; 1365 - 1366 - /* adjust the quota */ 1367 - key_payload_reserve(keyring, 1368 - sizeof(struct keyring_list) + 1369 - KEYQUOTA_LINK_BYTES * keep); 1370 - 1371 - if (keep == 0) { 1372 - rcu_assign_pointer(keyring->payload.subscriptions, NULL); 1373 - kfree(new); 1374 - } else { 1375 - rcu_assign_pointer(keyring->payload.subscriptions, new); 1376 - } 1377 - 1232 + assoc_array_gc(&keyring->keys, &keyring_assoc_array_ops, 1233 + keyring_gc_select_iterator, &limit); 1378 1234 up_write(&keyring->sem); 1379 - 1380 - call_rcu(&klist->rcu, keyring_clear_rcu_disposal); 1381 - kleave(" [yes]"); 1382 - return; 1383 - 1384 - discard_new: 1385 - new->nkeys = keep; 1386 - keyring_clear_rcu_disposal(&new->rcu); 1387 - up_write(&keyring->sem); 1388 - kleave(" [discard]"); 1389 - return; 1390 - 1391 - just_return: 1392 - up_write(&keyring->sem); 1393 - kleave(" [no dead]"); 1394 - return; 1395 - 1396 - no_klist: 1397 - up_write(&keyring->sem); 1398 - kleave(" [no_klist]"); 1399 - return; 1400 - 1401 - nomem: 1402 - up_write(&keyring->sem); 1403 - kleave(" [oom]"); 1235 + kleave(" [gc]"); 1404 1236 }
+167
security/keys/persistent.c
··· 1 + /* General persistent per-UID keyrings register 2 + * 3 + * Copyright (C) 2013 Red Hat, Inc. All Rights Reserved. 4 + * Written by David Howells (dhowells@redhat.com) 5 + * 6 + * This program is free software; you can redistribute it and/or 7 + * modify it under the terms of the GNU General Public Licence 8 + * as published by the Free Software Foundation; either version 9 + * 2 of the Licence, or (at your option) any later version. 10 + */ 11 + 12 + #include <linux/user_namespace.h> 13 + #include "internal.h" 14 + 15 + unsigned persistent_keyring_expiry = 3 * 24 * 3600; /* Expire after 3 days of non-use */ 16 + 17 + /* 18 + * Create the persistent keyring register for the current user namespace. 19 + * 20 + * Called with the namespace's sem locked for writing. 21 + */ 22 + static int key_create_persistent_register(struct user_namespace *ns) 23 + { 24 + struct key *reg = keyring_alloc(".persistent_register", 25 + KUIDT_INIT(0), KGIDT_INIT(0), 26 + current_cred(), 27 + ((KEY_POS_ALL & ~KEY_POS_SETATTR) | 28 + KEY_USR_VIEW | KEY_USR_READ), 29 + KEY_ALLOC_NOT_IN_QUOTA, NULL); 30 + if (IS_ERR(reg)) 31 + return PTR_ERR(reg); 32 + 33 + ns->persistent_keyring_register = reg; 34 + return 0; 35 + } 36 + 37 + /* 38 + * Create the persistent keyring for the specified user. 39 + * 40 + * Called with the namespace's sem locked for writing. 41 + */ 42 + static key_ref_t key_create_persistent(struct user_namespace *ns, kuid_t uid, 43 + struct keyring_index_key *index_key) 44 + { 45 + struct key *persistent; 46 + key_ref_t reg_ref, persistent_ref; 47 + 48 + if (!ns->persistent_keyring_register) { 49 + long err = key_create_persistent_register(ns); 50 + if (err < 0) 51 + return ERR_PTR(err); 52 + } else { 53 + reg_ref = make_key_ref(ns->persistent_keyring_register, true); 54 + persistent_ref = find_key_to_update(reg_ref, index_key); 55 + if (persistent_ref) 56 + return persistent_ref; 57 + } 58 + 59 + persistent = keyring_alloc(index_key->description, 60 + uid, INVALID_GID, current_cred(), 61 + ((KEY_POS_ALL & ~KEY_POS_SETATTR) | 62 + KEY_USR_VIEW | KEY_USR_READ), 63 + KEY_ALLOC_NOT_IN_QUOTA, 64 + ns->persistent_keyring_register); 65 + if (IS_ERR(persistent)) 66 + return ERR_CAST(persistent); 67 + 68 + return make_key_ref(persistent, true); 69 + } 70 + 71 + /* 72 + * Get the persistent keyring for a specific UID and link it to the nominated 73 + * keyring. 74 + */ 75 + static long key_get_persistent(struct user_namespace *ns, kuid_t uid, 76 + key_ref_t dest_ref) 77 + { 78 + struct keyring_index_key index_key; 79 + struct key *persistent; 80 + key_ref_t reg_ref, persistent_ref; 81 + char buf[32]; 82 + long ret; 83 + 84 + /* Look in the register if it exists */ 85 + index_key.type = &key_type_keyring; 86 + index_key.description = buf; 87 + index_key.desc_len = sprintf(buf, "_persistent.%u", from_kuid(ns, uid)); 88 + 89 + if (ns->persistent_keyring_register) { 90 + reg_ref = make_key_ref(ns->persistent_keyring_register, true); 91 + down_read(&ns->persistent_keyring_register_sem); 92 + persistent_ref = find_key_to_update(reg_ref, &index_key); 93 + up_read(&ns->persistent_keyring_register_sem); 94 + 95 + if (persistent_ref) 96 + goto found; 97 + } 98 + 99 + /* It wasn't in the register, so we'll need to create it. We might 100 + * also need to create the register. 101 + */ 102 + down_write(&ns->persistent_keyring_register_sem); 103 + persistent_ref = key_create_persistent(ns, uid, &index_key); 104 + up_write(&ns->persistent_keyring_register_sem); 105 + if (!IS_ERR(persistent_ref)) 106 + goto found; 107 + 108 + return PTR_ERR(persistent_ref); 109 + 110 + found: 111 + ret = key_task_permission(persistent_ref, current_cred(), KEY_LINK); 112 + if (ret == 0) { 113 + persistent = key_ref_to_ptr(persistent_ref); 114 + ret = key_link(key_ref_to_ptr(dest_ref), persistent); 115 + if (ret == 0) { 116 + key_set_timeout(persistent, persistent_keyring_expiry); 117 + ret = persistent->serial; 118 + } 119 + } 120 + 121 + key_ref_put(persistent_ref); 122 + return ret; 123 + } 124 + 125 + /* 126 + * Get the persistent keyring for a specific UID and link it to the nominated 127 + * keyring. 128 + */ 129 + long keyctl_get_persistent(uid_t _uid, key_serial_t destid) 130 + { 131 + struct user_namespace *ns = current_user_ns(); 132 + key_ref_t dest_ref; 133 + kuid_t uid; 134 + long ret; 135 + 136 + /* -1 indicates the current user */ 137 + if (_uid == (uid_t)-1) { 138 + uid = current_uid(); 139 + } else { 140 + uid = make_kuid(ns, _uid); 141 + if (!uid_valid(uid)) 142 + return -EINVAL; 143 + 144 + /* You can only see your own persistent cache if you're not 145 + * sufficiently privileged. 146 + */ 147 + if (!uid_eq(uid, current_uid()) && 148 + !uid_eq(uid, current_euid()) && 149 + !ns_capable(ns, CAP_SETUID)) 150 + return -EPERM; 151 + } 152 + 153 + /* There must be a destination keyring */ 154 + dest_ref = lookup_user_key(destid, KEY_LOOKUP_CREATE, KEY_WRITE); 155 + if (IS_ERR(dest_ref)) 156 + return PTR_ERR(dest_ref); 157 + if (key_ref_to_ptr(dest_ref)->type != &key_type_keyring) { 158 + ret = -ENOTDIR; 159 + goto out_put_dest; 160 + } 161 + 162 + ret = key_get_persistent(ns, uid, dest_ref); 163 + 164 + out_put_dest: 165 + key_ref_put(dest_ref); 166 + return ret; 167 + }
+12 -5
security/keys/proc.c
··· 182 182 183 183 static int proc_keys_show(struct seq_file *m, void *v) 184 184 { 185 - const struct cred *cred = current_cred(); 186 185 struct rb_node *_p = v; 187 186 struct key *key = rb_entry(_p, struct key, serial_node); 188 187 struct timespec now; ··· 190 191 char xbuf[12]; 191 192 int rc; 192 193 194 + struct keyring_search_context ctx = { 195 + .index_key.type = key->type, 196 + .index_key.description = key->description, 197 + .cred = current_cred(), 198 + .match = lookup_user_key_possessed, 199 + .match_data = key, 200 + .flags = (KEYRING_SEARCH_NO_STATE_CHECK | 201 + KEYRING_SEARCH_LOOKUP_DIRECT), 202 + }; 203 + 193 204 key_ref = make_key_ref(key, 0); 194 205 195 206 /* determine if the key is possessed by this process (a test we can 196 207 * skip if the key does not indicate the possessor can view it 197 208 */ 198 209 if (key->perm & KEY_POS_VIEW) { 199 - skey_ref = search_my_process_keyrings(key->type, key, 200 - lookup_user_key_possessed, 201 - true, cred); 210 + skey_ref = search_my_process_keyrings(&ctx); 202 211 if (!IS_ERR(skey_ref)) { 203 212 key_ref_put(skey_ref); 204 213 key_ref = make_key_ref(key, 1); ··· 218 211 * - the caller holds a spinlock, and thus the RCU read lock, making our 219 212 * access to __current_cred() safe 220 213 */ 221 - rc = key_task_permission(key_ref, cred, KEY_VIEW); 214 + rc = key_task_permission(key_ref, ctx.cred, KEY_VIEW); 222 215 if (rc < 0) 223 216 return 0; 224 217
+76 -65
security/keys/process_keys.c
··· 235 235 if (IS_ERR(keyring)) 236 236 return PTR_ERR(keyring); 237 237 } else { 238 - atomic_inc(&keyring->usage); 238 + __key_get(keyring); 239 239 } 240 240 241 241 /* install the keyring */ ··· 319 319 * In the case of a successful return, the possession attribute is set on the 320 320 * returned key reference. 321 321 */ 322 - key_ref_t search_my_process_keyrings(struct key_type *type, 323 - const void *description, 324 - key_match_func_t match, 325 - bool no_state_check, 326 - const struct cred *cred) 322 + key_ref_t search_my_process_keyrings(struct keyring_search_context *ctx) 327 323 { 328 324 key_ref_t key_ref, ret, err; 329 325 ··· 335 339 err = ERR_PTR(-EAGAIN); 336 340 337 341 /* search the thread keyring first */ 338 - if (cred->thread_keyring) { 342 + if (ctx->cred->thread_keyring) { 339 343 key_ref = keyring_search_aux( 340 - make_key_ref(cred->thread_keyring, 1), 341 - cred, type, description, match, no_state_check); 344 + make_key_ref(ctx->cred->thread_keyring, 1), ctx); 342 345 if (!IS_ERR(key_ref)) 343 346 goto found; 344 347 ··· 353 358 } 354 359 355 360 /* search the process keyring second */ 356 - if (cred->process_keyring) { 361 + if (ctx->cred->process_keyring) { 357 362 key_ref = keyring_search_aux( 358 - make_key_ref(cred->process_keyring, 1), 359 - cred, type, description, match, no_state_check); 363 + make_key_ref(ctx->cred->process_keyring, 1), ctx); 360 364 if (!IS_ERR(key_ref)) 361 365 goto found; 362 366 ··· 373 379 } 374 380 375 381 /* search the session keyring */ 376 - if (cred->session_keyring) { 382 + if (ctx->cred->session_keyring) { 377 383 rcu_read_lock(); 378 384 key_ref = keyring_search_aux( 379 - make_key_ref(rcu_dereference(cred->session_keyring), 1), 380 - cred, type, description, match, no_state_check); 385 + make_key_ref(rcu_dereference(ctx->cred->session_keyring), 1), 386 + ctx); 381 387 rcu_read_unlock(); 382 388 383 389 if (!IS_ERR(key_ref)) ··· 396 402 } 397 403 } 398 404 /* or search the user-session keyring */ 399 - else if (cred->user->session_keyring) { 405 + else if (ctx->cred->user->session_keyring) { 400 406 key_ref = keyring_search_aux( 401 - make_key_ref(cred->user->session_keyring, 1), 402 - cred, type, description, match, no_state_check); 407 + make_key_ref(ctx->cred->user->session_keyring, 1), 408 + ctx); 403 409 if (!IS_ERR(key_ref)) 404 410 goto found; 405 411 ··· 431 437 * 432 438 * Return same as search_my_process_keyrings(). 433 439 */ 434 - key_ref_t search_process_keyrings(struct key_type *type, 435 - const void *description, 436 - key_match_func_t match, 437 - const struct cred *cred) 440 + key_ref_t search_process_keyrings(struct keyring_search_context *ctx) 438 441 { 439 442 struct request_key_auth *rka; 440 443 key_ref_t key_ref, ret = ERR_PTR(-EACCES), err; 441 444 442 445 might_sleep(); 443 446 444 - key_ref = search_my_process_keyrings(type, description, match, 445 - false, cred); 447 + key_ref = search_my_process_keyrings(ctx); 446 448 if (!IS_ERR(key_ref)) 447 449 goto found; 448 450 err = key_ref; ··· 447 457 * search the keyrings of the process mentioned there 448 458 * - we don't permit access to request_key auth keys via this method 449 459 */ 450 - if (cred->request_key_auth && 451 - cred == current_cred() && 452 - type != &key_type_request_key_auth 460 + if (ctx->cred->request_key_auth && 461 + ctx->cred == current_cred() && 462 + ctx->index_key.type != &key_type_request_key_auth 453 463 ) { 464 + const struct cred *cred = ctx->cred; 465 + 454 466 /* defend against the auth key being revoked */ 455 467 down_read(&cred->request_key_auth->sem); 456 468 457 - if (key_validate(cred->request_key_auth) == 0) { 458 - rka = cred->request_key_auth->payload.data; 469 + if (key_validate(ctx->cred->request_key_auth) == 0) { 470 + rka = ctx->cred->request_key_auth->payload.data; 459 471 460 - key_ref = search_process_keyrings(type, description, 461 - match, rka->cred); 472 + ctx->cred = rka->cred; 473 + key_ref = search_process_keyrings(ctx); 474 + ctx->cred = cred; 462 475 463 476 up_read(&cred->request_key_auth->sem); 464 477 ··· 515 522 key_ref_t lookup_user_key(key_serial_t id, unsigned long lflags, 516 523 key_perm_t perm) 517 524 { 525 + struct keyring_search_context ctx = { 526 + .match = lookup_user_key_possessed, 527 + .flags = (KEYRING_SEARCH_NO_STATE_CHECK | 528 + KEYRING_SEARCH_LOOKUP_DIRECT), 529 + }; 518 530 struct request_key_auth *rka; 519 - const struct cred *cred; 520 531 struct key *key; 521 532 key_ref_t key_ref, skey_ref; 522 533 int ret; 523 534 524 535 try_again: 525 - cred = get_current_cred(); 536 + ctx.cred = get_current_cred(); 526 537 key_ref = ERR_PTR(-ENOKEY); 527 538 528 539 switch (id) { 529 540 case KEY_SPEC_THREAD_KEYRING: 530 - if (!cred->thread_keyring) { 541 + if (!ctx.cred->thread_keyring) { 531 542 if (!(lflags & KEY_LOOKUP_CREATE)) 532 543 goto error; 533 544 ··· 543 546 goto reget_creds; 544 547 } 545 548 546 - key = cred->thread_keyring; 547 - atomic_inc(&key->usage); 549 + key = ctx.cred->thread_keyring; 550 + __key_get(key); 548 551 key_ref = make_key_ref(key, 1); 549 552 break; 550 553 551 554 case KEY_SPEC_PROCESS_KEYRING: 552 - if (!cred->process_keyring) { 555 + if (!ctx.cred->process_keyring) { 553 556 if (!(lflags & KEY_LOOKUP_CREATE)) 554 557 goto error; 555 558 ··· 561 564 goto reget_creds; 562 565 } 563 566 564 - key = cred->process_keyring; 565 - atomic_inc(&key->usage); 567 + key = ctx.cred->process_keyring; 568 + __key_get(key); 566 569 key_ref = make_key_ref(key, 1); 567 570 break; 568 571 569 572 case KEY_SPEC_SESSION_KEYRING: 570 - if (!cred->session_keyring) { 573 + if (!ctx.cred->session_keyring) { 571 574 /* always install a session keyring upon access if one 572 575 * doesn't exist yet */ 573 576 ret = install_user_keyrings(); ··· 577 580 ret = join_session_keyring(NULL); 578 581 else 579 582 ret = install_session_keyring( 580 - cred->user->session_keyring); 583 + ctx.cred->user->session_keyring); 581 584 582 585 if (ret < 0) 583 586 goto error; 584 587 goto reget_creds; 585 - } else if (cred->session_keyring == 586 - cred->user->session_keyring && 588 + } else if (ctx.cred->session_keyring == 589 + ctx.cred->user->session_keyring && 587 590 lflags & KEY_LOOKUP_CREATE) { 588 591 ret = join_session_keyring(NULL); 589 592 if (ret < 0) ··· 592 595 } 593 596 594 597 rcu_read_lock(); 595 - key = rcu_dereference(cred->session_keyring); 596 - atomic_inc(&key->usage); 598 + key = rcu_dereference(ctx.cred->session_keyring); 599 + __key_get(key); 597 600 rcu_read_unlock(); 598 601 key_ref = make_key_ref(key, 1); 599 602 break; 600 603 601 604 case KEY_SPEC_USER_KEYRING: 602 - if (!cred->user->uid_keyring) { 605 + if (!ctx.cred->user->uid_keyring) { 603 606 ret = install_user_keyrings(); 604 607 if (ret < 0) 605 608 goto error; 606 609 } 607 610 608 - key = cred->user->uid_keyring; 609 - atomic_inc(&key->usage); 611 + key = ctx.cred->user->uid_keyring; 612 + __key_get(key); 610 613 key_ref = make_key_ref(key, 1); 611 614 break; 612 615 613 616 case KEY_SPEC_USER_SESSION_KEYRING: 614 - if (!cred->user->session_keyring) { 617 + if (!ctx.cred->user->session_keyring) { 615 618 ret = install_user_keyrings(); 616 619 if (ret < 0) 617 620 goto error; 618 621 } 619 622 620 - key = cred->user->session_keyring; 621 - atomic_inc(&key->usage); 623 + key = ctx.cred->user->session_keyring; 624 + __key_get(key); 622 625 key_ref = make_key_ref(key, 1); 623 626 break; 624 627 ··· 628 631 goto error; 629 632 630 633 case KEY_SPEC_REQKEY_AUTH_KEY: 631 - key = cred->request_key_auth; 634 + key = ctx.cred->request_key_auth; 632 635 if (!key) 633 636 goto error; 634 637 635 - atomic_inc(&key->usage); 638 + __key_get(key); 636 639 key_ref = make_key_ref(key, 1); 637 640 break; 638 641 639 642 case KEY_SPEC_REQUESTOR_KEYRING: 640 - if (!cred->request_key_auth) 643 + if (!ctx.cred->request_key_auth) 641 644 goto error; 642 645 643 - down_read(&cred->request_key_auth->sem); 646 + down_read(&ctx.cred->request_key_auth->sem); 644 647 if (test_bit(KEY_FLAG_REVOKED, 645 - &cred->request_key_auth->flags)) { 648 + &ctx.cred->request_key_auth->flags)) { 646 649 key_ref = ERR_PTR(-EKEYREVOKED); 647 650 key = NULL; 648 651 } else { 649 - rka = cred->request_key_auth->payload.data; 652 + rka = ctx.cred->request_key_auth->payload.data; 650 653 key = rka->dest_keyring; 651 - atomic_inc(&key->usage); 654 + __key_get(key); 652 655 } 653 - up_read(&cred->request_key_auth->sem); 656 + up_read(&ctx.cred->request_key_auth->sem); 654 657 if (!key) 655 658 goto error; 656 659 key_ref = make_key_ref(key, 1); ··· 670 673 key_ref = make_key_ref(key, 0); 671 674 672 675 /* check to see if we possess the key */ 673 - skey_ref = search_process_keyrings(key->type, key, 674 - lookup_user_key_possessed, 675 - cred); 676 + ctx.index_key.type = key->type; 677 + ctx.index_key.description = key->description; 678 + ctx.index_key.desc_len = strlen(key->description); 679 + ctx.match_data = key; 680 + kdebug("check possessed"); 681 + skey_ref = search_process_keyrings(&ctx); 682 + kdebug("possessed=%p", skey_ref); 676 683 677 684 if (!IS_ERR(skey_ref)) { 678 685 key_put(key); ··· 716 715 goto invalid_key; 717 716 718 717 /* check the permissions */ 719 - ret = key_task_permission(key_ref, cred, perm); 718 + ret = key_task_permission(key_ref, ctx.cred, perm); 720 719 if (ret < 0) 721 720 goto invalid_key; 722 721 723 722 key->last_used_at = current_kernel_time().tv_sec; 724 723 725 724 error: 726 - put_cred(cred); 725 + put_cred(ctx.cred); 727 726 return key_ref; 728 727 729 728 invalid_key: ··· 734 733 /* if we attempted to install a keyring, then it may have caused new 735 734 * creds to be installed */ 736 735 reget_creds: 737 - put_cred(cred); 736 + put_cred(ctx.cred); 738 737 goto try_again; 739 738 } 740 739 ··· 857 856 858 857 commit_creds(new); 859 858 } 859 + 860 + /* 861 + * Make sure that root's user and user-session keyrings exist. 862 + */ 863 + static int __init init_root_keyring(void) 864 + { 865 + return install_user_keyrings(); 866 + } 867 + 868 + late_initcall(init_root_keyring);
+33 -27
security/keys/request_key.c
··· 345 345 * May return a key that's already under construction instead if there was a 346 346 * race between two thread calling request_key(). 347 347 */ 348 - static int construct_alloc_key(struct key_type *type, 349 - const char *description, 348 + static int construct_alloc_key(struct keyring_search_context *ctx, 350 349 struct key *dest_keyring, 351 350 unsigned long flags, 352 351 struct key_user *user, 353 352 struct key **_key) 354 353 { 355 - const struct cred *cred = current_cred(); 356 - unsigned long prealloc; 354 + struct assoc_array_edit *edit; 357 355 struct key *key; 358 356 key_perm_t perm; 359 357 key_ref_t key_ref; 360 358 int ret; 361 359 362 - kenter("%s,%s,,,", type->name, description); 360 + kenter("%s,%s,,,", 361 + ctx->index_key.type->name, ctx->index_key.description); 363 362 364 363 *_key = NULL; 365 364 mutex_lock(&user->cons_lock); 366 365 367 366 perm = KEY_POS_VIEW | KEY_POS_SEARCH | KEY_POS_LINK | KEY_POS_SETATTR; 368 367 perm |= KEY_USR_VIEW; 369 - if (type->read) 368 + if (ctx->index_key.type->read) 370 369 perm |= KEY_POS_READ; 371 - if (type == &key_type_keyring || type->update) 370 + if (ctx->index_key.type == &key_type_keyring || 371 + ctx->index_key.type->update) 372 372 perm |= KEY_POS_WRITE; 373 373 374 - key = key_alloc(type, description, cred->fsuid, cred->fsgid, cred, 374 + key = key_alloc(ctx->index_key.type, ctx->index_key.description, 375 + ctx->cred->fsuid, ctx->cred->fsgid, ctx->cred, 375 376 perm, flags); 376 377 if (IS_ERR(key)) 377 378 goto alloc_failed; ··· 380 379 set_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags); 381 380 382 381 if (dest_keyring) { 383 - ret = __key_link_begin(dest_keyring, type, description, 384 - &prealloc); 382 + ret = __key_link_begin(dest_keyring, &ctx->index_key, &edit); 385 383 if (ret < 0) 386 384 goto link_prealloc_failed; 387 385 } ··· 390 390 * waited for locks */ 391 391 mutex_lock(&key_construction_mutex); 392 392 393 - key_ref = search_process_keyrings(type, description, type->match, cred); 393 + key_ref = search_process_keyrings(ctx); 394 394 if (!IS_ERR(key_ref)) 395 395 goto key_already_present; 396 396 397 397 if (dest_keyring) 398 - __key_link(dest_keyring, key, &prealloc); 398 + __key_link(key, &edit); 399 399 400 400 mutex_unlock(&key_construction_mutex); 401 401 if (dest_keyring) 402 - __key_link_end(dest_keyring, type, prealloc); 402 + __key_link_end(dest_keyring, &ctx->index_key, edit); 403 403 mutex_unlock(&user->cons_lock); 404 404 *_key = key; 405 405 kleave(" = 0 [%d]", key_serial(key)); ··· 414 414 if (dest_keyring) { 415 415 ret = __key_link_check_live_key(dest_keyring, key); 416 416 if (ret == 0) 417 - __key_link(dest_keyring, key, &prealloc); 418 - __key_link_end(dest_keyring, type, prealloc); 417 + __key_link(key, &edit); 418 + __key_link_end(dest_keyring, &ctx->index_key, edit); 419 419 if (ret < 0) 420 420 goto link_check_failed; 421 421 } ··· 444 444 /* 445 445 * Commence key construction. 446 446 */ 447 - static struct key *construct_key_and_link(struct key_type *type, 448 - const char *description, 447 + static struct key *construct_key_and_link(struct keyring_search_context *ctx, 449 448 const char *callout_info, 450 449 size_t callout_len, 451 450 void *aux, ··· 463 464 464 465 construct_get_dest_keyring(&dest_keyring); 465 466 466 - ret = construct_alloc_key(type, description, dest_keyring, flags, user, 467 - &key); 467 + ret = construct_alloc_key(ctx, dest_keyring, flags, user, &key); 468 468 key_user_put(user); 469 469 470 470 if (ret == 0) { ··· 527 529 struct key *dest_keyring, 528 530 unsigned long flags) 529 531 { 530 - const struct cred *cred = current_cred(); 532 + struct keyring_search_context ctx = { 533 + .index_key.type = type, 534 + .index_key.description = description, 535 + .cred = current_cred(), 536 + .match = type->match, 537 + .match_data = description, 538 + .flags = KEYRING_SEARCH_LOOKUP_DIRECT, 539 + }; 531 540 struct key *key; 532 541 key_ref_t key_ref; 533 542 int ret; 534 543 535 544 kenter("%s,%s,%p,%zu,%p,%p,%lx", 536 - type->name, description, callout_info, callout_len, aux, 537 - dest_keyring, flags); 545 + ctx.index_key.type->name, ctx.index_key.description, 546 + callout_info, callout_len, aux, dest_keyring, flags); 538 547 539 548 /* search all the process keyrings for a key */ 540 - key_ref = search_process_keyrings(type, description, type->match, cred); 549 + key_ref = search_process_keyrings(&ctx); 541 550 542 551 if (!IS_ERR(key_ref)) { 543 552 key = key_ref_to_ptr(key_ref); ··· 567 562 if (!callout_info) 568 563 goto error; 569 564 570 - key = construct_key_and_link(type, description, callout_info, 571 - callout_len, aux, dest_keyring, 572 - flags); 565 + key = construct_key_and_link(&ctx, callout_info, callout_len, 566 + aux, dest_keyring, flags); 573 567 } 574 568 575 569 error: ··· 596 592 intr ? TASK_INTERRUPTIBLE : TASK_UNINTERRUPTIBLE); 597 593 if (ret < 0) 598 594 return ret; 599 - if (test_bit(KEY_FLAG_NEGATIVE, &key->flags)) 595 + if (test_bit(KEY_FLAG_NEGATIVE, &key->flags)) { 596 + smp_rmb(); 600 597 return key->type_data.reject_error; 598 + } 601 599 return key_validate(key); 602 600 } 603 601 EXPORT_SYMBOL(wait_for_key_construction);
+13 -18
security/keys/request_key_auth.c
··· 18 18 #include <linux/slab.h> 19 19 #include <asm/uaccess.h> 20 20 #include "internal.h" 21 + #include <keys/user-type.h> 21 22 22 23 static int request_key_auth_instantiate(struct key *, 23 24 struct key_preparsed_payload *); ··· 223 222 } 224 223 225 224 /* 226 - * See if an authorisation key is associated with a particular key. 227 - */ 228 - static int key_get_instantiation_authkey_match(const struct key *key, 229 - const void *_id) 230 - { 231 - struct request_key_auth *rka = key->payload.data; 232 - key_serial_t id = (key_serial_t)(unsigned long) _id; 233 - 234 - return rka->target_key->serial == id; 235 - } 236 - 237 - /* 238 225 * Search the current process's keyrings for the authorisation key for 239 226 * instantiation of a key. 240 227 */ 241 228 struct key *key_get_instantiation_authkey(key_serial_t target_id) 242 229 { 243 - const struct cred *cred = current_cred(); 230 + char description[16]; 231 + struct keyring_search_context ctx = { 232 + .index_key.type = &key_type_request_key_auth, 233 + .index_key.description = description, 234 + .cred = current_cred(), 235 + .match = user_match, 236 + .match_data = description, 237 + .flags = KEYRING_SEARCH_LOOKUP_DIRECT, 238 + }; 244 239 struct key *authkey; 245 240 key_ref_t authkey_ref; 246 241 247 - authkey_ref = search_process_keyrings( 248 - &key_type_request_key_auth, 249 - (void *) (unsigned long) target_id, 250 - key_get_instantiation_authkey_match, 251 - cred); 242 + sprintf(description, "%x", target_id); 243 + 244 + authkey_ref = search_process_keyrings(&ctx); 252 245 253 246 if (IS_ERR(authkey_ref)) { 254 247 authkey = ERR_CAST(authkey_ref);
+11
security/keys/sysctl.c
··· 61 61 .extra1 = (void *) &zero, 62 62 .extra2 = (void *) &max, 63 63 }, 64 + #ifdef CONFIG_PERSISTENT_KEYRINGS 65 + { 66 + .procname = "persistent_keyring_expiry", 67 + .data = &persistent_keyring_expiry, 68 + .maxlen = sizeof(unsigned), 69 + .mode = 0644, 70 + .proc_handler = proc_dointvec_minmax, 71 + .extra1 = (void *) &zero, 72 + .extra2 = (void *) &max, 73 + }, 74 + #endif 64 75 { } 65 76 };
+10 -8
security/keys/user_defined.c
··· 25 25 * arbitrary blob of data as the payload 26 26 */ 27 27 struct key_type key_type_user = { 28 - .name = "user", 29 - .instantiate = user_instantiate, 30 - .update = user_update, 31 - .match = user_match, 32 - .revoke = user_revoke, 33 - .destroy = user_destroy, 34 - .describe = user_describe, 35 - .read = user_read, 28 + .name = "user", 29 + .def_lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT, 30 + .instantiate = user_instantiate, 31 + .update = user_update, 32 + .match = user_match, 33 + .revoke = user_revoke, 34 + .destroy = user_destroy, 35 + .describe = user_describe, 36 + .read = user_read, 36 37 }; 37 38 38 39 EXPORT_SYMBOL_GPL(key_type_user); ··· 46 45 */ 47 46 struct key_type key_type_logon = { 48 47 .name = "logon", 48 + .def_lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT, 49 49 .instantiate = user_instantiate, 50 50 .update = user_update, 51 51 .match = user_match,
+4 -9
security/security.c
··· 1340 1340 return security_ops->xfrm_policy_delete_security(ctx); 1341 1341 } 1342 1342 1343 - int security_xfrm_state_alloc(struct xfrm_state *x, struct xfrm_user_sec_ctx *sec_ctx) 1343 + int security_xfrm_state_alloc(struct xfrm_state *x, 1344 + struct xfrm_user_sec_ctx *sec_ctx) 1344 1345 { 1345 - return security_ops->xfrm_state_alloc_security(x, sec_ctx, 0); 1346 + return security_ops->xfrm_state_alloc(x, sec_ctx); 1346 1347 } 1347 1348 EXPORT_SYMBOL(security_xfrm_state_alloc); 1348 1349 1349 1350 int security_xfrm_state_alloc_acquire(struct xfrm_state *x, 1350 1351 struct xfrm_sec_ctx *polsec, u32 secid) 1351 1352 { 1352 - if (!polsec) 1353 - return 0; 1354 - /* 1355 - * We want the context to be taken from secid which is usually 1356 - * from the sock. 1357 - */ 1358 - return security_ops->xfrm_state_alloc_security(x, NULL, secid); 1353 + return security_ops->xfrm_state_alloc_acquire(x, polsec, secid); 1359 1354 } 1360 1355 1361 1356 int security_xfrm_state_delete(struct xfrm_state *x)
+94 -52
security/selinux/hooks.c
··· 95 95 #include "audit.h" 96 96 #include "avc_ss.h" 97 97 98 - #define NUM_SEL_MNT_OPTS 5 98 + #define SB_TYPE_FMT "%s%s%s" 99 + #define SB_SUBTYPE(sb) (sb->s_subtype && sb->s_subtype[0]) 100 + #define SB_TYPE_ARGS(sb) sb->s_type->name, SB_SUBTYPE(sb) ? "." : "", SB_SUBTYPE(sb) ? sb->s_subtype : "" 99 101 100 102 extern struct security_operations *security_ops; 101 103 ··· 141 139 * This function checks the SECMARK reference counter to see if any SECMARK 142 140 * targets are currently configured, if the reference counter is greater than 143 141 * zero SECMARK is considered to be enabled. Returns true (1) if SECMARK is 144 - * enabled, false (0) if SECMARK is disabled. 142 + * enabled, false (0) if SECMARK is disabled. If the always_check_network 143 + * policy capability is enabled, SECMARK is always considered enabled. 145 144 * 146 145 */ 147 146 static int selinux_secmark_enabled(void) 148 147 { 149 - return (atomic_read(&selinux_secmark_refcount) > 0); 148 + return (selinux_policycap_alwaysnetwork || atomic_read(&selinux_secmark_refcount)); 149 + } 150 + 151 + /** 152 + * selinux_peerlbl_enabled - Check to see if peer labeling is currently enabled 153 + * 154 + * Description: 155 + * This function checks if NetLabel or labeled IPSEC is enabled. Returns true 156 + * (1) if any are enabled or false (0) if neither are enabled. If the 157 + * always_check_network policy capability is enabled, peer labeling 158 + * is always considered enabled. 159 + * 160 + */ 161 + static int selinux_peerlbl_enabled(void) 162 + { 163 + return (selinux_policycap_alwaysnetwork || netlbl_enabled() || selinux_xfrm_enabled()); 150 164 } 151 165 152 166 /* ··· 327 309 Opt_defcontext = 3, 328 310 Opt_rootcontext = 4, 329 311 Opt_labelsupport = 5, 312 + Opt_nextmntopt = 6, 330 313 }; 314 + 315 + #define NUM_SEL_MNT_OPTS (Opt_nextmntopt - 1) 331 316 332 317 static const match_table_t tokens = { 333 318 {Opt_context, CONTEXT_STR "%s"}, ··· 376 355 return rc; 377 356 } 378 357 358 + static int selinux_is_sblabel_mnt(struct super_block *sb) 359 + { 360 + struct superblock_security_struct *sbsec = sb->s_security; 361 + 362 + if (sbsec->behavior == SECURITY_FS_USE_XATTR || 363 + sbsec->behavior == SECURITY_FS_USE_TRANS || 364 + sbsec->behavior == SECURITY_FS_USE_TASK) 365 + return 1; 366 + 367 + /* Special handling for sysfs. Is genfs but also has setxattr handler*/ 368 + if (strncmp(sb->s_type->name, "sysfs", sizeof("sysfs")) == 0) 369 + return 1; 370 + 371 + /* 372 + * Special handling for rootfs. Is genfs but supports 373 + * setting SELinux context on in-core inodes. 374 + */ 375 + if (strncmp(sb->s_type->name, "rootfs", sizeof("rootfs")) == 0) 376 + return 1; 377 + 378 + return 0; 379 + } 380 + 379 381 static int sb_finish_set_opts(struct super_block *sb) 380 382 { 381 383 struct superblock_security_struct *sbsec = sb->s_security; ··· 413 369 the first boot of the SELinux kernel before we have 414 370 assigned xattr values to the filesystem. */ 415 371 if (!root_inode->i_op->getxattr) { 416 - printk(KERN_WARNING "SELinux: (dev %s, type %s) has no " 417 - "xattr support\n", sb->s_id, sb->s_type->name); 372 + printk(KERN_WARNING "SELinux: (dev %s, type "SB_TYPE_FMT") has no " 373 + "xattr support\n", sb->s_id, SB_TYPE_ARGS(sb)); 418 374 rc = -EOPNOTSUPP; 419 375 goto out; 420 376 } ··· 422 378 if (rc < 0 && rc != -ENODATA) { 423 379 if (rc == -EOPNOTSUPP) 424 380 printk(KERN_WARNING "SELinux: (dev %s, type " 425 - "%s) has no security xattr handler\n", 426 - sb->s_id, sb->s_type->name); 381 + SB_TYPE_FMT") has no security xattr handler\n", 382 + sb->s_id, SB_TYPE_ARGS(sb)); 427 383 else 428 384 printk(KERN_WARNING "SELinux: (dev %s, type " 429 - "%s) getxattr errno %d\n", sb->s_id, 430 - sb->s_type->name, -rc); 385 + SB_TYPE_FMT") getxattr errno %d\n", sb->s_id, 386 + SB_TYPE_ARGS(sb), -rc); 431 387 goto out; 432 388 } 433 389 } 434 390 435 - sbsec->flags |= (SE_SBINITIALIZED | SE_SBLABELSUPP); 436 - 437 391 if (sbsec->behavior > ARRAY_SIZE(labeling_behaviors)) 438 - printk(KERN_ERR "SELinux: initialized (dev %s, type %s), unknown behavior\n", 439 - sb->s_id, sb->s_type->name); 392 + printk(KERN_ERR "SELinux: initialized (dev %s, type "SB_TYPE_FMT"), unknown behavior\n", 393 + sb->s_id, SB_TYPE_ARGS(sb)); 440 394 else 441 - printk(KERN_DEBUG "SELinux: initialized (dev %s, type %s), %s\n", 442 - sb->s_id, sb->s_type->name, 395 + printk(KERN_DEBUG "SELinux: initialized (dev %s, type "SB_TYPE_FMT"), %s\n", 396 + sb->s_id, SB_TYPE_ARGS(sb), 443 397 labeling_behaviors[sbsec->behavior-1]); 444 398 445 - if (sbsec->behavior == SECURITY_FS_USE_GENFS || 446 - sbsec->behavior == SECURITY_FS_USE_MNTPOINT || 447 - sbsec->behavior == SECURITY_FS_USE_NONE || 448 - sbsec->behavior > ARRAY_SIZE(labeling_behaviors)) 449 - sbsec->flags &= ~SE_SBLABELSUPP; 450 - 451 - /* Special handling for sysfs. Is genfs but also has setxattr handler*/ 452 - if (strncmp(sb->s_type->name, "sysfs", sizeof("sysfs")) == 0) 453 - sbsec->flags |= SE_SBLABELSUPP; 399 + sbsec->flags |= SE_SBINITIALIZED; 400 + if (selinux_is_sblabel_mnt(sb)) 401 + sbsec->flags |= SBLABEL_MNT; 454 402 455 403 /* Initialize the root inode. */ 456 404 rc = inode_doinit_with_dentry(root_inode, root); ··· 496 460 if (!ss_initialized) 497 461 return -EINVAL; 498 462 463 + /* make sure we always check enough bits to cover the mask */ 464 + BUILD_BUG_ON(SE_MNTMASK >= (1 << NUM_SEL_MNT_OPTS)); 465 + 499 466 tmp = sbsec->flags & SE_MNTMASK; 500 467 /* count the number of mount options for this sb */ 501 - for (i = 0; i < 8; i++) { 468 + for (i = 0; i < NUM_SEL_MNT_OPTS; i++) { 502 469 if (tmp & 0x01) 503 470 opts->num_mnt_opts++; 504 471 tmp >>= 1; 505 472 } 506 473 /* Check if the Label support flag is set */ 507 - if (sbsec->flags & SE_SBLABELSUPP) 474 + if (sbsec->flags & SBLABEL_MNT) 508 475 opts->num_mnt_opts++; 509 476 510 477 opts->mnt_opts = kcalloc(opts->num_mnt_opts, sizeof(char *), GFP_ATOMIC); ··· 554 515 opts->mnt_opts[i] = context; 555 516 opts->mnt_opts_flags[i++] = ROOTCONTEXT_MNT; 556 517 } 557 - if (sbsec->flags & SE_SBLABELSUPP) { 518 + if (sbsec->flags & SBLABEL_MNT) { 558 519 opts->mnt_opts[i] = NULL; 559 - opts->mnt_opts_flags[i++] = SE_SBLABELSUPP; 520 + opts->mnt_opts_flags[i++] = SBLABEL_MNT; 560 521 } 561 522 562 523 BUG_ON(i != opts->num_mnt_opts); ··· 600 561 const struct cred *cred = current_cred(); 601 562 int rc = 0, i; 602 563 struct superblock_security_struct *sbsec = sb->s_security; 603 - const char *name = sb->s_type->name; 604 564 struct inode *inode = sbsec->sb->s_root->d_inode; 605 565 struct inode_security_struct *root_isec = inode->i_security; 606 566 u32 fscontext_sid = 0, context_sid = 0, rootcontext_sid = 0; ··· 652 614 for (i = 0; i < num_opts; i++) { 653 615 u32 sid; 654 616 655 - if (flags[i] == SE_SBLABELSUPP) 617 + if (flags[i] == SBLABEL_MNT) 656 618 continue; 657 619 rc = security_context_to_sid(mount_options[i], 658 620 strlen(mount_options[i]), &sid); 659 621 if (rc) { 660 622 printk(KERN_WARNING "SELinux: security_context_to_sid" 661 - "(%s) failed for (dev %s, type %s) errno=%d\n", 662 - mount_options[i], sb->s_id, name, rc); 623 + "(%s) failed for (dev %s, type "SB_TYPE_FMT") errno=%d\n", 624 + mount_options[i], sb->s_id, SB_TYPE_ARGS(sb), rc); 663 625 goto out; 664 626 } 665 627 switch (flags[i]) { ··· 723 685 * Determine the labeling behavior to use for this 724 686 * filesystem type. 725 687 */ 726 - rc = security_fs_use((sbsec->flags & SE_SBPROC) ? 727 - "proc" : sb->s_type->name, 728 - &sbsec->behavior, &sbsec->sid); 688 + rc = security_fs_use(sb); 729 689 if (rc) { 730 690 printk(KERN_WARNING 731 691 "%s: security_fs_use(%s) returned %d\n", ··· 806 770 out_double_mount: 807 771 rc = -EINVAL; 808 772 printk(KERN_WARNING "SELinux: mount invalid. Same superblock, different " 809 - "security settings for (dev %s, type %s)\n", sb->s_id, name); 773 + "security settings for (dev %s, type "SB_TYPE_FMT")\n", sb->s_id, 774 + SB_TYPE_ARGS(sb)); 810 775 goto out; 811 776 } 812 777 ··· 1074 1037 case DEFCONTEXT_MNT: 1075 1038 prefix = DEFCONTEXT_STR; 1076 1039 break; 1077 - case SE_SBLABELSUPP: 1040 + case SBLABEL_MNT: 1078 1041 seq_putc(m, ','); 1079 1042 seq_puts(m, LABELSUPP_STR); 1080 1043 continue; ··· 1686 1649 if (rc) 1687 1650 return rc; 1688 1651 1689 - if (!newsid || !(sbsec->flags & SE_SBLABELSUPP)) { 1652 + if (!newsid || !(sbsec->flags & SBLABEL_MNT)) { 1690 1653 rc = security_transition_sid(sid, dsec->sid, tclass, 1691 1654 &dentry->d_name, &newsid); 1692 1655 if (rc) ··· 2474 2437 u32 sid; 2475 2438 size_t len; 2476 2439 2477 - if (flags[i] == SE_SBLABELSUPP) 2440 + if (flags[i] == SBLABEL_MNT) 2478 2441 continue; 2479 2442 len = strlen(mount_options[i]); 2480 2443 rc = security_context_to_sid(mount_options[i], len, &sid); 2481 2444 if (rc) { 2482 2445 printk(KERN_WARNING "SELinux: security_context_to_sid" 2483 - "(%s) failed for (dev %s, type %s) errno=%d\n", 2484 - mount_options[i], sb->s_id, sb->s_type->name, rc); 2446 + "(%s) failed for (dev %s, type "SB_TYPE_FMT") errno=%d\n", 2447 + mount_options[i], sb->s_id, SB_TYPE_ARGS(sb), rc); 2485 2448 goto out_free_opts; 2486 2449 } 2487 2450 rc = -EINVAL; ··· 2519 2482 return rc; 2520 2483 out_bad_option: 2521 2484 printk(KERN_WARNING "SELinux: unable to change security options " 2522 - "during remount (dev %s, type=%s)\n", sb->s_id, 2523 - sb->s_type->name); 2485 + "during remount (dev %s, type "SB_TYPE_FMT")\n", sb->s_id, 2486 + SB_TYPE_ARGS(sb)); 2524 2487 goto out_free_opts; 2525 2488 } 2526 2489 ··· 2643 2606 if ((sbsec->flags & SE_SBINITIALIZED) && 2644 2607 (sbsec->behavior == SECURITY_FS_USE_MNTPOINT)) 2645 2608 newsid = sbsec->mntpoint_sid; 2646 - else if (!newsid || !(sbsec->flags & SE_SBLABELSUPP)) { 2609 + else if (!newsid || !(sbsec->flags & SBLABEL_MNT)) { 2647 2610 rc = security_transition_sid(sid, dsec->sid, 2648 2611 inode_mode_to_security_class(inode->i_mode), 2649 2612 qstr, &newsid); ··· 2665 2628 isec->initialized = 1; 2666 2629 } 2667 2630 2668 - if (!ss_initialized || !(sbsec->flags & SE_SBLABELSUPP)) 2631 + if (!ss_initialized || !(sbsec->flags & SBLABEL_MNT)) 2669 2632 return -EOPNOTSUPP; 2670 2633 2671 2634 if (name) ··· 2867 2830 return selinux_inode_setotherxattr(dentry, name); 2868 2831 2869 2832 sbsec = inode->i_sb->s_security; 2870 - if (!(sbsec->flags & SE_SBLABELSUPP)) 2833 + if (!(sbsec->flags & SBLABEL_MNT)) 2871 2834 return -EOPNOTSUPP; 2872 2835 2873 2836 if (!inode_owner_or_capable(inode)) ··· 3828 3791 u32 nlbl_sid; 3829 3792 u32 nlbl_type; 3830 3793 3831 - selinux_skb_xfrm_sid(skb, &xfrm_sid); 3832 - selinux_netlbl_skbuff_getsid(skb, family, &nlbl_type, &nlbl_sid); 3794 + err = selinux_skb_xfrm_sid(skb, &xfrm_sid); 3795 + if (unlikely(err)) 3796 + return -EACCES; 3797 + err = selinux_netlbl_skbuff_getsid(skb, family, &nlbl_type, &nlbl_sid); 3798 + if (unlikely(err)) 3799 + return -EACCES; 3833 3800 3834 3801 err = security_net_peersid_resolve(nlbl_sid, nlbl_type, xfrm_sid, sid); 3835 3802 if (unlikely(err)) { ··· 4287 4246 return selinux_sock_rcv_skb_compat(sk, skb, family); 4288 4247 4289 4248 secmark_active = selinux_secmark_enabled(); 4290 - peerlbl_active = netlbl_enabled() || selinux_xfrm_enabled(); 4249 + peerlbl_active = selinux_peerlbl_enabled(); 4291 4250 if (!secmark_active && !peerlbl_active) 4292 4251 return 0; 4293 4252 ··· 4669 4628 4670 4629 secmark_active = selinux_secmark_enabled(); 4671 4630 netlbl_active = netlbl_enabled(); 4672 - peerlbl_active = netlbl_active || selinux_xfrm_enabled(); 4631 + peerlbl_active = selinux_peerlbl_enabled(); 4673 4632 if (!secmark_active && !peerlbl_active) 4674 4633 return NF_ACCEPT; 4675 4634 ··· 4821 4780 return NF_ACCEPT; 4822 4781 #endif 4823 4782 secmark_active = selinux_secmark_enabled(); 4824 - peerlbl_active = netlbl_enabled() || selinux_xfrm_enabled(); 4783 + peerlbl_active = selinux_peerlbl_enabled(); 4825 4784 if (!secmark_active && !peerlbl_active) 4826 4785 return NF_ACCEPT; 4827 4786 ··· 5825 5784 .xfrm_policy_clone_security = selinux_xfrm_policy_clone, 5826 5785 .xfrm_policy_free_security = selinux_xfrm_policy_free, 5827 5786 .xfrm_policy_delete_security = selinux_xfrm_policy_delete, 5828 - .xfrm_state_alloc_security = selinux_xfrm_state_alloc, 5787 + .xfrm_state_alloc = selinux_xfrm_state_alloc, 5788 + .xfrm_state_alloc_acquire = selinux_xfrm_state_alloc_acquire, 5829 5789 .xfrm_state_free_security = selinux_xfrm_state_free, 5830 5790 .xfrm_state_delete_security = selinux_xfrm_state_delete, 5831 5791 .xfrm_policy_lookup = selinux_xfrm_policy_lookup,
+2 -2
security/selinux/include/objsec.h
··· 58 58 u32 sid; /* SID of file system superblock */ 59 59 u32 def_sid; /* default SID for labeling */ 60 60 u32 mntpoint_sid; /* SECURITY_FS_USE_MNTPOINT context for files */ 61 - unsigned int behavior; /* labeling behavior */ 62 - unsigned char flags; /* which mount options were specified */ 61 + unsigned short behavior; /* labeling behavior */ 62 + unsigned short flags; /* which mount options were specified */ 63 63 struct mutex lock; 64 64 struct list_head isec_head; 65 65 spinlock_t isec_lock;
+8 -5
security/selinux/include/security.h
··· 45 45 /* Mask for just the mount related flags */ 46 46 #define SE_MNTMASK 0x0f 47 47 /* Super block security struct flags for mount options */ 48 + /* BE CAREFUL, these need to be the low order bits for selinux_get_mnt_opts */ 48 49 #define CONTEXT_MNT 0x01 49 50 #define FSCONTEXT_MNT 0x02 50 51 #define ROOTCONTEXT_MNT 0x04 51 52 #define DEFCONTEXT_MNT 0x08 53 + #define SBLABEL_MNT 0x10 52 54 /* Non-mount related flags */ 53 - #define SE_SBINITIALIZED 0x10 54 - #define SE_SBPROC 0x20 55 - #define SE_SBLABELSUPP 0x40 55 + #define SE_SBINITIALIZED 0x0100 56 + #define SE_SBPROC 0x0200 56 57 57 58 #define CONTEXT_STR "context=" 58 59 #define FSCONTEXT_STR "fscontext=" ··· 69 68 enum { 70 69 POLICYDB_CAPABILITY_NETPEER, 71 70 POLICYDB_CAPABILITY_OPENPERM, 71 + POLICYDB_CAPABILITY_REDHAT1, 72 + POLICYDB_CAPABILITY_ALWAYSNETWORK, 72 73 __POLICYDB_CAPABILITY_MAX 73 74 }; 74 75 #define POLICYDB_CAPABILITY_MAX (__POLICYDB_CAPABILITY_MAX - 1) 75 76 76 77 extern int selinux_policycap_netpeer; 77 78 extern int selinux_policycap_openperm; 79 + extern int selinux_policycap_alwaysnetwork; 78 80 79 81 /* 80 82 * type_datum properties ··· 176 172 #define SECURITY_FS_USE_NATIVE 7 /* use native label support */ 177 173 #define SECURITY_FS_USE_MAX 7 /* Highest SECURITY_FS_USE_XXX */ 178 174 179 - int security_fs_use(const char *fstype, unsigned int *behavior, 180 - u32 *sid); 175 + int security_fs_use(struct super_block *sb); 181 176 182 177 int security_genfs_sid(const char *fstype, char *name, u16 sclass, 183 178 u32 *sid);
+19 -26
security/selinux/include/xfrm.h
··· 10 10 #include <net/flow.h> 11 11 12 12 int selinux_xfrm_policy_alloc(struct xfrm_sec_ctx **ctxp, 13 - struct xfrm_user_sec_ctx *sec_ctx); 13 + struct xfrm_user_sec_ctx *uctx); 14 14 int selinux_xfrm_policy_clone(struct xfrm_sec_ctx *old_ctx, 15 15 struct xfrm_sec_ctx **new_ctxp); 16 16 void selinux_xfrm_policy_free(struct xfrm_sec_ctx *ctx); 17 17 int selinux_xfrm_policy_delete(struct xfrm_sec_ctx *ctx); 18 18 int selinux_xfrm_state_alloc(struct xfrm_state *x, 19 - struct xfrm_user_sec_ctx *sec_ctx, u32 secid); 19 + struct xfrm_user_sec_ctx *uctx); 20 + int selinux_xfrm_state_alloc_acquire(struct xfrm_state *x, 21 + struct xfrm_sec_ctx *polsec, u32 secid); 20 22 void selinux_xfrm_state_free(struct xfrm_state *x); 21 23 int selinux_xfrm_state_delete(struct xfrm_state *x); 22 24 int selinux_xfrm_policy_lookup(struct xfrm_sec_ctx *ctx, u32 fl_secid, u8 dir); 23 25 int selinux_xfrm_state_pol_flow_match(struct xfrm_state *x, 24 - struct xfrm_policy *xp, const struct flowi *fl); 25 - 26 - /* 27 - * Extract the security blob from the sock (it's actually on the socket) 28 - */ 29 - static inline struct inode_security_struct *get_sock_isec(struct sock *sk) 30 - { 31 - if (!sk->sk_socket) 32 - return NULL; 33 - 34 - return SOCK_INODE(sk->sk_socket)->i_security; 35 - } 26 + struct xfrm_policy *xp, 27 + const struct flowi *fl); 36 28 37 29 #ifdef CONFIG_SECURITY_NETWORK_XFRM 38 30 extern atomic_t selinux_xfrm_refcount; ··· 34 42 return (atomic_read(&selinux_xfrm_refcount) > 0); 35 43 } 36 44 37 - int selinux_xfrm_sock_rcv_skb(u32 sid, struct sk_buff *skb, 38 - struct common_audit_data *ad); 39 - int selinux_xfrm_postroute_last(u32 isec_sid, struct sk_buff *skb, 40 - struct common_audit_data *ad, u8 proto); 45 + int selinux_xfrm_sock_rcv_skb(u32 sk_sid, struct sk_buff *skb, 46 + struct common_audit_data *ad); 47 + int selinux_xfrm_postroute_last(u32 sk_sid, struct sk_buff *skb, 48 + struct common_audit_data *ad, u8 proto); 41 49 int selinux_xfrm_decode_session(struct sk_buff *skb, u32 *sid, int ckall); 42 50 43 51 static inline void selinux_xfrm_notify_policyload(void) ··· 56 64 return 0; 57 65 } 58 66 59 - static inline int selinux_xfrm_sock_rcv_skb(u32 isec_sid, struct sk_buff *skb, 60 - struct common_audit_data *ad) 67 + static inline int selinux_xfrm_sock_rcv_skb(u32 sk_sid, struct sk_buff *skb, 68 + struct common_audit_data *ad) 61 69 { 62 70 return 0; 63 71 } 64 72 65 - static inline int selinux_xfrm_postroute_last(u32 isec_sid, struct sk_buff *skb, 66 - struct common_audit_data *ad, u8 proto) 73 + static inline int selinux_xfrm_postroute_last(u32 sk_sid, struct sk_buff *skb, 74 + struct common_audit_data *ad, 75 + u8 proto) 67 76 { 68 77 return 0; 69 78 } 70 79 71 - static inline int selinux_xfrm_decode_session(struct sk_buff *skb, u32 *sid, int ckall) 80 + static inline int selinux_xfrm_decode_session(struct sk_buff *skb, u32 *sid, 81 + int ckall) 72 82 { 73 83 *sid = SECSID_NULL; 74 84 return 0; ··· 81 87 } 82 88 #endif 83 89 84 - static inline void selinux_skb_xfrm_sid(struct sk_buff *skb, u32 *sid) 90 + static inline int selinux_skb_xfrm_sid(struct sk_buff *skb, u32 *sid) 85 91 { 86 - int err = selinux_xfrm_decode_session(skb, sid, 0); 87 - BUG_ON(err); 92 + return selinux_xfrm_decode_session(skb, sid, 0); 88 93 } 89 94 90 95 #endif /* _SELINUX_XFRM_H_ */
+2 -4
security/selinux/netlabel.c
··· 442 442 sksec->nlbl_state != NLBL_CONNLABELED) 443 443 return 0; 444 444 445 - local_bh_disable(); 446 - bh_lock_sock_nested(sk); 445 + lock_sock(sk); 447 446 448 447 /* connected sockets are allowed to disconnect when the address family 449 448 * is set to AF_UNSPEC, if that is what is happening we want to reset ··· 463 464 sksec->nlbl_state = NLBL_CONNLABELED; 464 465 465 466 socket_connect_return: 466 - bh_unlock_sock(sk); 467 - local_bh_enable(); 467 + release_sock(sk); 468 468 return rc; 469 469 }
+2
security/selinux/netnode.c
··· 166 166 break; 167 167 default: 168 168 BUG(); 169 + return; 169 170 } 170 171 171 172 /* we need to impose a limit on the growth of the hash table so check ··· 226 225 break; 227 226 default: 228 227 BUG(); 228 + ret = -EINVAL; 229 229 } 230 230 if (ret != 0) 231 231 goto out;
+3 -1
security/selinux/selinuxfs.c
··· 44 44 /* Policy capability filenames */ 45 45 static char *policycap_names[] = { 46 46 "network_peer_controls", 47 - "open_perms" 47 + "open_perms", 48 + "redhat1", 49 + "always_check_network" 48 50 }; 49 51 50 52 unsigned int selinux_checkreqprot = CONFIG_SECURITY_SELINUX_CHECKREQPROT_VALUE;
+18 -2
security/selinux/ss/ebitmap.c
··· 213 213 } 214 214 #endif /* CONFIG_NETLABEL */ 215 215 216 - int ebitmap_contains(struct ebitmap *e1, struct ebitmap *e2) 216 + /* 217 + * Check to see if all the bits set in e2 are also set in e1. Optionally, 218 + * if last_e2bit is non-zero, the highest set bit in e2 cannot exceed 219 + * last_e2bit. 220 + */ 221 + int ebitmap_contains(struct ebitmap *e1, struct ebitmap *e2, u32 last_e2bit) 217 222 { 218 223 struct ebitmap_node *n1, *n2; 219 224 int i; ··· 228 223 229 224 n1 = e1->node; 230 225 n2 = e2->node; 226 + 231 227 while (n1 && n2 && (n1->startbit <= n2->startbit)) { 232 228 if (n1->startbit < n2->startbit) { 233 229 n1 = n1->next; 234 230 continue; 235 231 } 236 - for (i = 0; i < EBITMAP_UNIT_NUMS; i++) { 232 + for (i = EBITMAP_UNIT_NUMS - 1; (i >= 0) && !n2->maps[i]; ) 233 + i--; /* Skip trailing NULL map entries */ 234 + if (last_e2bit && (i >= 0)) { 235 + u32 lastsetbit = n2->startbit + i * EBITMAP_UNIT_SIZE + 236 + __fls(n2->maps[i]); 237 + if (lastsetbit > last_e2bit) 238 + return 0; 239 + } 240 + 241 + while (i >= 0) { 237 242 if ((n1->maps[i] & n2->maps[i]) != n2->maps[i]) 238 243 return 0; 244 + i--; 239 245 } 240 246 241 247 n1 = n1->next;
+8 -2
security/selinux/ss/ebitmap.h
··· 16 16 17 17 #include <net/netlabel.h> 18 18 19 - #define EBITMAP_UNIT_NUMS ((32 - sizeof(void *) - sizeof(u32)) \ 19 + #ifdef CONFIG_64BIT 20 + #define EBITMAP_NODE_SIZE 64 21 + #else 22 + #define EBITMAP_NODE_SIZE 32 23 + #endif 24 + 25 + #define EBITMAP_UNIT_NUMS ((EBITMAP_NODE_SIZE-sizeof(void *)-sizeof(u32))\ 20 26 / sizeof(unsigned long)) 21 27 #define EBITMAP_UNIT_SIZE BITS_PER_LONG 22 28 #define EBITMAP_SIZE (EBITMAP_UNIT_NUMS * EBITMAP_UNIT_SIZE) ··· 123 117 124 118 int ebitmap_cmp(struct ebitmap *e1, struct ebitmap *e2); 125 119 int ebitmap_cpy(struct ebitmap *dst, struct ebitmap *src); 126 - int ebitmap_contains(struct ebitmap *e1, struct ebitmap *e2); 120 + int ebitmap_contains(struct ebitmap *e1, struct ebitmap *e2, u32 last_e2bit); 127 121 int ebitmap_get_bit(struct ebitmap *e, unsigned long bit); 128 122 int ebitmap_set_bit(struct ebitmap *e, unsigned long bit, int value); 129 123 void ebitmap_destroy(struct ebitmap *e);
+7 -15
security/selinux/ss/mls.c
··· 160 160 int mls_level_isvalid(struct policydb *p, struct mls_level *l) 161 161 { 162 162 struct level_datum *levdatum; 163 - struct ebitmap_node *node; 164 - int i; 165 163 166 164 if (!l->sens || l->sens > p->p_levels.nprim) 167 165 return 0; ··· 168 170 if (!levdatum) 169 171 return 0; 170 172 171 - ebitmap_for_each_positive_bit(&l->cat, node, i) { 172 - if (i > p->p_cats.nprim) 173 - return 0; 174 - if (!ebitmap_get_bit(&levdatum->level->cat, i)) { 175 - /* 176 - * Category may not be associated with 177 - * sensitivity. 178 - */ 179 - return 0; 180 - } 181 - } 182 - 183 - return 1; 173 + /* 174 + * Return 1 iff all the bits set in l->cat are also be set in 175 + * levdatum->level->cat and no bit in l->cat is larger than 176 + * p->p_cats.nprim. 177 + */ 178 + return ebitmap_contains(&levdatum->level->cat, &l->cat, 179 + p->p_cats.nprim); 184 180 } 185 181 186 182 int mls_range_isvalid(struct policydb *p, struct mls_range *r)
+1 -1
security/selinux/ss/mls_types.h
··· 35 35 static inline int mls_level_dom(struct mls_level *l1, struct mls_level *l2) 36 36 { 37 37 return ((l1->sens >= l2->sens) && 38 - ebitmap_contains(&l1->cat, &l2->cat)); 38 + ebitmap_contains(&l1->cat, &l2->cat, 0)); 39 39 } 40 40 41 41 #define mls_level_incomp(l1, l2) \
+1 -2
security/selinux/ss/policydb.c
··· 3203 3203 3204 3204 static int range_write(struct policydb *p, void *fp) 3205 3205 { 3206 - size_t nel; 3207 3206 __le32 buf[1]; 3208 - int rc; 3207 + int rc, nel; 3209 3208 struct policy_data pd; 3210 3209 3211 3210 pd.p = p;
+50 -16
security/selinux/ss/services.c
··· 72 72 73 73 int selinux_policycap_netpeer; 74 74 int selinux_policycap_openperm; 75 + int selinux_policycap_alwaysnetwork; 75 76 76 77 static DEFINE_RWLOCK(policy_rwlock); 77 78 ··· 1813 1812 POLICYDB_CAPABILITY_NETPEER); 1814 1813 selinux_policycap_openperm = ebitmap_get_bit(&policydb.policycaps, 1815 1814 POLICYDB_CAPABILITY_OPENPERM); 1815 + selinux_policycap_alwaysnetwork = ebitmap_get_bit(&policydb.policycaps, 1816 + POLICYDB_CAPABILITY_ALWAYSNETWORK); 1816 1817 } 1817 1818 1818 1819 static int security_preserve_bools(struct policydb *p); ··· 2326 2323 2327 2324 /** 2328 2325 * security_fs_use - Determine how to handle labeling for a filesystem. 2329 - * @fstype: filesystem type 2330 - * @behavior: labeling behavior 2331 - * @sid: SID for filesystem (superblock) 2326 + * @sb: superblock in question 2332 2327 */ 2333 - int security_fs_use( 2334 - const char *fstype, 2335 - unsigned int *behavior, 2336 - u32 *sid) 2328 + int security_fs_use(struct super_block *sb) 2337 2329 { 2338 2330 int rc = 0; 2339 2331 struct ocontext *c; 2332 + struct superblock_security_struct *sbsec = sb->s_security; 2333 + const char *fstype = sb->s_type->name; 2334 + const char *subtype = (sb->s_subtype && sb->s_subtype[0]) ? sb->s_subtype : NULL; 2335 + struct ocontext *base = NULL; 2340 2336 2341 2337 read_lock(&policy_rwlock); 2342 2338 2343 - c = policydb.ocontexts[OCON_FSUSE]; 2344 - while (c) { 2345 - if (strcmp(fstype, c->u.name) == 0) 2339 + for (c = policydb.ocontexts[OCON_FSUSE]; c; c = c->next) { 2340 + char *sub; 2341 + int baselen; 2342 + 2343 + baselen = strlen(fstype); 2344 + 2345 + /* if base does not match, this is not the one */ 2346 + if (strncmp(fstype, c->u.name, baselen)) 2347 + continue; 2348 + 2349 + /* if there is no subtype, this is the one! */ 2350 + if (!subtype) 2346 2351 break; 2347 - c = c->next; 2352 + 2353 + /* skip past the base in this entry */ 2354 + sub = c->u.name + baselen; 2355 + 2356 + /* entry is only a base. save it. keep looking for subtype */ 2357 + if (sub[0] == '\0') { 2358 + base = c; 2359 + continue; 2360 + } 2361 + 2362 + /* entry is not followed by a subtype, so it is not a match */ 2363 + if (sub[0] != '.') 2364 + continue; 2365 + 2366 + /* whew, we found a subtype of this fstype */ 2367 + sub++; /* move past '.' */ 2368 + 2369 + /* exact match of fstype AND subtype */ 2370 + if (!strcmp(subtype, sub)) 2371 + break; 2348 2372 } 2349 2373 2374 + /* in case we had found an fstype match but no subtype match */ 2375 + if (!c) 2376 + c = base; 2377 + 2350 2378 if (c) { 2351 - *behavior = c->v.behavior; 2379 + sbsec->behavior = c->v.behavior; 2352 2380 if (!c->sid[0]) { 2353 2381 rc = sidtab_context_to_sid(&sidtab, &c->context[0], 2354 2382 &c->sid[0]); 2355 2383 if (rc) 2356 2384 goto out; 2357 2385 } 2358 - *sid = c->sid[0]; 2386 + sbsec->sid = c->sid[0]; 2359 2387 } else { 2360 - rc = security_genfs_sid(fstype, "/", SECCLASS_DIR, sid); 2388 + rc = security_genfs_sid(fstype, "/", SECCLASS_DIR, &sbsec->sid); 2361 2389 if (rc) { 2362 - *behavior = SECURITY_FS_USE_NONE; 2390 + sbsec->behavior = SECURITY_FS_USE_NONE; 2363 2391 rc = 0; 2364 2392 } else { 2365 - *behavior = SECURITY_FS_USE_GENFS; 2393 + sbsec->behavior = SECURITY_FS_USE_GENFS; 2366 2394 } 2367 2395 } 2368 2396
+203 -252
security/selinux/xfrm.c
··· 56 56 atomic_t selinux_xfrm_refcount = ATOMIC_INIT(0); 57 57 58 58 /* 59 - * Returns true if an LSM/SELinux context 59 + * Returns true if the context is an LSM/SELinux context. 60 60 */ 61 61 static inline int selinux_authorizable_ctx(struct xfrm_sec_ctx *ctx) 62 62 { ··· 66 66 } 67 67 68 68 /* 69 - * Returns true if the xfrm contains a security blob for SELinux 69 + * Returns true if the xfrm contains a security blob for SELinux. 70 70 */ 71 71 static inline int selinux_authorizable_xfrm(struct xfrm_state *x) 72 72 { ··· 74 74 } 75 75 76 76 /* 77 - * LSM hook implementation that authorizes that a flow can use 78 - * a xfrm policy rule. 77 + * Allocates a xfrm_sec_state and populates it using the supplied security 78 + * xfrm_user_sec_ctx context. 79 + */ 80 + static int selinux_xfrm_alloc_user(struct xfrm_sec_ctx **ctxp, 81 + struct xfrm_user_sec_ctx *uctx) 82 + { 83 + int rc; 84 + const struct task_security_struct *tsec = current_security(); 85 + struct xfrm_sec_ctx *ctx = NULL; 86 + u32 str_len; 87 + 88 + if (ctxp == NULL || uctx == NULL || 89 + uctx->ctx_doi != XFRM_SC_DOI_LSM || 90 + uctx->ctx_alg != XFRM_SC_ALG_SELINUX) 91 + return -EINVAL; 92 + 93 + str_len = uctx->ctx_len; 94 + if (str_len >= PAGE_SIZE) 95 + return -ENOMEM; 96 + 97 + ctx = kmalloc(sizeof(*ctx) + str_len + 1, GFP_KERNEL); 98 + if (!ctx) 99 + return -ENOMEM; 100 + 101 + ctx->ctx_doi = XFRM_SC_DOI_LSM; 102 + ctx->ctx_alg = XFRM_SC_ALG_SELINUX; 103 + ctx->ctx_len = str_len; 104 + memcpy(ctx->ctx_str, &uctx[1], str_len); 105 + ctx->ctx_str[str_len] = '\0'; 106 + rc = security_context_to_sid(ctx->ctx_str, str_len, &ctx->ctx_sid); 107 + if (rc) 108 + goto err; 109 + 110 + rc = avc_has_perm(tsec->sid, ctx->ctx_sid, 111 + SECCLASS_ASSOCIATION, ASSOCIATION__SETCONTEXT, NULL); 112 + if (rc) 113 + goto err; 114 + 115 + *ctxp = ctx; 116 + atomic_inc(&selinux_xfrm_refcount); 117 + return 0; 118 + 119 + err: 120 + kfree(ctx); 121 + return rc; 122 + } 123 + 124 + /* 125 + * Free the xfrm_sec_ctx structure. 126 + */ 127 + static void selinux_xfrm_free(struct xfrm_sec_ctx *ctx) 128 + { 129 + if (!ctx) 130 + return; 131 + 132 + atomic_dec(&selinux_xfrm_refcount); 133 + kfree(ctx); 134 + } 135 + 136 + /* 137 + * Authorize the deletion of a labeled SA or policy rule. 138 + */ 139 + static int selinux_xfrm_delete(struct xfrm_sec_ctx *ctx) 140 + { 141 + const struct task_security_struct *tsec = current_security(); 142 + 143 + if (!ctx) 144 + return 0; 145 + 146 + return avc_has_perm(tsec->sid, ctx->ctx_sid, 147 + SECCLASS_ASSOCIATION, ASSOCIATION__SETCONTEXT, 148 + NULL); 149 + } 150 + 151 + /* 152 + * LSM hook implementation that authorizes that a flow can use a xfrm policy 153 + * rule. 79 154 */ 80 155 int selinux_xfrm_policy_lookup(struct xfrm_sec_ctx *ctx, u32 fl_secid, u8 dir) 81 156 { 82 157 int rc; 83 - u32 sel_sid; 84 158 85 - /* Context sid is either set to label or ANY_ASSOC */ 86 - if (ctx) { 87 - if (!selinux_authorizable_ctx(ctx)) 88 - return -EINVAL; 89 - 90 - sel_sid = ctx->ctx_sid; 91 - } else 92 - /* 93 - * All flows should be treated as polmatch'ing an 94 - * otherwise applicable "non-labeled" policy. This 95 - * would prevent inadvertent "leaks". 96 - */ 159 + /* All flows should be treated as polmatch'ing an otherwise applicable 160 + * "non-labeled" policy. This would prevent inadvertent "leaks". */ 161 + if (!ctx) 97 162 return 0; 98 163 99 - rc = avc_has_perm(fl_secid, sel_sid, SECCLASS_ASSOCIATION, 100 - ASSOCIATION__POLMATCH, 101 - NULL); 164 + /* Context sid is either set to label or ANY_ASSOC */ 165 + if (!selinux_authorizable_ctx(ctx)) 166 + return -EINVAL; 102 167 103 - if (rc == -EACCES) 104 - return -ESRCH; 105 - 106 - return rc; 168 + rc = avc_has_perm(fl_secid, ctx->ctx_sid, 169 + SECCLASS_ASSOCIATION, ASSOCIATION__POLMATCH, NULL); 170 + return (rc == -EACCES ? -ESRCH : rc); 107 171 } 108 172 109 173 /* 110 174 * LSM hook implementation that authorizes that a state matches 111 175 * the given policy, flow combo. 112 176 */ 113 - 114 - int selinux_xfrm_state_pol_flow_match(struct xfrm_state *x, struct xfrm_policy *xp, 115 - const struct flowi *fl) 177 + int selinux_xfrm_state_pol_flow_match(struct xfrm_state *x, 178 + struct xfrm_policy *xp, 179 + const struct flowi *fl) 116 180 { 117 181 u32 state_sid; 118 - int rc; 119 182 120 183 if (!xp->security) 121 184 if (x->security) ··· 201 138 if (fl->flowi_secid != state_sid) 202 139 return 0; 203 140 204 - rc = avc_has_perm(fl->flowi_secid, state_sid, SECCLASS_ASSOCIATION, 205 - ASSOCIATION__SENDTO, 206 - NULL)? 0:1; 207 - 208 - /* 209 - * We don't need a separate SA Vs. policy polmatch check 210 - * since the SA is now of the same label as the flow and 211 - * a flow Vs. policy polmatch check had already happened 212 - * in selinux_xfrm_policy_lookup() above. 213 - */ 214 - 215 - return rc; 141 + /* We don't need a separate SA Vs. policy polmatch check since the SA 142 + * is now of the same label as the flow and a flow Vs. policy polmatch 143 + * check had already happened in selinux_xfrm_policy_lookup() above. */ 144 + return (avc_has_perm(fl->flowi_secid, state_sid, 145 + SECCLASS_ASSOCIATION, ASSOCIATION__SENDTO, 146 + NULL) ? 0 : 1); 216 147 } 217 148 218 149 /* 219 150 * LSM hook implementation that checks and/or returns the xfrm sid for the 220 151 * incoming packet. 221 152 */ 222 - 223 153 int selinux_xfrm_decode_session(struct sk_buff *skb, u32 *sid, int ckall) 224 154 { 155 + u32 sid_session = SECSID_NULL; 225 156 struct sec_path *sp; 226 157 227 - *sid = SECSID_NULL; 228 - 229 158 if (skb == NULL) 230 - return 0; 159 + goto out; 231 160 232 161 sp = skb->sp; 233 162 if (sp) { 234 - int i, sid_set = 0; 163 + int i; 235 164 236 - for (i = sp->len-1; i >= 0; i--) { 165 + for (i = sp->len - 1; i >= 0; i--) { 237 166 struct xfrm_state *x = sp->xvec[i]; 238 167 if (selinux_authorizable_xfrm(x)) { 239 168 struct xfrm_sec_ctx *ctx = x->security; 240 169 241 - if (!sid_set) { 242 - *sid = ctx->ctx_sid; 243 - sid_set = 1; 244 - 170 + if (sid_session == SECSID_NULL) { 171 + sid_session = ctx->ctx_sid; 245 172 if (!ckall) 246 - break; 247 - } else if (*sid != ctx->ctx_sid) 173 + goto out; 174 + } else if (sid_session != ctx->ctx_sid) { 175 + *sid = SECSID_NULL; 248 176 return -EINVAL; 177 + } 249 178 } 250 179 } 251 180 } 252 181 182 + out: 183 + *sid = sid_session; 253 184 return 0; 254 185 } 255 186 256 187 /* 257 - * Security blob allocation for xfrm_policy and xfrm_state 258 - * CTX does not have a meaningful value on input 259 - */ 260 - static int selinux_xfrm_sec_ctx_alloc(struct xfrm_sec_ctx **ctxp, 261 - struct xfrm_user_sec_ctx *uctx, u32 sid) 262 - { 263 - int rc = 0; 264 - const struct task_security_struct *tsec = current_security(); 265 - struct xfrm_sec_ctx *ctx = NULL; 266 - char *ctx_str = NULL; 267 - u32 str_len; 268 - 269 - BUG_ON(uctx && sid); 270 - 271 - if (!uctx) 272 - goto not_from_user; 273 - 274 - if (uctx->ctx_alg != XFRM_SC_ALG_SELINUX) 275 - return -EINVAL; 276 - 277 - str_len = uctx->ctx_len; 278 - if (str_len >= PAGE_SIZE) 279 - return -ENOMEM; 280 - 281 - *ctxp = ctx = kmalloc(sizeof(*ctx) + 282 - str_len + 1, 283 - GFP_KERNEL); 284 - 285 - if (!ctx) 286 - return -ENOMEM; 287 - 288 - ctx->ctx_doi = uctx->ctx_doi; 289 - ctx->ctx_len = str_len; 290 - ctx->ctx_alg = uctx->ctx_alg; 291 - 292 - memcpy(ctx->ctx_str, 293 - uctx+1, 294 - str_len); 295 - ctx->ctx_str[str_len] = 0; 296 - rc = security_context_to_sid(ctx->ctx_str, 297 - str_len, 298 - &ctx->ctx_sid); 299 - 300 - if (rc) 301 - goto out; 302 - 303 - /* 304 - * Does the subject have permission to set security context? 305 - */ 306 - rc = avc_has_perm(tsec->sid, ctx->ctx_sid, 307 - SECCLASS_ASSOCIATION, 308 - ASSOCIATION__SETCONTEXT, NULL); 309 - if (rc) 310 - goto out; 311 - 312 - return rc; 313 - 314 - not_from_user: 315 - rc = security_sid_to_context(sid, &ctx_str, &str_len); 316 - if (rc) 317 - goto out; 318 - 319 - *ctxp = ctx = kmalloc(sizeof(*ctx) + 320 - str_len, 321 - GFP_ATOMIC); 322 - 323 - if (!ctx) { 324 - rc = -ENOMEM; 325 - goto out; 326 - } 327 - 328 - ctx->ctx_doi = XFRM_SC_DOI_LSM; 329 - ctx->ctx_alg = XFRM_SC_ALG_SELINUX; 330 - ctx->ctx_sid = sid; 331 - ctx->ctx_len = str_len; 332 - memcpy(ctx->ctx_str, 333 - ctx_str, 334 - str_len); 335 - 336 - goto out2; 337 - 338 - out: 339 - *ctxp = NULL; 340 - kfree(ctx); 341 - out2: 342 - kfree(ctx_str); 343 - return rc; 344 - } 345 - 346 - /* 347 - * LSM hook implementation that allocs and transfers uctx spec to 348 - * xfrm_policy. 188 + * LSM hook implementation that allocs and transfers uctx spec to xfrm_policy. 349 189 */ 350 190 int selinux_xfrm_policy_alloc(struct xfrm_sec_ctx **ctxp, 351 191 struct xfrm_user_sec_ctx *uctx) 352 192 { 353 - int err; 354 - 355 - BUG_ON(!uctx); 356 - 357 - err = selinux_xfrm_sec_ctx_alloc(ctxp, uctx, 0); 358 - if (err == 0) 359 - atomic_inc(&selinux_xfrm_refcount); 360 - 361 - return err; 193 + return selinux_xfrm_alloc_user(ctxp, uctx); 362 194 } 363 195 364 - 365 196 /* 366 - * LSM hook implementation that copies security data structure from old to 367 - * new for policy cloning. 197 + * LSM hook implementation that copies security data structure from old to new 198 + * for policy cloning. 368 199 */ 369 200 int selinux_xfrm_policy_clone(struct xfrm_sec_ctx *old_ctx, 370 201 struct xfrm_sec_ctx **new_ctxp) 371 202 { 372 203 struct xfrm_sec_ctx *new_ctx; 373 204 374 - if (old_ctx) { 375 - new_ctx = kmalloc(sizeof(*old_ctx) + old_ctx->ctx_len, 376 - GFP_ATOMIC); 377 - if (!new_ctx) 378 - return -ENOMEM; 205 + if (!old_ctx) 206 + return 0; 379 207 380 - memcpy(new_ctx, old_ctx, sizeof(*new_ctx)); 381 - memcpy(new_ctx->ctx_str, old_ctx->ctx_str, new_ctx->ctx_len); 382 - atomic_inc(&selinux_xfrm_refcount); 383 - *new_ctxp = new_ctx; 384 - } 208 + new_ctx = kmemdup(old_ctx, sizeof(*old_ctx) + old_ctx->ctx_len, 209 + GFP_ATOMIC); 210 + if (!new_ctx) 211 + return -ENOMEM; 212 + atomic_inc(&selinux_xfrm_refcount); 213 + *new_ctxp = new_ctx; 214 + 385 215 return 0; 386 216 } 387 217 ··· 283 327 */ 284 328 void selinux_xfrm_policy_free(struct xfrm_sec_ctx *ctx) 285 329 { 286 - atomic_dec(&selinux_xfrm_refcount); 287 - kfree(ctx); 330 + selinux_xfrm_free(ctx); 288 331 } 289 332 290 333 /* ··· 291 336 */ 292 337 int selinux_xfrm_policy_delete(struct xfrm_sec_ctx *ctx) 293 338 { 294 - const struct task_security_struct *tsec = current_security(); 295 - 296 - if (!ctx) 297 - return 0; 298 - 299 - return avc_has_perm(tsec->sid, ctx->ctx_sid, 300 - SECCLASS_ASSOCIATION, ASSOCIATION__SETCONTEXT, 301 - NULL); 339 + return selinux_xfrm_delete(ctx); 302 340 } 303 341 304 342 /* 305 - * LSM hook implementation that allocs and transfers sec_ctx spec to 306 - * xfrm_state. 343 + * LSM hook implementation that allocates a xfrm_sec_state, populates it using 344 + * the supplied security context, and assigns it to the xfrm_state. 307 345 */ 308 - int selinux_xfrm_state_alloc(struct xfrm_state *x, struct xfrm_user_sec_ctx *uctx, 309 - u32 secid) 346 + int selinux_xfrm_state_alloc(struct xfrm_state *x, 347 + struct xfrm_user_sec_ctx *uctx) 310 348 { 311 - int err; 349 + return selinux_xfrm_alloc_user(&x->security, uctx); 350 + } 312 351 313 - BUG_ON(!x); 352 + /* 353 + * LSM hook implementation that allocates a xfrm_sec_state and populates based 354 + * on a secid. 355 + */ 356 + int selinux_xfrm_state_alloc_acquire(struct xfrm_state *x, 357 + struct xfrm_sec_ctx *polsec, u32 secid) 358 + { 359 + int rc; 360 + struct xfrm_sec_ctx *ctx; 361 + char *ctx_str = NULL; 362 + int str_len; 314 363 315 - err = selinux_xfrm_sec_ctx_alloc(&x->security, uctx, secid); 316 - if (err == 0) 317 - atomic_inc(&selinux_xfrm_refcount); 318 - return err; 364 + if (!polsec) 365 + return 0; 366 + 367 + if (secid == 0) 368 + return -EINVAL; 369 + 370 + rc = security_sid_to_context(secid, &ctx_str, &str_len); 371 + if (rc) 372 + return rc; 373 + 374 + ctx = kmalloc(sizeof(*ctx) + str_len, GFP_ATOMIC); 375 + if (!ctx) 376 + return -ENOMEM; 377 + 378 + ctx->ctx_doi = XFRM_SC_DOI_LSM; 379 + ctx->ctx_alg = XFRM_SC_ALG_SELINUX; 380 + ctx->ctx_sid = secid; 381 + ctx->ctx_len = str_len; 382 + memcpy(ctx->ctx_str, ctx_str, str_len); 383 + kfree(ctx_str); 384 + 385 + x->security = ctx; 386 + atomic_inc(&selinux_xfrm_refcount); 387 + return 0; 319 388 } 320 389 321 390 /* ··· 347 368 */ 348 369 void selinux_xfrm_state_free(struct xfrm_state *x) 349 370 { 350 - atomic_dec(&selinux_xfrm_refcount); 351 - kfree(x->security); 371 + selinux_xfrm_free(x->security); 352 372 } 353 373 354 - /* 355 - * LSM hook implementation that authorizes deletion of labeled SAs. 356 - */ 374 + /* 375 + * LSM hook implementation that authorizes deletion of labeled SAs. 376 + */ 357 377 int selinux_xfrm_state_delete(struct xfrm_state *x) 358 378 { 359 - const struct task_security_struct *tsec = current_security(); 360 - struct xfrm_sec_ctx *ctx = x->security; 361 - 362 - if (!ctx) 363 - return 0; 364 - 365 - return avc_has_perm(tsec->sid, ctx->ctx_sid, 366 - SECCLASS_ASSOCIATION, ASSOCIATION__SETCONTEXT, 367 - NULL); 379 + return selinux_xfrm_delete(x->security); 368 380 } 369 381 370 382 /* ··· 365 395 * we need to check for unlabelled access since this may not have 366 396 * gone thru the IPSec process. 367 397 */ 368 - int selinux_xfrm_sock_rcv_skb(u32 isec_sid, struct sk_buff *skb, 369 - struct common_audit_data *ad) 398 + int selinux_xfrm_sock_rcv_skb(u32 sk_sid, struct sk_buff *skb, 399 + struct common_audit_data *ad) 370 400 { 371 - int i, rc = 0; 372 - struct sec_path *sp; 373 - u32 sel_sid = SECINITSID_UNLABELED; 374 - 375 - sp = skb->sp; 401 + int i; 402 + struct sec_path *sp = skb->sp; 403 + u32 peer_sid = SECINITSID_UNLABELED; 376 404 377 405 if (sp) { 378 406 for (i = 0; i < sp->len; i++) { ··· 378 410 379 411 if (x && selinux_authorizable_xfrm(x)) { 380 412 struct xfrm_sec_ctx *ctx = x->security; 381 - sel_sid = ctx->ctx_sid; 413 + peer_sid = ctx->ctx_sid; 382 414 break; 383 415 } 384 416 } 385 417 } 386 418 387 - /* 388 - * This check even when there's no association involved is 389 - * intended, according to Trent Jaeger, to make sure a 390 - * process can't engage in non-ipsec communication unless 391 - * explicitly allowed by policy. 392 - */ 393 - 394 - rc = avc_has_perm(isec_sid, sel_sid, SECCLASS_ASSOCIATION, 395 - ASSOCIATION__RECVFROM, ad); 396 - 397 - return rc; 419 + /* This check even when there's no association involved is intended, 420 + * according to Trent Jaeger, to make sure a process can't engage in 421 + * non-IPsec communication unless explicitly allowed by policy. */ 422 + return avc_has_perm(sk_sid, peer_sid, 423 + SECCLASS_ASSOCIATION, ASSOCIATION__RECVFROM, ad); 398 424 } 399 425 400 426 /* ··· 398 436 * If we do have a authorizable security association, then it has already been 399 437 * checked in the selinux_xfrm_state_pol_flow_match hook above. 400 438 */ 401 - int selinux_xfrm_postroute_last(u32 isec_sid, struct sk_buff *skb, 402 - struct common_audit_data *ad, u8 proto) 439 + int selinux_xfrm_postroute_last(u32 sk_sid, struct sk_buff *skb, 440 + struct common_audit_data *ad, u8 proto) 403 441 { 404 442 struct dst_entry *dst; 405 - int rc = 0; 406 - 407 - dst = skb_dst(skb); 408 - 409 - if (dst) { 410 - struct dst_entry *dst_test; 411 - 412 - for (dst_test = dst; dst_test != NULL; 413 - dst_test = dst_test->child) { 414 - struct xfrm_state *x = dst_test->xfrm; 415 - 416 - if (x && selinux_authorizable_xfrm(x)) 417 - goto out; 418 - } 419 - } 420 443 421 444 switch (proto) { 422 445 case IPPROTO_AH: 423 446 case IPPROTO_ESP: 424 447 case IPPROTO_COMP: 425 - /* 426 - * We should have already seen this packet once before 427 - * it underwent xfrm(s). No need to subject it to the 428 - * unlabeled check. 429 - */ 430 - goto out; 448 + /* We should have already seen this packet once before it 449 + * underwent xfrm(s). No need to subject it to the unlabeled 450 + * check. */ 451 + return 0; 431 452 default: 432 453 break; 433 454 } 434 455 435 - /* 436 - * This check even when there's no association involved is 437 - * intended, according to Trent Jaeger, to make sure a 438 - * process can't engage in non-ipsec communication unless 439 - * explicitly allowed by policy. 440 - */ 456 + dst = skb_dst(skb); 457 + if (dst) { 458 + struct dst_entry *iter; 441 459 442 - rc = avc_has_perm(isec_sid, SECINITSID_UNLABELED, SECCLASS_ASSOCIATION, 443 - ASSOCIATION__SENDTO, ad); 444 - out: 445 - return rc; 460 + for (iter = dst; iter != NULL; iter = iter->child) { 461 + struct xfrm_state *x = iter->xfrm; 462 + 463 + if (x && selinux_authorizable_xfrm(x)) 464 + return 0; 465 + } 466 + } 467 + 468 + /* This check even when there's no association involved is intended, 469 + * according to Trent Jaeger, to make sure a process can't engage in 470 + * non-IPsec communication unless explicitly allowed by policy. */ 471 + return avc_has_perm(sk_sid, SECINITSID_UNLABELED, 472 + SECCLASS_ASSOCIATION, ASSOCIATION__SENDTO, ad); 446 473 }
+8 -4
security/smack/smack.h
··· 177 177 #define SMACK_CIPSO_MAXCATNUM 184 /* 23 * 8 */ 178 178 179 179 /* 180 - * Flag for transmute access 180 + * Flags for untraditional access modes. 181 + * It shouldn't be necessary to avoid conflicts with definitions 182 + * in fs.h, but do so anyway. 181 183 */ 182 - #define MAY_TRANSMUTE 64 184 + #define MAY_TRANSMUTE 0x00001000 /* Controls directory labeling */ 185 + #define MAY_LOCK 0x00002000 /* Locks should be writes, but ... */ 186 + 183 187 /* 184 188 * Just to make the common cases easier to deal with 185 189 */ ··· 192 188 #define MAY_NOT 0 193 189 194 190 /* 195 - * Number of access types used by Smack (rwxat) 191 + * Number of access types used by Smack (rwxatl) 196 192 */ 197 - #define SMK_NUM_ACCESS_TYPE 5 193 + #define SMK_NUM_ACCESS_TYPE 6 198 194 199 195 /* SMACK data */ 200 196 struct smack_audit_data {
+10
security/smack/smack_access.c
··· 84 84 * 85 85 * Do the object check first because that is more 86 86 * likely to differ. 87 + * 88 + * Allowing write access implies allowing locking. 87 89 */ 88 90 int smk_access_entry(char *subject_label, char *object_label, 89 91 struct list_head *rule_list) ··· 101 99 } 102 100 } 103 101 102 + /* 103 + * MAY_WRITE implies MAY_LOCK. 104 + */ 105 + if ((may & MAY_WRITE) == MAY_WRITE) 106 + may |= MAY_LOCK; 104 107 return may; 105 108 } 106 109 ··· 252 245 static inline void smack_str_from_perm(char *string, int access) 253 246 { 254 247 int i = 0; 248 + 255 249 if (access & MAY_READ) 256 250 string[i++] = 'r'; 257 251 if (access & MAY_WRITE) ··· 263 255 string[i++] = 'a'; 264 256 if (access & MAY_TRANSMUTE) 265 257 string[i++] = 't'; 258 + if (access & MAY_LOCK) 259 + string[i++] = 'l'; 266 260 string[i] = '\0'; 267 261 } 268 262 /**
+8 -3
security/smack/smack_lsm.c
··· 185 185 smk_ad_init(&ad, __func__, LSM_AUDIT_DATA_TASK); 186 186 smk_ad_setfield_u_tsk(&ad, ctp); 187 187 188 - rc = smk_curacc(skp->smk_known, MAY_READWRITE, &ad); 188 + rc = smk_curacc(skp->smk_known, mode, &ad); 189 189 return rc; 190 190 } 191 191 ··· 1146 1146 * @file: the object 1147 1147 * @cmd: unused 1148 1148 * 1149 - * Returns 0 if current has write access, error code otherwise 1149 + * Returns 0 if current has lock access, error code otherwise 1150 1150 */ 1151 1151 static int smack_file_lock(struct file *file, unsigned int cmd) 1152 1152 { ··· 1154 1154 1155 1155 smk_ad_init(&ad, __func__, LSM_AUDIT_DATA_PATH); 1156 1156 smk_ad_setfield_u_fs_path(&ad, file->f_path); 1157 - return smk_curacc(file->f_security, MAY_WRITE, &ad); 1157 + return smk_curacc(file->f_security, MAY_LOCK, &ad); 1158 1158 } 1159 1159 1160 1160 /** ··· 1178 1178 1179 1179 switch (cmd) { 1180 1180 case F_GETLK: 1181 + break; 1181 1182 case F_SETLK: 1182 1183 case F_SETLKW: 1184 + smk_ad_init(&ad, __func__, LSM_AUDIT_DATA_PATH); 1185 + smk_ad_setfield_u_fs_path(&ad, file->f_path); 1186 + rc = smk_curacc(file->f_security, MAY_LOCK, &ad); 1187 + break; 1183 1188 case F_SETOWN: 1184 1189 case F_SETSIG: 1185 1190 smk_ad_init(&ad, __func__, LSM_AUDIT_DATA_PATH);
+8 -2
security/smack/smackfs.c
··· 139 139 * SMK_LOADLEN: Smack rule length 140 140 */ 141 141 #define SMK_OACCESS "rwxa" 142 - #define SMK_ACCESS "rwxat" 142 + #define SMK_ACCESS "rwxatl" 143 143 #define SMK_OACCESSLEN (sizeof(SMK_OACCESS) - 1) 144 144 #define SMK_ACCESSLEN (sizeof(SMK_ACCESS) - 1) 145 145 #define SMK_OLOADLEN (SMK_LABELLEN + SMK_LABELLEN + SMK_OACCESSLEN) ··· 281 281 case 't': 282 282 case 'T': 283 283 perm |= MAY_TRANSMUTE; 284 + break; 285 + case 'l': 286 + case 'L': 287 + perm |= MAY_LOCK; 284 288 break; 285 289 default: 286 290 return perm; ··· 456 452 /* 457 453 * Minor hack for backward compatibility 458 454 */ 459 - if (count != SMK_OLOADLEN && count != SMK_LOADLEN) 455 + if (count < SMK_OLOADLEN || count > SMK_LOADLEN) 460 456 return -EINVAL; 461 457 } else { 462 458 if (count >= PAGE_SIZE) { ··· 596 592 seq_putc(s, 'a'); 597 593 if (srp->smk_access & MAY_TRANSMUTE) 598 594 seq_putc(s, 't'); 595 + if (srp->smk_access & MAY_LOCK) 596 + seq_putc(s, 'l'); 599 597 600 598 seq_putc(s, '\n'); 601 599 }