]> Pileus Git - ~andy/linux/blob - kernel/auditsc.c
audit: loginuid functions coding style
[~andy/linux] / kernel / auditsc.c
1 /* auditsc.c -- System-call auditing support
2  * Handles all system-call specific auditing features.
3  *
4  * Copyright 2003-2004 Red Hat Inc., Durham, North Carolina.
5  * Copyright 2005 Hewlett-Packard Development Company, L.P.
6  * Copyright (C) 2005, 2006 IBM Corporation
7  * All Rights Reserved.
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
22  *
23  * Written by Rickard E. (Rik) Faith <faith@redhat.com>
24  *
25  * Many of the ideas implemented here are from Stephen C. Tweedie,
26  * especially the idea of avoiding a copy by using getname.
27  *
28  * The method for actual interception of syscall entry and exit (not in
29  * this file -- see entry.S) is based on a GPL'd patch written by
30  * okir@suse.de and Copyright 2003 SuSE Linux AG.
31  *
32  * POSIX message queue support added by George Wilson <ltcgcw@us.ibm.com>,
33  * 2006.
34  *
35  * The support of additional filter rules compares (>, <, >=, <=) was
36  * added by Dustin Kirkland <dustin.kirkland@us.ibm.com>, 2005.
37  *
38  * Modified by Amy Griffis <amy.griffis@hp.com> to collect additional
39  * filesystem information.
40  *
41  * Subject and object context labeling support added by <danjones@us.ibm.com>
42  * and <dustin.kirkland@us.ibm.com> for LSPP certification compliance.
43  */
44
45 #include <linux/init.h>
46 #include <asm/types.h>
47 #include <linux/atomic.h>
48 #include <linux/fs.h>
49 #include <linux/namei.h>
50 #include <linux/mm.h>
51 #include <linux/export.h>
52 #include <linux/slab.h>
53 #include <linux/mount.h>
54 #include <linux/socket.h>
55 #include <linux/mqueue.h>
56 #include <linux/audit.h>
57 #include <linux/personality.h>
58 #include <linux/time.h>
59 #include <linux/netlink.h>
60 #include <linux/compiler.h>
61 #include <asm/unistd.h>
62 #include <linux/security.h>
63 #include <linux/list.h>
64 #include <linux/tty.h>
65 #include <linux/binfmts.h>
66 #include <linux/highmem.h>
67 #include <linux/syscalls.h>
68 #include <linux/capability.h>
69 #include <linux/fs_struct.h>
70 #include <linux/compat.h>
71
72 #include "audit.h"
73
74 /* flags stating the success for a syscall */
75 #define AUDITSC_INVALID 0
76 #define AUDITSC_SUCCESS 1
77 #define AUDITSC_FAILURE 2
78
79 /* no execve audit message should be longer than this (userspace limits) */
80 #define MAX_EXECVE_AUDIT_LEN 7500
81
82 /* number of audit rules */
83 int audit_n_rules;
84
85 /* determines whether we collect data for signals sent */
86 int audit_signals;
87
88 struct audit_aux_data {
89         struct audit_aux_data   *next;
90         int                     type;
91 };
92
93 #define AUDIT_AUX_IPCPERM       0
94
95 /* Number of target pids per aux struct. */
96 #define AUDIT_AUX_PIDS  16
97
98 struct audit_aux_data_execve {
99         struct audit_aux_data   d;
100         int argc;
101         int envc;
102         struct mm_struct *mm;
103 };
104
105 struct audit_aux_data_pids {
106         struct audit_aux_data   d;
107         pid_t                   target_pid[AUDIT_AUX_PIDS];
108         kuid_t                  target_auid[AUDIT_AUX_PIDS];
109         kuid_t                  target_uid[AUDIT_AUX_PIDS];
110         unsigned int            target_sessionid[AUDIT_AUX_PIDS];
111         u32                     target_sid[AUDIT_AUX_PIDS];
112         char                    target_comm[AUDIT_AUX_PIDS][TASK_COMM_LEN];
113         int                     pid_count;
114 };
115
116 struct audit_aux_data_bprm_fcaps {
117         struct audit_aux_data   d;
118         struct audit_cap_data   fcap;
119         unsigned int            fcap_ver;
120         struct audit_cap_data   old_pcap;
121         struct audit_cap_data   new_pcap;
122 };
123
124 struct audit_aux_data_capset {
125         struct audit_aux_data   d;
126         pid_t                   pid;
127         struct audit_cap_data   cap;
128 };
129
130 struct audit_tree_refs {
131         struct audit_tree_refs *next;
132         struct audit_chunk *c[31];
133 };
134
135 static inline int open_arg(int flags, int mask)
136 {
137         int n = ACC_MODE(flags);
138         if (flags & (O_TRUNC | O_CREAT))
139                 n |= AUDIT_PERM_WRITE;
140         return n & mask;
141 }
142
143 static int audit_match_perm(struct audit_context *ctx, int mask)
144 {
145         unsigned n;
146         if (unlikely(!ctx))
147                 return 0;
148         n = ctx->major;
149
150         switch (audit_classify_syscall(ctx->arch, n)) {
151         case 0: /* native */
152                 if ((mask & AUDIT_PERM_WRITE) &&
153                      audit_match_class(AUDIT_CLASS_WRITE, n))
154                         return 1;
155                 if ((mask & AUDIT_PERM_READ) &&
156                      audit_match_class(AUDIT_CLASS_READ, n))
157                         return 1;
158                 if ((mask & AUDIT_PERM_ATTR) &&
159                      audit_match_class(AUDIT_CLASS_CHATTR, n))
160                         return 1;
161                 return 0;
162         case 1: /* 32bit on biarch */
163                 if ((mask & AUDIT_PERM_WRITE) &&
164                      audit_match_class(AUDIT_CLASS_WRITE_32, n))
165                         return 1;
166                 if ((mask & AUDIT_PERM_READ) &&
167                      audit_match_class(AUDIT_CLASS_READ_32, n))
168                         return 1;
169                 if ((mask & AUDIT_PERM_ATTR) &&
170                      audit_match_class(AUDIT_CLASS_CHATTR_32, n))
171                         return 1;
172                 return 0;
173         case 2: /* open */
174                 return mask & ACC_MODE(ctx->argv[1]);
175         case 3: /* openat */
176                 return mask & ACC_MODE(ctx->argv[2]);
177         case 4: /* socketcall */
178                 return ((mask & AUDIT_PERM_WRITE) && ctx->argv[0] == SYS_BIND);
179         case 5: /* execve */
180                 return mask & AUDIT_PERM_EXEC;
181         default:
182                 return 0;
183         }
184 }
185
186 static int audit_match_filetype(struct audit_context *ctx, int val)
187 {
188         struct audit_names *n;
189         umode_t mode = (umode_t)val;
190
191         if (unlikely(!ctx))
192                 return 0;
193
194         list_for_each_entry(n, &ctx->names_list, list) {
195                 if ((n->ino != -1) &&
196                     ((n->mode & S_IFMT) == mode))
197                         return 1;
198         }
199
200         return 0;
201 }
202
203 /*
204  * We keep a linked list of fixed-sized (31 pointer) arrays of audit_chunk *;
205  * ->first_trees points to its beginning, ->trees - to the current end of data.
206  * ->tree_count is the number of free entries in array pointed to by ->trees.
207  * Original condition is (NULL, NULL, 0); as soon as it grows we never revert to NULL,
208  * "empty" becomes (p, p, 31) afterwards.  We don't shrink the list (and seriously,
209  * it's going to remain 1-element for almost any setup) until we free context itself.
210  * References in it _are_ dropped - at the same time we free/drop aux stuff.
211  */
212
213 #ifdef CONFIG_AUDIT_TREE
214 static void audit_set_auditable(struct audit_context *ctx)
215 {
216         if (!ctx->prio) {
217                 ctx->prio = 1;
218                 ctx->current_state = AUDIT_RECORD_CONTEXT;
219         }
220 }
221
222 static int put_tree_ref(struct audit_context *ctx, struct audit_chunk *chunk)
223 {
224         struct audit_tree_refs *p = ctx->trees;
225         int left = ctx->tree_count;
226         if (likely(left)) {
227                 p->c[--left] = chunk;
228                 ctx->tree_count = left;
229                 return 1;
230         }
231         if (!p)
232                 return 0;
233         p = p->next;
234         if (p) {
235                 p->c[30] = chunk;
236                 ctx->trees = p;
237                 ctx->tree_count = 30;
238                 return 1;
239         }
240         return 0;
241 }
242
243 static int grow_tree_refs(struct audit_context *ctx)
244 {
245         struct audit_tree_refs *p = ctx->trees;
246         ctx->trees = kzalloc(sizeof(struct audit_tree_refs), GFP_KERNEL);
247         if (!ctx->trees) {
248                 ctx->trees = p;
249                 return 0;
250         }
251         if (p)
252                 p->next = ctx->trees;
253         else
254                 ctx->first_trees = ctx->trees;
255         ctx->tree_count = 31;
256         return 1;
257 }
258 #endif
259
260 static void unroll_tree_refs(struct audit_context *ctx,
261                       struct audit_tree_refs *p, int count)
262 {
263 #ifdef CONFIG_AUDIT_TREE
264         struct audit_tree_refs *q;
265         int n;
266         if (!p) {
267                 /* we started with empty chain */
268                 p = ctx->first_trees;
269                 count = 31;
270                 /* if the very first allocation has failed, nothing to do */
271                 if (!p)
272                         return;
273         }
274         n = count;
275         for (q = p; q != ctx->trees; q = q->next, n = 31) {
276                 while (n--) {
277                         audit_put_chunk(q->c[n]);
278                         q->c[n] = NULL;
279                 }
280         }
281         while (n-- > ctx->tree_count) {
282                 audit_put_chunk(q->c[n]);
283                 q->c[n] = NULL;
284         }
285         ctx->trees = p;
286         ctx->tree_count = count;
287 #endif
288 }
289
290 static void free_tree_refs(struct audit_context *ctx)
291 {
292         struct audit_tree_refs *p, *q;
293         for (p = ctx->first_trees; p; p = q) {
294                 q = p->next;
295                 kfree(p);
296         }
297 }
298
299 static int match_tree_refs(struct audit_context *ctx, struct audit_tree *tree)
300 {
301 #ifdef CONFIG_AUDIT_TREE
302         struct audit_tree_refs *p;
303         int n;
304         if (!tree)
305                 return 0;
306         /* full ones */
307         for (p = ctx->first_trees; p != ctx->trees; p = p->next) {
308                 for (n = 0; n < 31; n++)
309                         if (audit_tree_match(p->c[n], tree))
310                                 return 1;
311         }
312         /* partial */
313         if (p) {
314                 for (n = ctx->tree_count; n < 31; n++)
315                         if (audit_tree_match(p->c[n], tree))
316                                 return 1;
317         }
318 #endif
319         return 0;
320 }
321
322 static int audit_compare_uid(kuid_t uid,
323                              struct audit_names *name,
324                              struct audit_field *f,
325                              struct audit_context *ctx)
326 {
327         struct audit_names *n;
328         int rc;
329  
330         if (name) {
331                 rc = audit_uid_comparator(uid, f->op, name->uid);
332                 if (rc)
333                         return rc;
334         }
335  
336         if (ctx) {
337                 list_for_each_entry(n, &ctx->names_list, list) {
338                         rc = audit_uid_comparator(uid, f->op, n->uid);
339                         if (rc)
340                                 return rc;
341                 }
342         }
343         return 0;
344 }
345
346 static int audit_compare_gid(kgid_t gid,
347                              struct audit_names *name,
348                              struct audit_field *f,
349                              struct audit_context *ctx)
350 {
351         struct audit_names *n;
352         int rc;
353  
354         if (name) {
355                 rc = audit_gid_comparator(gid, f->op, name->gid);
356                 if (rc)
357                         return rc;
358         }
359  
360         if (ctx) {
361                 list_for_each_entry(n, &ctx->names_list, list) {
362                         rc = audit_gid_comparator(gid, f->op, n->gid);
363                         if (rc)
364                                 return rc;
365                 }
366         }
367         return 0;
368 }
369
370 static int audit_field_compare(struct task_struct *tsk,
371                                const struct cred *cred,
372                                struct audit_field *f,
373                                struct audit_context *ctx,
374                                struct audit_names *name)
375 {
376         switch (f->val) {
377         /* process to file object comparisons */
378         case AUDIT_COMPARE_UID_TO_OBJ_UID:
379                 return audit_compare_uid(cred->uid, name, f, ctx);
380         case AUDIT_COMPARE_GID_TO_OBJ_GID:
381                 return audit_compare_gid(cred->gid, name, f, ctx);
382         case AUDIT_COMPARE_EUID_TO_OBJ_UID:
383                 return audit_compare_uid(cred->euid, name, f, ctx);
384         case AUDIT_COMPARE_EGID_TO_OBJ_GID:
385                 return audit_compare_gid(cred->egid, name, f, ctx);
386         case AUDIT_COMPARE_AUID_TO_OBJ_UID:
387                 return audit_compare_uid(tsk->loginuid, name, f, ctx);
388         case AUDIT_COMPARE_SUID_TO_OBJ_UID:
389                 return audit_compare_uid(cred->suid, name, f, ctx);
390         case AUDIT_COMPARE_SGID_TO_OBJ_GID:
391                 return audit_compare_gid(cred->sgid, name, f, ctx);
392         case AUDIT_COMPARE_FSUID_TO_OBJ_UID:
393                 return audit_compare_uid(cred->fsuid, name, f, ctx);
394         case AUDIT_COMPARE_FSGID_TO_OBJ_GID:
395                 return audit_compare_gid(cred->fsgid, name, f, ctx);
396         /* uid comparisons */
397         case AUDIT_COMPARE_UID_TO_AUID:
398                 return audit_uid_comparator(cred->uid, f->op, tsk->loginuid);
399         case AUDIT_COMPARE_UID_TO_EUID:
400                 return audit_uid_comparator(cred->uid, f->op, cred->euid);
401         case AUDIT_COMPARE_UID_TO_SUID:
402                 return audit_uid_comparator(cred->uid, f->op, cred->suid);
403         case AUDIT_COMPARE_UID_TO_FSUID:
404                 return audit_uid_comparator(cred->uid, f->op, cred->fsuid);
405         /* auid comparisons */
406         case AUDIT_COMPARE_AUID_TO_EUID:
407                 return audit_uid_comparator(tsk->loginuid, f->op, cred->euid);
408         case AUDIT_COMPARE_AUID_TO_SUID:
409                 return audit_uid_comparator(tsk->loginuid, f->op, cred->suid);
410         case AUDIT_COMPARE_AUID_TO_FSUID:
411                 return audit_uid_comparator(tsk->loginuid, f->op, cred->fsuid);
412         /* euid comparisons */
413         case AUDIT_COMPARE_EUID_TO_SUID:
414                 return audit_uid_comparator(cred->euid, f->op, cred->suid);
415         case AUDIT_COMPARE_EUID_TO_FSUID:
416                 return audit_uid_comparator(cred->euid, f->op, cred->fsuid);
417         /* suid comparisons */
418         case AUDIT_COMPARE_SUID_TO_FSUID:
419                 return audit_uid_comparator(cred->suid, f->op, cred->fsuid);
420         /* gid comparisons */
421         case AUDIT_COMPARE_GID_TO_EGID:
422                 return audit_gid_comparator(cred->gid, f->op, cred->egid);
423         case AUDIT_COMPARE_GID_TO_SGID:
424                 return audit_gid_comparator(cred->gid, f->op, cred->sgid);
425         case AUDIT_COMPARE_GID_TO_FSGID:
426                 return audit_gid_comparator(cred->gid, f->op, cred->fsgid);
427         /* egid comparisons */
428         case AUDIT_COMPARE_EGID_TO_SGID:
429                 return audit_gid_comparator(cred->egid, f->op, cred->sgid);
430         case AUDIT_COMPARE_EGID_TO_FSGID:
431                 return audit_gid_comparator(cred->egid, f->op, cred->fsgid);
432         /* sgid comparison */
433         case AUDIT_COMPARE_SGID_TO_FSGID:
434                 return audit_gid_comparator(cred->sgid, f->op, cred->fsgid);
435         default:
436                 WARN(1, "Missing AUDIT_COMPARE define.  Report as a bug\n");
437                 return 0;
438         }
439         return 0;
440 }
441
442 /* Determine if any context name data matches a rule's watch data */
443 /* Compare a task_struct with an audit_rule.  Return 1 on match, 0
444  * otherwise.
445  *
446  * If task_creation is true, this is an explicit indication that we are
447  * filtering a task rule at task creation time.  This and tsk == current are
448  * the only situations where tsk->cred may be accessed without an rcu read lock.
449  */
450 static int audit_filter_rules(struct task_struct *tsk,
451                               struct audit_krule *rule,
452                               struct audit_context *ctx,
453                               struct audit_names *name,
454                               enum audit_state *state,
455                               bool task_creation)
456 {
457         const struct cred *cred;
458         int i, need_sid = 1;
459         u32 sid;
460
461         cred = rcu_dereference_check(tsk->cred, tsk == current || task_creation);
462
463         for (i = 0; i < rule->field_count; i++) {
464                 struct audit_field *f = &rule->fields[i];
465                 struct audit_names *n;
466                 int result = 0;
467
468                 switch (f->type) {
469                 case AUDIT_PID:
470                         result = audit_comparator(tsk->pid, f->op, f->val);
471                         break;
472                 case AUDIT_PPID:
473                         if (ctx) {
474                                 if (!ctx->ppid)
475                                         ctx->ppid = sys_getppid();
476                                 result = audit_comparator(ctx->ppid, f->op, f->val);
477                         }
478                         break;
479                 case AUDIT_UID:
480                         result = audit_uid_comparator(cred->uid, f->op, f->uid);
481                         break;
482                 case AUDIT_EUID:
483                         result = audit_uid_comparator(cred->euid, f->op, f->uid);
484                         break;
485                 case AUDIT_SUID:
486                         result = audit_uid_comparator(cred->suid, f->op, f->uid);
487                         break;
488                 case AUDIT_FSUID:
489                         result = audit_uid_comparator(cred->fsuid, f->op, f->uid);
490                         break;
491                 case AUDIT_GID:
492                         result = audit_gid_comparator(cred->gid, f->op, f->gid);
493                         if (f->op == Audit_equal) {
494                                 if (!result)
495                                         result = in_group_p(f->gid);
496                         } else if (f->op == Audit_not_equal) {
497                                 if (result)
498                                         result = !in_group_p(f->gid);
499                         }
500                         break;
501                 case AUDIT_EGID:
502                         result = audit_gid_comparator(cred->egid, f->op, f->gid);
503                         if (f->op == Audit_equal) {
504                                 if (!result)
505                                         result = in_egroup_p(f->gid);
506                         } else if (f->op == Audit_not_equal) {
507                                 if (result)
508                                         result = !in_egroup_p(f->gid);
509                         }
510                         break;
511                 case AUDIT_SGID:
512                         result = audit_gid_comparator(cred->sgid, f->op, f->gid);
513                         break;
514                 case AUDIT_FSGID:
515                         result = audit_gid_comparator(cred->fsgid, f->op, f->gid);
516                         break;
517                 case AUDIT_PERS:
518                         result = audit_comparator(tsk->personality, f->op, f->val);
519                         break;
520                 case AUDIT_ARCH:
521                         if (ctx)
522                                 result = audit_comparator(ctx->arch, f->op, f->val);
523                         break;
524
525                 case AUDIT_EXIT:
526                         if (ctx && ctx->return_valid)
527                                 result = audit_comparator(ctx->return_code, f->op, f->val);
528                         break;
529                 case AUDIT_SUCCESS:
530                         if (ctx && ctx->return_valid) {
531                                 if (f->val)
532                                         result = audit_comparator(ctx->return_valid, f->op, AUDITSC_SUCCESS);
533                                 else
534                                         result = audit_comparator(ctx->return_valid, f->op, AUDITSC_FAILURE);
535                         }
536                         break;
537                 case AUDIT_DEVMAJOR:
538                         if (name) {
539                                 if (audit_comparator(MAJOR(name->dev), f->op, f->val) ||
540                                     audit_comparator(MAJOR(name->rdev), f->op, f->val))
541                                         ++result;
542                         } else if (ctx) {
543                                 list_for_each_entry(n, &ctx->names_list, list) {
544                                         if (audit_comparator(MAJOR(n->dev), f->op, f->val) ||
545                                             audit_comparator(MAJOR(n->rdev), f->op, f->val)) {
546                                                 ++result;
547                                                 break;
548                                         }
549                                 }
550                         }
551                         break;
552                 case AUDIT_DEVMINOR:
553                         if (name) {
554                                 if (audit_comparator(MINOR(name->dev), f->op, f->val) ||
555                                     audit_comparator(MINOR(name->rdev), f->op, f->val))
556                                         ++result;
557                         } else if (ctx) {
558                                 list_for_each_entry(n, &ctx->names_list, list) {
559                                         if (audit_comparator(MINOR(n->dev), f->op, f->val) ||
560                                             audit_comparator(MINOR(n->rdev), f->op, f->val)) {
561                                                 ++result;
562                                                 break;
563                                         }
564                                 }
565                         }
566                         break;
567                 case AUDIT_INODE:
568                         if (name)
569                                 result = (name->ino == f->val);
570                         else if (ctx) {
571                                 list_for_each_entry(n, &ctx->names_list, list) {
572                                         if (audit_comparator(n->ino, f->op, f->val)) {
573                                                 ++result;
574                                                 break;
575                                         }
576                                 }
577                         }
578                         break;
579                 case AUDIT_OBJ_UID:
580                         if (name) {
581                                 result = audit_uid_comparator(name->uid, f->op, f->uid);
582                         } else if (ctx) {
583                                 list_for_each_entry(n, &ctx->names_list, list) {
584                                         if (audit_uid_comparator(n->uid, f->op, f->uid)) {
585                                                 ++result;
586                                                 break;
587                                         }
588                                 }
589                         }
590                         break;
591                 case AUDIT_OBJ_GID:
592                         if (name) {
593                                 result = audit_gid_comparator(name->gid, f->op, f->gid);
594                         } else if (ctx) {
595                                 list_for_each_entry(n, &ctx->names_list, list) {
596                                         if (audit_gid_comparator(n->gid, f->op, f->gid)) {
597                                                 ++result;
598                                                 break;
599                                         }
600                                 }
601                         }
602                         break;
603                 case AUDIT_WATCH:
604                         if (name)
605                                 result = audit_watch_compare(rule->watch, name->ino, name->dev);
606                         break;
607                 case AUDIT_DIR:
608                         if (ctx)
609                                 result = match_tree_refs(ctx, rule->tree);
610                         break;
611                 case AUDIT_LOGINUID:
612                         result = 0;
613                         if (ctx)
614                                 result = audit_uid_comparator(tsk->loginuid, f->op, f->uid);
615                         break;
616                 case AUDIT_LOGINUID_SET:
617                         result = audit_comparator(audit_loginuid_set(tsk), f->op, f->val);
618                         break;
619                 case AUDIT_SUBJ_USER:
620                 case AUDIT_SUBJ_ROLE:
621                 case AUDIT_SUBJ_TYPE:
622                 case AUDIT_SUBJ_SEN:
623                 case AUDIT_SUBJ_CLR:
624                         /* NOTE: this may return negative values indicating
625                            a temporary error.  We simply treat this as a
626                            match for now to avoid losing information that
627                            may be wanted.   An error message will also be
628                            logged upon error */
629                         if (f->lsm_rule) {
630                                 if (need_sid) {
631                                         security_task_getsecid(tsk, &sid);
632                                         need_sid = 0;
633                                 }
634                                 result = security_audit_rule_match(sid, f->type,
635                                                                   f->op,
636                                                                   f->lsm_rule,
637                                                                   ctx);
638                         }
639                         break;
640                 case AUDIT_OBJ_USER:
641                 case AUDIT_OBJ_ROLE:
642                 case AUDIT_OBJ_TYPE:
643                 case AUDIT_OBJ_LEV_LOW:
644                 case AUDIT_OBJ_LEV_HIGH:
645                         /* The above note for AUDIT_SUBJ_USER...AUDIT_SUBJ_CLR
646                            also applies here */
647                         if (f->lsm_rule) {
648                                 /* Find files that match */
649                                 if (name) {
650                                         result = security_audit_rule_match(
651                                                    name->osid, f->type, f->op,
652                                                    f->lsm_rule, ctx);
653                                 } else if (ctx) {
654                                         list_for_each_entry(n, &ctx->names_list, list) {
655                                                 if (security_audit_rule_match(n->osid, f->type,
656                                                                               f->op, f->lsm_rule,
657                                                                               ctx)) {
658                                                         ++result;
659                                                         break;
660                                                 }
661                                         }
662                                 }
663                                 /* Find ipc objects that match */
664                                 if (!ctx || ctx->type != AUDIT_IPC)
665                                         break;
666                                 if (security_audit_rule_match(ctx->ipc.osid,
667                                                               f->type, f->op,
668                                                               f->lsm_rule, ctx))
669                                         ++result;
670                         }
671                         break;
672                 case AUDIT_ARG0:
673                 case AUDIT_ARG1:
674                 case AUDIT_ARG2:
675                 case AUDIT_ARG3:
676                         if (ctx)
677                                 result = audit_comparator(ctx->argv[f->type-AUDIT_ARG0], f->op, f->val);
678                         break;
679                 case AUDIT_FILTERKEY:
680                         /* ignore this field for filtering */
681                         result = 1;
682                         break;
683                 case AUDIT_PERM:
684                         result = audit_match_perm(ctx, f->val);
685                         break;
686                 case AUDIT_FILETYPE:
687                         result = audit_match_filetype(ctx, f->val);
688                         break;
689                 case AUDIT_FIELD_COMPARE:
690                         result = audit_field_compare(tsk, cred, f, ctx, name);
691                         break;
692                 }
693                 if (!result)
694                         return 0;
695         }
696
697         if (ctx) {
698                 if (rule->prio <= ctx->prio)
699                         return 0;
700                 if (rule->filterkey) {
701                         kfree(ctx->filterkey);
702                         ctx->filterkey = kstrdup(rule->filterkey, GFP_ATOMIC);
703                 }
704                 ctx->prio = rule->prio;
705         }
706         switch (rule->action) {
707         case AUDIT_NEVER:    *state = AUDIT_DISABLED;       break;
708         case AUDIT_ALWAYS:   *state = AUDIT_RECORD_CONTEXT; break;
709         }
710         return 1;
711 }
712
713 /* At process creation time, we can determine if system-call auditing is
714  * completely disabled for this task.  Since we only have the task
715  * structure at this point, we can only check uid and gid.
716  */
717 static enum audit_state audit_filter_task(struct task_struct *tsk, char **key)
718 {
719         struct audit_entry *e;
720         enum audit_state   state;
721
722         rcu_read_lock();
723         list_for_each_entry_rcu(e, &audit_filter_list[AUDIT_FILTER_TASK], list) {
724                 if (audit_filter_rules(tsk, &e->rule, NULL, NULL,
725                                        &state, true)) {
726                         if (state == AUDIT_RECORD_CONTEXT)
727                                 *key = kstrdup(e->rule.filterkey, GFP_ATOMIC);
728                         rcu_read_unlock();
729                         return state;
730                 }
731         }
732         rcu_read_unlock();
733         return AUDIT_BUILD_CONTEXT;
734 }
735
736 /* At syscall entry and exit time, this filter is called if the
737  * audit_state is not low enough that auditing cannot take place, but is
738  * also not high enough that we already know we have to write an audit
739  * record (i.e., the state is AUDIT_SETUP_CONTEXT or AUDIT_BUILD_CONTEXT).
740  */
741 static enum audit_state audit_filter_syscall(struct task_struct *tsk,
742                                              struct audit_context *ctx,
743                                              struct list_head *list)
744 {
745         struct audit_entry *e;
746         enum audit_state state;
747
748         if (audit_pid && tsk->tgid == audit_pid)
749                 return AUDIT_DISABLED;
750
751         rcu_read_lock();
752         if (!list_empty(list)) {
753                 int word = AUDIT_WORD(ctx->major);
754                 int bit  = AUDIT_BIT(ctx->major);
755
756                 list_for_each_entry_rcu(e, list, list) {
757                         if ((e->rule.mask[word] & bit) == bit &&
758                             audit_filter_rules(tsk, &e->rule, ctx, NULL,
759                                                &state, false)) {
760                                 rcu_read_unlock();
761                                 ctx->current_state = state;
762                                 return state;
763                         }
764                 }
765         }
766         rcu_read_unlock();
767         return AUDIT_BUILD_CONTEXT;
768 }
769
770 /*
771  * Given an audit_name check the inode hash table to see if they match.
772  * Called holding the rcu read lock to protect the use of audit_inode_hash
773  */
774 static int audit_filter_inode_name(struct task_struct *tsk,
775                                    struct audit_names *n,
776                                    struct audit_context *ctx) {
777         int word, bit;
778         int h = audit_hash_ino((u32)n->ino);
779         struct list_head *list = &audit_inode_hash[h];
780         struct audit_entry *e;
781         enum audit_state state;
782
783         word = AUDIT_WORD(ctx->major);
784         bit  = AUDIT_BIT(ctx->major);
785
786         if (list_empty(list))
787                 return 0;
788
789         list_for_each_entry_rcu(e, list, list) {
790                 if ((e->rule.mask[word] & bit) == bit &&
791                     audit_filter_rules(tsk, &e->rule, ctx, n, &state, false)) {
792                         ctx->current_state = state;
793                         return 1;
794                 }
795         }
796
797         return 0;
798 }
799
800 /* At syscall exit time, this filter is called if any audit_names have been
801  * collected during syscall processing.  We only check rules in sublists at hash
802  * buckets applicable to the inode numbers in audit_names.
803  * Regarding audit_state, same rules apply as for audit_filter_syscall().
804  */
805 void audit_filter_inodes(struct task_struct *tsk, struct audit_context *ctx)
806 {
807         struct audit_names *n;
808
809         if (audit_pid && tsk->tgid == audit_pid)
810                 return;
811
812         rcu_read_lock();
813
814         list_for_each_entry(n, &ctx->names_list, list) {
815                 if (audit_filter_inode_name(tsk, n, ctx))
816                         break;
817         }
818         rcu_read_unlock();
819 }
820
821 static inline struct audit_context *audit_get_context(struct task_struct *tsk,
822                                                       int return_valid,
823                                                       long return_code)
824 {
825         struct audit_context *context = tsk->audit_context;
826
827         if (!context)
828                 return NULL;
829         context->return_valid = return_valid;
830
831         /*
832          * we need to fix up the return code in the audit logs if the actual
833          * return codes are later going to be fixed up by the arch specific
834          * signal handlers
835          *
836          * This is actually a test for:
837          * (rc == ERESTARTSYS ) || (rc == ERESTARTNOINTR) ||
838          * (rc == ERESTARTNOHAND) || (rc == ERESTART_RESTARTBLOCK)
839          *
840          * but is faster than a bunch of ||
841          */
842         if (unlikely(return_code <= -ERESTARTSYS) &&
843             (return_code >= -ERESTART_RESTARTBLOCK) &&
844             (return_code != -ENOIOCTLCMD))
845                 context->return_code = -EINTR;
846         else
847                 context->return_code  = return_code;
848
849         if (context->in_syscall && !context->dummy) {
850                 audit_filter_syscall(tsk, context, &audit_filter_list[AUDIT_FILTER_EXIT]);
851                 audit_filter_inodes(tsk, context);
852         }
853
854         tsk->audit_context = NULL;
855         return context;
856 }
857
858 static inline void audit_free_names(struct audit_context *context)
859 {
860         struct audit_names *n, *next;
861
862 #if AUDIT_DEBUG == 2
863         if (context->put_count + context->ino_count != context->name_count) {
864                 int i = 0;
865
866                 printk(KERN_ERR "%s:%d(:%d): major=%d in_syscall=%d"
867                        " name_count=%d put_count=%d"
868                        " ino_count=%d [NOT freeing]\n",
869                        __FILE__, __LINE__,
870                        context->serial, context->major, context->in_syscall,
871                        context->name_count, context->put_count,
872                        context->ino_count);
873                 list_for_each_entry(n, &context->names_list, list) {
874                         printk(KERN_ERR "names[%d] = %p = %s\n", i++,
875                                n->name, n->name->name ?: "(null)");
876                 }
877                 dump_stack();
878                 return;
879         }
880 #endif
881 #if AUDIT_DEBUG
882         context->put_count  = 0;
883         context->ino_count  = 0;
884 #endif
885
886         list_for_each_entry_safe(n, next, &context->names_list, list) {
887                 list_del(&n->list);
888                 if (n->name && n->name_put)
889                         final_putname(n->name);
890                 if (n->should_free)
891                         kfree(n);
892         }
893         context->name_count = 0;
894         path_put(&context->pwd);
895         context->pwd.dentry = NULL;
896         context->pwd.mnt = NULL;
897 }
898
899 static inline void audit_free_aux(struct audit_context *context)
900 {
901         struct audit_aux_data *aux;
902
903         while ((aux = context->aux)) {
904                 context->aux = aux->next;
905                 kfree(aux);
906         }
907         while ((aux = context->aux_pids)) {
908                 context->aux_pids = aux->next;
909                 kfree(aux);
910         }
911 }
912
913 static inline struct audit_context *audit_alloc_context(enum audit_state state)
914 {
915         struct audit_context *context;
916
917         context = kzalloc(sizeof(*context), GFP_KERNEL);
918         if (!context)
919                 return NULL;
920         context->state = state;
921         context->prio = state == AUDIT_RECORD_CONTEXT ? ~0ULL : 0;
922         INIT_LIST_HEAD(&context->killed_trees);
923         INIT_LIST_HEAD(&context->names_list);
924         return context;
925 }
926
927 /**
928  * audit_alloc - allocate an audit context block for a task
929  * @tsk: task
930  *
931  * Filter on the task information and allocate a per-task audit context
932  * if necessary.  Doing so turns on system call auditing for the
933  * specified task.  This is called from copy_process, so no lock is
934  * needed.
935  */
936 int audit_alloc(struct task_struct *tsk)
937 {
938         struct audit_context *context;
939         enum audit_state     state;
940         char *key = NULL;
941
942         if (likely(!audit_ever_enabled))
943                 return 0; /* Return if not auditing. */
944
945         state = audit_filter_task(tsk, &key);
946         if (state == AUDIT_DISABLED) {
947                 clear_tsk_thread_flag(tsk, TIF_SYSCALL_AUDIT);
948                 return 0;
949         }
950
951         if (!(context = audit_alloc_context(state))) {
952                 kfree(key);
953                 audit_log_lost("out of memory in audit_alloc");
954                 return -ENOMEM;
955         }
956         context->filterkey = key;
957
958         tsk->audit_context  = context;
959         set_tsk_thread_flag(tsk, TIF_SYSCALL_AUDIT);
960         return 0;
961 }
962
963 static inline void audit_free_context(struct audit_context *context)
964 {
965         audit_free_names(context);
966         unroll_tree_refs(context, NULL, 0);
967         free_tree_refs(context);
968         audit_free_aux(context);
969         kfree(context->filterkey);
970         kfree(context->sockaddr);
971         kfree(context);
972 }
973
974 static int audit_log_pid_context(struct audit_context *context, pid_t pid,
975                                  kuid_t auid, kuid_t uid, unsigned int sessionid,
976                                  u32 sid, char *comm)
977 {
978         struct audit_buffer *ab;
979         char *ctx = NULL;
980         u32 len;
981         int rc = 0;
982
983         ab = audit_log_start(context, GFP_KERNEL, AUDIT_OBJ_PID);
984         if (!ab)
985                 return rc;
986
987         audit_log_format(ab, "opid=%d oauid=%d ouid=%d oses=%d", pid,
988                          from_kuid(&init_user_ns, auid),
989                          from_kuid(&init_user_ns, uid), sessionid);
990         if (sid) {
991                 if (security_secid_to_secctx(sid, &ctx, &len)) {
992                         audit_log_format(ab, " obj=(none)");
993                         rc = 1;
994                 } else {
995                         audit_log_format(ab, " obj=%s", ctx);
996                         security_release_secctx(ctx, len);
997                 }
998         }
999         audit_log_format(ab, " ocomm=");
1000         audit_log_untrustedstring(ab, comm);
1001         audit_log_end(ab);
1002
1003         return rc;
1004 }
1005
1006 /*
1007  * to_send and len_sent accounting are very loose estimates.  We aren't
1008  * really worried about a hard cap to MAX_EXECVE_AUDIT_LEN so much as being
1009  * within about 500 bytes (next page boundary)
1010  *
1011  * why snprintf?  an int is up to 12 digits long.  if we just assumed when
1012  * logging that a[%d]= was going to be 16 characters long we would be wasting
1013  * space in every audit message.  In one 7500 byte message we can log up to
1014  * about 1000 min size arguments.  That comes down to about 50% waste of space
1015  * if we didn't do the snprintf to find out how long arg_num_len was.
1016  */
1017 static int audit_log_single_execve_arg(struct audit_context *context,
1018                                         struct audit_buffer **ab,
1019                                         int arg_num,
1020                                         size_t *len_sent,
1021                                         const char __user *p,
1022                                         char *buf)
1023 {
1024         char arg_num_len_buf[12];
1025         const char __user *tmp_p = p;
1026         /* how many digits are in arg_num? 5 is the length of ' a=""' */
1027         size_t arg_num_len = snprintf(arg_num_len_buf, 12, "%d", arg_num) + 5;
1028         size_t len, len_left, to_send;
1029         size_t max_execve_audit_len = MAX_EXECVE_AUDIT_LEN;
1030         unsigned int i, has_cntl = 0, too_long = 0;
1031         int ret;
1032
1033         /* strnlen_user includes the null we don't want to send */
1034         len_left = len = strnlen_user(p, MAX_ARG_STRLEN) - 1;
1035
1036         /*
1037          * We just created this mm, if we can't find the strings
1038          * we just copied into it something is _very_ wrong. Similar
1039          * for strings that are too long, we should not have created
1040          * any.
1041          */
1042         if (unlikely((len == -1) || len > MAX_ARG_STRLEN - 1)) {
1043                 WARN_ON(1);
1044                 send_sig(SIGKILL, current, 0);
1045                 return -1;
1046         }
1047
1048         /* walk the whole argument looking for non-ascii chars */
1049         do {
1050                 if (len_left > MAX_EXECVE_AUDIT_LEN)
1051                         to_send = MAX_EXECVE_AUDIT_LEN;
1052                 else
1053                         to_send = len_left;
1054                 ret = copy_from_user(buf, tmp_p, to_send);
1055                 /*
1056                  * There is no reason for this copy to be short. We just
1057                  * copied them here, and the mm hasn't been exposed to user-
1058                  * space yet.
1059                  */
1060                 if (ret) {
1061                         WARN_ON(1);
1062                         send_sig(SIGKILL, current, 0);
1063                         return -1;
1064                 }
1065                 buf[to_send] = '\0';
1066                 has_cntl = audit_string_contains_control(buf, to_send);
1067                 if (has_cntl) {
1068                         /*
1069                          * hex messages get logged as 2 bytes, so we can only
1070                          * send half as much in each message
1071                          */
1072                         max_execve_audit_len = MAX_EXECVE_AUDIT_LEN / 2;
1073                         break;
1074                 }
1075                 len_left -= to_send;
1076                 tmp_p += to_send;
1077         } while (len_left > 0);
1078
1079         len_left = len;
1080
1081         if (len > max_execve_audit_len)
1082                 too_long = 1;
1083
1084         /* rewalk the argument actually logging the message */
1085         for (i = 0; len_left > 0; i++) {
1086                 int room_left;
1087
1088                 if (len_left > max_execve_audit_len)
1089                         to_send = max_execve_audit_len;
1090                 else
1091                         to_send = len_left;
1092
1093                 /* do we have space left to send this argument in this ab? */
1094                 room_left = MAX_EXECVE_AUDIT_LEN - arg_num_len - *len_sent;
1095                 if (has_cntl)
1096                         room_left -= (to_send * 2);
1097                 else
1098                         room_left -= to_send;
1099                 if (room_left < 0) {
1100                         *len_sent = 0;
1101                         audit_log_end(*ab);
1102                         *ab = audit_log_start(context, GFP_KERNEL, AUDIT_EXECVE);
1103                         if (!*ab)
1104                                 return 0;
1105                 }
1106
1107                 /*
1108                  * first record needs to say how long the original string was
1109                  * so we can be sure nothing was lost.
1110                  */
1111                 if ((i == 0) && (too_long))
1112                         audit_log_format(*ab, " a%d_len=%zu", arg_num,
1113                                          has_cntl ? 2*len : len);
1114
1115                 /*
1116                  * normally arguments are small enough to fit and we already
1117                  * filled buf above when we checked for control characters
1118                  * so don't bother with another copy_from_user
1119                  */
1120                 if (len >= max_execve_audit_len)
1121                         ret = copy_from_user(buf, p, to_send);
1122                 else
1123                         ret = 0;
1124                 if (ret) {
1125                         WARN_ON(1);
1126                         send_sig(SIGKILL, current, 0);
1127                         return -1;
1128                 }
1129                 buf[to_send] = '\0';
1130
1131                 /* actually log it */
1132                 audit_log_format(*ab, " a%d", arg_num);
1133                 if (too_long)
1134                         audit_log_format(*ab, "[%d]", i);
1135                 audit_log_format(*ab, "=");
1136                 if (has_cntl)
1137                         audit_log_n_hex(*ab, buf, to_send);
1138                 else
1139                         audit_log_string(*ab, buf);
1140
1141                 p += to_send;
1142                 len_left -= to_send;
1143                 *len_sent += arg_num_len;
1144                 if (has_cntl)
1145                         *len_sent += to_send * 2;
1146                 else
1147                         *len_sent += to_send;
1148         }
1149         /* include the null we didn't log */
1150         return len + 1;
1151 }
1152
1153 static void audit_log_execve_info(struct audit_context *context,
1154                                   struct audit_buffer **ab,
1155                                   struct audit_aux_data_execve *axi)
1156 {
1157         int i, len;
1158         size_t len_sent = 0;
1159         const char __user *p;
1160         char *buf;
1161
1162         if (axi->mm != current->mm)
1163                 return; /* execve failed, no additional info */
1164
1165         p = (const char __user *)axi->mm->arg_start;
1166
1167         audit_log_format(*ab, "argc=%d", axi->argc);
1168
1169         /*
1170          * we need some kernel buffer to hold the userspace args.  Just
1171          * allocate one big one rather than allocating one of the right size
1172          * for every single argument inside audit_log_single_execve_arg()
1173          * should be <8k allocation so should be pretty safe.
1174          */
1175         buf = kmalloc(MAX_EXECVE_AUDIT_LEN + 1, GFP_KERNEL);
1176         if (!buf) {
1177                 audit_panic("out of memory for argv string\n");
1178                 return;
1179         }
1180
1181         for (i = 0; i < axi->argc; i++) {
1182                 len = audit_log_single_execve_arg(context, ab, i,
1183                                                   &len_sent, p, buf);
1184                 if (len <= 0)
1185                         break;
1186                 p += len;
1187         }
1188         kfree(buf);
1189 }
1190
1191 static void show_special(struct audit_context *context, int *call_panic)
1192 {
1193         struct audit_buffer *ab;
1194         int i;
1195
1196         ab = audit_log_start(context, GFP_KERNEL, context->type);
1197         if (!ab)
1198                 return;
1199
1200         switch (context->type) {
1201         case AUDIT_SOCKETCALL: {
1202                 int nargs = context->socketcall.nargs;
1203                 audit_log_format(ab, "nargs=%d", nargs);
1204                 for (i = 0; i < nargs; i++)
1205                         audit_log_format(ab, " a%d=%lx", i,
1206                                 context->socketcall.args[i]);
1207                 break; }
1208         case AUDIT_IPC: {
1209                 u32 osid = context->ipc.osid;
1210
1211                 audit_log_format(ab, "ouid=%u ogid=%u mode=%#ho",
1212                                  from_kuid(&init_user_ns, context->ipc.uid),
1213                                  from_kgid(&init_user_ns, context->ipc.gid),
1214                                  context->ipc.mode);
1215                 if (osid) {
1216                         char *ctx = NULL;
1217                         u32 len;
1218                         if (security_secid_to_secctx(osid, &ctx, &len)) {
1219                                 audit_log_format(ab, " osid=%u", osid);
1220                                 *call_panic = 1;
1221                         } else {
1222                                 audit_log_format(ab, " obj=%s", ctx);
1223                                 security_release_secctx(ctx, len);
1224                         }
1225                 }
1226                 if (context->ipc.has_perm) {
1227                         audit_log_end(ab);
1228                         ab = audit_log_start(context, GFP_KERNEL,
1229                                              AUDIT_IPC_SET_PERM);
1230                         if (unlikely(!ab))
1231                                 return;
1232                         audit_log_format(ab,
1233                                 "qbytes=%lx ouid=%u ogid=%u mode=%#ho",
1234                                 context->ipc.qbytes,
1235                                 context->ipc.perm_uid,
1236                                 context->ipc.perm_gid,
1237                                 context->ipc.perm_mode);
1238                 }
1239                 break; }
1240         case AUDIT_MQ_OPEN: {
1241                 audit_log_format(ab,
1242                         "oflag=0x%x mode=%#ho mq_flags=0x%lx mq_maxmsg=%ld "
1243                         "mq_msgsize=%ld mq_curmsgs=%ld",
1244                         context->mq_open.oflag, context->mq_open.mode,
1245                         context->mq_open.attr.mq_flags,
1246                         context->mq_open.attr.mq_maxmsg,
1247                         context->mq_open.attr.mq_msgsize,
1248                         context->mq_open.attr.mq_curmsgs);
1249                 break; }
1250         case AUDIT_MQ_SENDRECV: {
1251                 audit_log_format(ab,
1252                         "mqdes=%d msg_len=%zd msg_prio=%u "
1253                         "abs_timeout_sec=%ld abs_timeout_nsec=%ld",
1254                         context->mq_sendrecv.mqdes,
1255                         context->mq_sendrecv.msg_len,
1256                         context->mq_sendrecv.msg_prio,
1257                         context->mq_sendrecv.abs_timeout.tv_sec,
1258                         context->mq_sendrecv.abs_timeout.tv_nsec);
1259                 break; }
1260         case AUDIT_MQ_NOTIFY: {
1261                 audit_log_format(ab, "mqdes=%d sigev_signo=%d",
1262                                 context->mq_notify.mqdes,
1263                                 context->mq_notify.sigev_signo);
1264                 break; }
1265         case AUDIT_MQ_GETSETATTR: {
1266                 struct mq_attr *attr = &context->mq_getsetattr.mqstat;
1267                 audit_log_format(ab,
1268                         "mqdes=%d mq_flags=0x%lx mq_maxmsg=%ld mq_msgsize=%ld "
1269                         "mq_curmsgs=%ld ",
1270                         context->mq_getsetattr.mqdes,
1271                         attr->mq_flags, attr->mq_maxmsg,
1272                         attr->mq_msgsize, attr->mq_curmsgs);
1273                 break; }
1274         case AUDIT_CAPSET: {
1275                 audit_log_format(ab, "pid=%d", context->capset.pid);
1276                 audit_log_cap(ab, "cap_pi", &context->capset.cap.inheritable);
1277                 audit_log_cap(ab, "cap_pp", &context->capset.cap.permitted);
1278                 audit_log_cap(ab, "cap_pe", &context->capset.cap.effective);
1279                 break; }
1280         case AUDIT_MMAP: {
1281                 audit_log_format(ab, "fd=%d flags=0x%x", context->mmap.fd,
1282                                  context->mmap.flags);
1283                 break; }
1284         }
1285         audit_log_end(ab);
1286 }
1287
1288 static void audit_log_exit(struct audit_context *context, struct task_struct *tsk)
1289 {
1290         int i, call_panic = 0;
1291         struct audit_buffer *ab;
1292         struct audit_aux_data *aux;
1293         struct audit_names *n;
1294
1295         /* tsk == current */
1296         context->personality = tsk->personality;
1297
1298         ab = audit_log_start(context, GFP_KERNEL, AUDIT_SYSCALL);
1299         if (!ab)
1300                 return;         /* audit_panic has been called */
1301         audit_log_format(ab, "arch=%x syscall=%d",
1302                          context->arch, context->major);
1303         if (context->personality != PER_LINUX)
1304                 audit_log_format(ab, " per=%lx", context->personality);
1305         if (context->return_valid)
1306                 audit_log_format(ab, " success=%s exit=%ld",
1307                                  (context->return_valid==AUDITSC_SUCCESS)?"yes":"no",
1308                                  context->return_code);
1309
1310         audit_log_format(ab,
1311                          " a0=%lx a1=%lx a2=%lx a3=%lx items=%d",
1312                          context->argv[0],
1313                          context->argv[1],
1314                          context->argv[2],
1315                          context->argv[3],
1316                          context->name_count);
1317
1318         audit_log_task_info(ab, tsk);
1319         audit_log_key(ab, context->filterkey);
1320         audit_log_end(ab);
1321
1322         for (aux = context->aux; aux; aux = aux->next) {
1323
1324                 ab = audit_log_start(context, GFP_KERNEL, aux->type);
1325                 if (!ab)
1326                         continue; /* audit_panic has been called */
1327
1328                 switch (aux->type) {
1329
1330                 case AUDIT_EXECVE: {
1331                         struct audit_aux_data_execve *axi = (void *)aux;
1332                         audit_log_execve_info(context, &ab, axi);
1333                         break; }
1334
1335                 case AUDIT_BPRM_FCAPS: {
1336                         struct audit_aux_data_bprm_fcaps *axs = (void *)aux;
1337                         audit_log_format(ab, "fver=%x", axs->fcap_ver);
1338                         audit_log_cap(ab, "fp", &axs->fcap.permitted);
1339                         audit_log_cap(ab, "fi", &axs->fcap.inheritable);
1340                         audit_log_format(ab, " fe=%d", axs->fcap.fE);
1341                         audit_log_cap(ab, "old_pp", &axs->old_pcap.permitted);
1342                         audit_log_cap(ab, "old_pi", &axs->old_pcap.inheritable);
1343                         audit_log_cap(ab, "old_pe", &axs->old_pcap.effective);
1344                         audit_log_cap(ab, "new_pp", &axs->new_pcap.permitted);
1345                         audit_log_cap(ab, "new_pi", &axs->new_pcap.inheritable);
1346                         audit_log_cap(ab, "new_pe", &axs->new_pcap.effective);
1347                         break; }
1348
1349                 }
1350                 audit_log_end(ab);
1351         }
1352
1353         if (context->type)
1354                 show_special(context, &call_panic);
1355
1356         if (context->fds[0] >= 0) {
1357                 ab = audit_log_start(context, GFP_KERNEL, AUDIT_FD_PAIR);
1358                 if (ab) {
1359                         audit_log_format(ab, "fd0=%d fd1=%d",
1360                                         context->fds[0], context->fds[1]);
1361                         audit_log_end(ab);
1362                 }
1363         }
1364
1365         if (context->sockaddr_len) {
1366                 ab = audit_log_start(context, GFP_KERNEL, AUDIT_SOCKADDR);
1367                 if (ab) {
1368                         audit_log_format(ab, "saddr=");
1369                         audit_log_n_hex(ab, (void *)context->sockaddr,
1370                                         context->sockaddr_len);
1371                         audit_log_end(ab);
1372                 }
1373         }
1374
1375         for (aux = context->aux_pids; aux; aux = aux->next) {
1376                 struct audit_aux_data_pids *axs = (void *)aux;
1377
1378                 for (i = 0; i < axs->pid_count; i++)
1379                         if (audit_log_pid_context(context, axs->target_pid[i],
1380                                                   axs->target_auid[i],
1381                                                   axs->target_uid[i],
1382                                                   axs->target_sessionid[i],
1383                                                   axs->target_sid[i],
1384                                                   axs->target_comm[i]))
1385                                 call_panic = 1;
1386         }
1387
1388         if (context->target_pid &&
1389             audit_log_pid_context(context, context->target_pid,
1390                                   context->target_auid, context->target_uid,
1391                                   context->target_sessionid,
1392                                   context->target_sid, context->target_comm))
1393                         call_panic = 1;
1394
1395         if (context->pwd.dentry && context->pwd.mnt) {
1396                 ab = audit_log_start(context, GFP_KERNEL, AUDIT_CWD);
1397                 if (ab) {
1398                         audit_log_d_path(ab, " cwd=", &context->pwd);
1399                         audit_log_end(ab);
1400                 }
1401         }
1402
1403         i = 0;
1404         list_for_each_entry(n, &context->names_list, list) {
1405                 if (n->hidden)
1406                         continue;
1407                 audit_log_name(context, n, NULL, i++, &call_panic);
1408         }
1409
1410         /* Send end of event record to help user space know we are finished */
1411         ab = audit_log_start(context, GFP_KERNEL, AUDIT_EOE);
1412         if (ab)
1413                 audit_log_end(ab);
1414         if (call_panic)
1415                 audit_panic("error converting sid to string");
1416 }
1417
1418 /**
1419  * audit_free - free a per-task audit context
1420  * @tsk: task whose audit context block to free
1421  *
1422  * Called from copy_process and do_exit
1423  */
1424 void __audit_free(struct task_struct *tsk)
1425 {
1426         struct audit_context *context;
1427
1428         context = audit_get_context(tsk, 0, 0);
1429         if (!context)
1430                 return;
1431
1432         /* Check for system calls that do not go through the exit
1433          * function (e.g., exit_group), then free context block.
1434          * We use GFP_ATOMIC here because we might be doing this
1435          * in the context of the idle thread */
1436         /* that can happen only if we are called from do_exit() */
1437         if (context->in_syscall && context->current_state == AUDIT_RECORD_CONTEXT)
1438                 audit_log_exit(context, tsk);
1439         if (!list_empty(&context->killed_trees))
1440                 audit_kill_trees(&context->killed_trees);
1441
1442         audit_free_context(context);
1443 }
1444
1445 /**
1446  * audit_syscall_entry - fill in an audit record at syscall entry
1447  * @arch: architecture type
1448  * @major: major syscall type (function)
1449  * @a1: additional syscall register 1
1450  * @a2: additional syscall register 2
1451  * @a3: additional syscall register 3
1452  * @a4: additional syscall register 4
1453  *
1454  * Fill in audit context at syscall entry.  This only happens if the
1455  * audit context was created when the task was created and the state or
1456  * filters demand the audit context be built.  If the state from the
1457  * per-task filter or from the per-syscall filter is AUDIT_RECORD_CONTEXT,
1458  * then the record will be written at syscall exit time (otherwise, it
1459  * will only be written if another part of the kernel requests that it
1460  * be written).
1461  */
1462 void __audit_syscall_entry(int arch, int major,
1463                          unsigned long a1, unsigned long a2,
1464                          unsigned long a3, unsigned long a4)
1465 {
1466         struct task_struct *tsk = current;
1467         struct audit_context *context = tsk->audit_context;
1468         enum audit_state     state;
1469
1470         if (!context)
1471                 return;
1472
1473         BUG_ON(context->in_syscall || context->name_count);
1474
1475         if (!audit_enabled)
1476                 return;
1477
1478         context->arch       = arch;
1479         context->major      = major;
1480         context->argv[0]    = a1;
1481         context->argv[1]    = a2;
1482         context->argv[2]    = a3;
1483         context->argv[3]    = a4;
1484
1485         state = context->state;
1486         context->dummy = !audit_n_rules;
1487         if (!context->dummy && state == AUDIT_BUILD_CONTEXT) {
1488                 context->prio = 0;
1489                 state = audit_filter_syscall(tsk, context, &audit_filter_list[AUDIT_FILTER_ENTRY]);
1490         }
1491         if (state == AUDIT_DISABLED)
1492                 return;
1493
1494         context->serial     = 0;
1495         context->ctime      = CURRENT_TIME;
1496         context->in_syscall = 1;
1497         context->current_state  = state;
1498         context->ppid       = 0;
1499 }
1500
1501 /**
1502  * audit_syscall_exit - deallocate audit context after a system call
1503  * @success: success value of the syscall
1504  * @return_code: return value of the syscall
1505  *
1506  * Tear down after system call.  If the audit context has been marked as
1507  * auditable (either because of the AUDIT_RECORD_CONTEXT state from
1508  * filtering, or because some other part of the kernel wrote an audit
1509  * message), then write out the syscall information.  In call cases,
1510  * free the names stored from getname().
1511  */
1512 void __audit_syscall_exit(int success, long return_code)
1513 {
1514         struct task_struct *tsk = current;
1515         struct audit_context *context;
1516
1517         if (success)
1518                 success = AUDITSC_SUCCESS;
1519         else
1520                 success = AUDITSC_FAILURE;
1521
1522         context = audit_get_context(tsk, success, return_code);
1523         if (!context)
1524                 return;
1525
1526         if (context->in_syscall && context->current_state == AUDIT_RECORD_CONTEXT)
1527                 audit_log_exit(context, tsk);
1528
1529         context->in_syscall = 0;
1530         context->prio = context->state == AUDIT_RECORD_CONTEXT ? ~0ULL : 0;
1531
1532         if (!list_empty(&context->killed_trees))
1533                 audit_kill_trees(&context->killed_trees);
1534
1535         audit_free_names(context);
1536         unroll_tree_refs(context, NULL, 0);
1537         audit_free_aux(context);
1538         context->aux = NULL;
1539         context->aux_pids = NULL;
1540         context->target_pid = 0;
1541         context->target_sid = 0;
1542         context->sockaddr_len = 0;
1543         context->type = 0;
1544         context->fds[0] = -1;
1545         if (context->state != AUDIT_RECORD_CONTEXT) {
1546                 kfree(context->filterkey);
1547                 context->filterkey = NULL;
1548         }
1549         tsk->audit_context = context;
1550 }
1551
1552 static inline void handle_one(const struct inode *inode)
1553 {
1554 #ifdef CONFIG_AUDIT_TREE
1555         struct audit_context *context;
1556         struct audit_tree_refs *p;
1557         struct audit_chunk *chunk;
1558         int count;
1559         if (likely(hlist_empty(&inode->i_fsnotify_marks)))
1560                 return;
1561         context = current->audit_context;
1562         p = context->trees;
1563         count = context->tree_count;
1564         rcu_read_lock();
1565         chunk = audit_tree_lookup(inode);
1566         rcu_read_unlock();
1567         if (!chunk)
1568                 return;
1569         if (likely(put_tree_ref(context, chunk)))
1570                 return;
1571         if (unlikely(!grow_tree_refs(context))) {
1572                 printk(KERN_WARNING "out of memory, audit has lost a tree reference\n");
1573                 audit_set_auditable(context);
1574                 audit_put_chunk(chunk);
1575                 unroll_tree_refs(context, p, count);
1576                 return;
1577         }
1578         put_tree_ref(context, chunk);
1579 #endif
1580 }
1581
1582 static void handle_path(const struct dentry *dentry)
1583 {
1584 #ifdef CONFIG_AUDIT_TREE
1585         struct audit_context *context;
1586         struct audit_tree_refs *p;
1587         const struct dentry *d, *parent;
1588         struct audit_chunk *drop;
1589         unsigned long seq;
1590         int count;
1591
1592         context = current->audit_context;
1593         p = context->trees;
1594         count = context->tree_count;
1595 retry:
1596         drop = NULL;
1597         d = dentry;
1598         rcu_read_lock();
1599         seq = read_seqbegin(&rename_lock);
1600         for(;;) {
1601                 struct inode *inode = d->d_inode;
1602                 if (inode && unlikely(!hlist_empty(&inode->i_fsnotify_marks))) {
1603                         struct audit_chunk *chunk;
1604                         chunk = audit_tree_lookup(inode);
1605                         if (chunk) {
1606                                 if (unlikely(!put_tree_ref(context, chunk))) {
1607                                         drop = chunk;
1608                                         break;
1609                                 }
1610                         }
1611                 }
1612                 parent = d->d_parent;
1613                 if (parent == d)
1614                         break;
1615                 d = parent;
1616         }
1617         if (unlikely(read_seqretry(&rename_lock, seq) || drop)) {  /* in this order */
1618                 rcu_read_unlock();
1619                 if (!drop) {
1620                         /* just a race with rename */
1621                         unroll_tree_refs(context, p, count);
1622                         goto retry;
1623                 }
1624                 audit_put_chunk(drop);
1625                 if (grow_tree_refs(context)) {
1626                         /* OK, got more space */
1627                         unroll_tree_refs(context, p, count);
1628                         goto retry;
1629                 }
1630                 /* too bad */
1631                 printk(KERN_WARNING
1632                         "out of memory, audit has lost a tree reference\n");
1633                 unroll_tree_refs(context, p, count);
1634                 audit_set_auditable(context);
1635                 return;
1636         }
1637         rcu_read_unlock();
1638 #endif
1639 }
1640
1641 static struct audit_names *audit_alloc_name(struct audit_context *context,
1642                                                 unsigned char type)
1643 {
1644         struct audit_names *aname;
1645
1646         if (context->name_count < AUDIT_NAMES) {
1647                 aname = &context->preallocated_names[context->name_count];
1648                 memset(aname, 0, sizeof(*aname));
1649         } else {
1650                 aname = kzalloc(sizeof(*aname), GFP_NOFS);
1651                 if (!aname)
1652                         return NULL;
1653                 aname->should_free = true;
1654         }
1655
1656         aname->ino = (unsigned long)-1;
1657         aname->type = type;
1658         list_add_tail(&aname->list, &context->names_list);
1659
1660         context->name_count++;
1661 #if AUDIT_DEBUG
1662         context->ino_count++;
1663 #endif
1664         return aname;
1665 }
1666
1667 /**
1668  * audit_reusename - fill out filename with info from existing entry
1669  * @uptr: userland ptr to pathname
1670  *
1671  * Search the audit_names list for the current audit context. If there is an
1672  * existing entry with a matching "uptr" then return the filename
1673  * associated with that audit_name. If not, return NULL.
1674  */
1675 struct filename *
1676 __audit_reusename(const __user char *uptr)
1677 {
1678         struct audit_context *context = current->audit_context;
1679         struct audit_names *n;
1680
1681         list_for_each_entry(n, &context->names_list, list) {
1682                 if (!n->name)
1683                         continue;
1684                 if (n->name->uptr == uptr)
1685                         return n->name;
1686         }
1687         return NULL;
1688 }
1689
1690 /**
1691  * audit_getname - add a name to the list
1692  * @name: name to add
1693  *
1694  * Add a name to the list of audit names for this context.
1695  * Called from fs/namei.c:getname().
1696  */
1697 void __audit_getname(struct filename *name)
1698 {
1699         struct audit_context *context = current->audit_context;
1700         struct audit_names *n;
1701
1702         if (!context->in_syscall) {
1703 #if AUDIT_DEBUG == 2
1704                 printk(KERN_ERR "%s:%d(:%d): ignoring getname(%p)\n",
1705                        __FILE__, __LINE__, context->serial, name);
1706                 dump_stack();
1707 #endif
1708                 return;
1709         }
1710
1711 #if AUDIT_DEBUG
1712         /* The filename _must_ have a populated ->name */
1713         BUG_ON(!name->name);
1714 #endif
1715
1716         n = audit_alloc_name(context, AUDIT_TYPE_UNKNOWN);
1717         if (!n)
1718                 return;
1719
1720         n->name = name;
1721         n->name_len = AUDIT_NAME_FULL;
1722         n->name_put = true;
1723         name->aname = n;
1724
1725         if (!context->pwd.dentry)
1726                 get_fs_pwd(current->fs, &context->pwd);
1727 }
1728
1729 /* audit_putname - intercept a putname request
1730  * @name: name to intercept and delay for putname
1731  *
1732  * If we have stored the name from getname in the audit context,
1733  * then we delay the putname until syscall exit.
1734  * Called from include/linux/fs.h:putname().
1735  */
1736 void audit_putname(struct filename *name)
1737 {
1738         struct audit_context *context = current->audit_context;
1739
1740         BUG_ON(!context);
1741         if (!context->in_syscall) {
1742 #if AUDIT_DEBUG == 2
1743                 printk(KERN_ERR "%s:%d(:%d): final_putname(%p)\n",
1744                        __FILE__, __LINE__, context->serial, name);
1745                 if (context->name_count) {
1746                         struct audit_names *n;
1747                         int i = 0;
1748
1749                         list_for_each_entry(n, &context->names_list, list)
1750                                 printk(KERN_ERR "name[%d] = %p = %s\n", i++,
1751                                        n->name, n->name->name ?: "(null)");
1752                         }
1753 #endif
1754                 final_putname(name);
1755         }
1756 #if AUDIT_DEBUG
1757         else {
1758                 ++context->put_count;
1759                 if (context->put_count > context->name_count) {
1760                         printk(KERN_ERR "%s:%d(:%d): major=%d"
1761                                " in_syscall=%d putname(%p) name_count=%d"
1762                                " put_count=%d\n",
1763                                __FILE__, __LINE__,
1764                                context->serial, context->major,
1765                                context->in_syscall, name->name,
1766                                context->name_count, context->put_count);
1767                         dump_stack();
1768                 }
1769         }
1770 #endif
1771 }
1772
1773 /**
1774  * __audit_inode - store the inode and device from a lookup
1775  * @name: name being audited
1776  * @dentry: dentry being audited
1777  * @flags: attributes for this particular entry
1778  */
1779 void __audit_inode(struct filename *name, const struct dentry *dentry,
1780                    unsigned int flags)
1781 {
1782         struct audit_context *context = current->audit_context;
1783         const struct inode *inode = dentry->d_inode;
1784         struct audit_names *n;
1785         bool parent = flags & AUDIT_INODE_PARENT;
1786
1787         if (!context->in_syscall)
1788                 return;
1789
1790         if (!name)
1791                 goto out_alloc;
1792
1793 #if AUDIT_DEBUG
1794         /* The struct filename _must_ have a populated ->name */
1795         BUG_ON(!name->name);
1796 #endif
1797         /*
1798          * If we have a pointer to an audit_names entry already, then we can
1799          * just use it directly if the type is correct.
1800          */
1801         n = name->aname;
1802         if (n) {
1803                 if (parent) {
1804                         if (n->type == AUDIT_TYPE_PARENT ||
1805                             n->type == AUDIT_TYPE_UNKNOWN)
1806                                 goto out;
1807                 } else {
1808                         if (n->type != AUDIT_TYPE_PARENT)
1809                                 goto out;
1810                 }
1811         }
1812
1813         list_for_each_entry_reverse(n, &context->names_list, list) {
1814                 /* does the name pointer match? */
1815                 if (!n->name || n->name->name != name->name)
1816                         continue;
1817
1818                 /* match the correct record type */
1819                 if (parent) {
1820                         if (n->type == AUDIT_TYPE_PARENT ||
1821                             n->type == AUDIT_TYPE_UNKNOWN)
1822                                 goto out;
1823                 } else {
1824                         if (n->type != AUDIT_TYPE_PARENT)
1825                                 goto out;
1826                 }
1827         }
1828
1829 out_alloc:
1830         /* unable to find the name from a previous getname(). Allocate a new
1831          * anonymous entry.
1832          */
1833         n = audit_alloc_name(context, AUDIT_TYPE_NORMAL);
1834         if (!n)
1835                 return;
1836 out:
1837         if (parent) {
1838                 n->name_len = n->name ? parent_len(n->name->name) : AUDIT_NAME_FULL;
1839                 n->type = AUDIT_TYPE_PARENT;
1840                 if (flags & AUDIT_INODE_HIDDEN)
1841                         n->hidden = true;
1842         } else {
1843                 n->name_len = AUDIT_NAME_FULL;
1844                 n->type = AUDIT_TYPE_NORMAL;
1845         }
1846         handle_path(dentry);
1847         audit_copy_inode(n, dentry, inode);
1848 }
1849
1850 /**
1851  * __audit_inode_child - collect inode info for created/removed objects
1852  * @parent: inode of dentry parent
1853  * @dentry: dentry being audited
1854  * @type:   AUDIT_TYPE_* value that we're looking for
1855  *
1856  * For syscalls that create or remove filesystem objects, audit_inode
1857  * can only collect information for the filesystem object's parent.
1858  * This call updates the audit context with the child's information.
1859  * Syscalls that create a new filesystem object must be hooked after
1860  * the object is created.  Syscalls that remove a filesystem object
1861  * must be hooked prior, in order to capture the target inode during
1862  * unsuccessful attempts.
1863  */
1864 void __audit_inode_child(const struct inode *parent,
1865                          const struct dentry *dentry,
1866                          const unsigned char type)
1867 {
1868         struct audit_context *context = current->audit_context;
1869         const struct inode *inode = dentry->d_inode;
1870         const char *dname = dentry->d_name.name;
1871         struct audit_names *n, *found_parent = NULL, *found_child = NULL;
1872
1873         if (!context->in_syscall)
1874                 return;
1875
1876         if (inode)
1877                 handle_one(inode);
1878
1879         /* look for a parent entry first */
1880         list_for_each_entry(n, &context->names_list, list) {
1881                 if (!n->name || n->type != AUDIT_TYPE_PARENT)
1882                         continue;
1883
1884                 if (n->ino == parent->i_ino &&
1885                     !audit_compare_dname_path(dname, n->name->name, n->name_len)) {
1886                         found_parent = n;
1887                         break;
1888                 }
1889         }
1890
1891         /* is there a matching child entry? */
1892         list_for_each_entry(n, &context->names_list, list) {
1893                 /* can only match entries that have a name */
1894                 if (!n->name || n->type != type)
1895                         continue;
1896
1897                 /* if we found a parent, make sure this one is a child of it */
1898                 if (found_parent && (n->name != found_parent->name))
1899                         continue;
1900
1901                 if (!strcmp(dname, n->name->name) ||
1902                     !audit_compare_dname_path(dname, n->name->name,
1903                                                 found_parent ?
1904                                                 found_parent->name_len :
1905                                                 AUDIT_NAME_FULL)) {
1906                         found_child = n;
1907                         break;
1908                 }
1909         }
1910
1911         if (!found_parent) {
1912                 /* create a new, "anonymous" parent record */
1913                 n = audit_alloc_name(context, AUDIT_TYPE_PARENT);
1914                 if (!n)
1915                         return;
1916                 audit_copy_inode(n, NULL, parent);
1917         }
1918
1919         if (!found_child) {
1920                 found_child = audit_alloc_name(context, type);
1921                 if (!found_child)
1922                         return;
1923
1924                 /* Re-use the name belonging to the slot for a matching parent
1925                  * directory. All names for this context are relinquished in
1926                  * audit_free_names() */
1927                 if (found_parent) {
1928                         found_child->name = found_parent->name;
1929                         found_child->name_len = AUDIT_NAME_FULL;
1930                         /* don't call __putname() */
1931                         found_child->name_put = false;
1932                 }
1933         }
1934         if (inode)
1935                 audit_copy_inode(found_child, dentry, inode);
1936         else
1937                 found_child->ino = (unsigned long)-1;
1938 }
1939 EXPORT_SYMBOL_GPL(__audit_inode_child);
1940
1941 /**
1942  * auditsc_get_stamp - get local copies of audit_context values
1943  * @ctx: audit_context for the task
1944  * @t: timespec to store time recorded in the audit_context
1945  * @serial: serial value that is recorded in the audit_context
1946  *
1947  * Also sets the context as auditable.
1948  */
1949 int auditsc_get_stamp(struct audit_context *ctx,
1950                        struct timespec *t, unsigned int *serial)
1951 {
1952         if (!ctx->in_syscall)
1953                 return 0;
1954         if (!ctx->serial)
1955                 ctx->serial = audit_serial();
1956         t->tv_sec  = ctx->ctime.tv_sec;
1957         t->tv_nsec = ctx->ctime.tv_nsec;
1958         *serial    = ctx->serial;
1959         if (!ctx->prio) {
1960                 ctx->prio = 1;
1961                 ctx->current_state = AUDIT_RECORD_CONTEXT;
1962         }
1963         return 1;
1964 }
1965
1966 /* global counter which is incremented every time something logs in */
1967 static atomic_t session_id = ATOMIC_INIT(0);
1968
1969 static int audit_set_loginuid_perm(kuid_t loginuid)
1970 {
1971 #ifdef CONFIG_AUDIT_LOGINUID_IMMUTABLE
1972         /* if we are unset, we don't need privs */
1973         if (!audit_loginuid_set(current))
1974                 return 0;
1975 #else   /* CONFIG_AUDIT_LOGINUID_IMMUTABLE */
1976         if (capable(CAP_AUDIT_CONTROL))
1977                 return 0;
1978 #endif /* CONFIG_AUDIT_LOGINUID_IMMUTABLE */
1979         return -EPERM;
1980 }
1981
1982 static void audit_log_set_loginuid(kuid_t koldloginuid, kuid_t kloginuid,
1983                                    unsigned int oldsessionid, unsigned int sessionid,
1984                                    int rc)
1985 {
1986         struct audit_buffer *ab;
1987         uid_t uid, ologinuid, nloginuid;
1988
1989         uid = from_kuid(&init_user_ns, task_uid(current));
1990         ologinuid = from_kuid(&init_user_ns, koldloginuid);
1991         nloginuid = from_kuid(&init_user_ns, kloginuid),
1992
1993         ab = audit_log_start(NULL, GFP_KERNEL, AUDIT_LOGIN);
1994         if (!ab)
1995                 return;
1996         audit_log_format(ab, "pid=%d uid=%u old auid=%u new auid=%u old "
1997                          "ses=%u new ses=%u res=%d", current->pid, uid, ologinuid,
1998                          nloginuid, oldsessionid, sessionid, !rc);
1999         audit_log_end(ab);
2000 }
2001
2002 /**
2003  * audit_set_loginuid - set current task's audit_context loginuid
2004  * @loginuid: loginuid value
2005  *
2006  * Returns 0.
2007  *
2008  * Called (set) from fs/proc/base.c::proc_loginuid_write().
2009  */
2010 int audit_set_loginuid(kuid_t loginuid)
2011 {
2012         struct task_struct *task = current;
2013         unsigned int sessionid = -1;
2014         kuid_t oldloginuid, oldsessionid;
2015         int rc;
2016
2017         oldloginuid = audit_get_loginuid(current);
2018         oldsessionid = audit_get_sessionid(current);
2019
2020         rc = audit_set_loginuid_perm(loginuid);
2021         if (rc)
2022                 goto out;
2023
2024         sessionid = atomic_inc_return(&session_id);
2025
2026         task->sessionid = sessionid;
2027         task->loginuid = loginuid;
2028 out:
2029         audit_log_set_loginuid(oldloginuid, loginuid, oldsessionid, sessionid, rc);
2030         return rc;
2031 }
2032
2033 /**
2034  * __audit_mq_open - record audit data for a POSIX MQ open
2035  * @oflag: open flag
2036  * @mode: mode bits
2037  * @attr: queue attributes
2038  *
2039  */
2040 void __audit_mq_open(int oflag, umode_t mode, struct mq_attr *attr)
2041 {
2042         struct audit_context *context = current->audit_context;
2043
2044         if (attr)
2045                 memcpy(&context->mq_open.attr, attr, sizeof(struct mq_attr));
2046         else
2047                 memset(&context->mq_open.attr, 0, sizeof(struct mq_attr));
2048
2049         context->mq_open.oflag = oflag;
2050         context->mq_open.mode = mode;
2051
2052         context->type = AUDIT_MQ_OPEN;
2053 }
2054
2055 /**
2056  * __audit_mq_sendrecv - record audit data for a POSIX MQ timed send/receive
2057  * @mqdes: MQ descriptor
2058  * @msg_len: Message length
2059  * @msg_prio: Message priority
2060  * @abs_timeout: Message timeout in absolute time
2061  *
2062  */
2063 void __audit_mq_sendrecv(mqd_t mqdes, size_t msg_len, unsigned int msg_prio,
2064                         const struct timespec *abs_timeout)
2065 {
2066         struct audit_context *context = current->audit_context;
2067         struct timespec *p = &context->mq_sendrecv.abs_timeout;
2068
2069         if (abs_timeout)
2070                 memcpy(p, abs_timeout, sizeof(struct timespec));
2071         else
2072                 memset(p, 0, sizeof(struct timespec));
2073
2074         context->mq_sendrecv.mqdes = mqdes;
2075         context->mq_sendrecv.msg_len = msg_len;
2076         context->mq_sendrecv.msg_prio = msg_prio;
2077
2078         context->type = AUDIT_MQ_SENDRECV;
2079 }
2080
2081 /**
2082  * __audit_mq_notify - record audit data for a POSIX MQ notify
2083  * @mqdes: MQ descriptor
2084  * @notification: Notification event
2085  *
2086  */
2087
2088 void __audit_mq_notify(mqd_t mqdes, const struct sigevent *notification)
2089 {
2090         struct audit_context *context = current->audit_context;
2091
2092         if (notification)
2093                 context->mq_notify.sigev_signo = notification->sigev_signo;
2094         else
2095                 context->mq_notify.sigev_signo = 0;
2096
2097         context->mq_notify.mqdes = mqdes;
2098         context->type = AUDIT_MQ_NOTIFY;
2099 }
2100
2101 /**
2102  * __audit_mq_getsetattr - record audit data for a POSIX MQ get/set attribute
2103  * @mqdes: MQ descriptor
2104  * @mqstat: MQ flags
2105  *
2106  */
2107 void __audit_mq_getsetattr(mqd_t mqdes, struct mq_attr *mqstat)
2108 {
2109         struct audit_context *context = current->audit_context;
2110         context->mq_getsetattr.mqdes = mqdes;
2111         context->mq_getsetattr.mqstat = *mqstat;
2112         context->type = AUDIT_MQ_GETSETATTR;
2113 }
2114
2115 /**
2116  * audit_ipc_obj - record audit data for ipc object
2117  * @ipcp: ipc permissions
2118  *
2119  */
2120 void __audit_ipc_obj(struct kern_ipc_perm *ipcp)
2121 {
2122         struct audit_context *context = current->audit_context;
2123         context->ipc.uid = ipcp->uid;
2124         context->ipc.gid = ipcp->gid;
2125         context->ipc.mode = ipcp->mode;
2126         context->ipc.has_perm = 0;
2127         security_ipc_getsecid(ipcp, &context->ipc.osid);
2128         context->type = AUDIT_IPC;
2129 }
2130
2131 /**
2132  * audit_ipc_set_perm - record audit data for new ipc permissions
2133  * @qbytes: msgq bytes
2134  * @uid: msgq user id
2135  * @gid: msgq group id
2136  * @mode: msgq mode (permissions)
2137  *
2138  * Called only after audit_ipc_obj().
2139  */
2140 void __audit_ipc_set_perm(unsigned long qbytes, uid_t uid, gid_t gid, umode_t mode)
2141 {
2142         struct audit_context *context = current->audit_context;
2143
2144         context->ipc.qbytes = qbytes;
2145         context->ipc.perm_uid = uid;
2146         context->ipc.perm_gid = gid;
2147         context->ipc.perm_mode = mode;
2148         context->ipc.has_perm = 1;
2149 }
2150
2151 int __audit_bprm(struct linux_binprm *bprm)
2152 {
2153         struct audit_aux_data_execve *ax;
2154         struct audit_context *context = current->audit_context;
2155
2156         ax = kmalloc(sizeof(*ax), GFP_KERNEL);
2157         if (!ax)
2158                 return -ENOMEM;
2159
2160         ax->argc = bprm->argc;
2161         ax->envc = bprm->envc;
2162         ax->mm = bprm->mm;
2163         ax->d.type = AUDIT_EXECVE;
2164         ax->d.next = context->aux;
2165         context->aux = (void *)ax;
2166         return 0;
2167 }
2168
2169
2170 /**
2171  * audit_socketcall - record audit data for sys_socketcall
2172  * @nargs: number of args, which should not be more than AUDITSC_ARGS.
2173  * @args: args array
2174  *
2175  */
2176 int __audit_socketcall(int nargs, unsigned long *args)
2177 {
2178         struct audit_context *context = current->audit_context;
2179
2180         if (nargs <= 0 || nargs > AUDITSC_ARGS || !args)
2181                 return -EINVAL;
2182         context->type = AUDIT_SOCKETCALL;
2183         context->socketcall.nargs = nargs;
2184         memcpy(context->socketcall.args, args, nargs * sizeof(unsigned long));
2185         return 0;
2186 }
2187
2188 /**
2189  * __audit_fd_pair - record audit data for pipe and socketpair
2190  * @fd1: the first file descriptor
2191  * @fd2: the second file descriptor
2192  *
2193  */
2194 void __audit_fd_pair(int fd1, int fd2)
2195 {
2196         struct audit_context *context = current->audit_context;
2197         context->fds[0] = fd1;
2198         context->fds[1] = fd2;
2199 }
2200
2201 /**
2202  * audit_sockaddr - record audit data for sys_bind, sys_connect, sys_sendto
2203  * @len: data length in user space
2204  * @a: data address in kernel space
2205  *
2206  * Returns 0 for success or NULL context or < 0 on error.
2207  */
2208 int __audit_sockaddr(int len, void *a)
2209 {
2210         struct audit_context *context = current->audit_context;
2211
2212         if (!context->sockaddr) {
2213                 void *p = kmalloc(sizeof(struct sockaddr_storage), GFP_KERNEL);
2214                 if (!p)
2215                         return -ENOMEM;
2216                 context->sockaddr = p;
2217         }
2218
2219         context->sockaddr_len = len;
2220         memcpy(context->sockaddr, a, len);
2221         return 0;
2222 }
2223
2224 void __audit_ptrace(struct task_struct *t)
2225 {
2226         struct audit_context *context = current->audit_context;
2227
2228         context->target_pid = t->pid;
2229         context->target_auid = audit_get_loginuid(t);
2230         context->target_uid = task_uid(t);
2231         context->target_sessionid = audit_get_sessionid(t);
2232         security_task_getsecid(t, &context->target_sid);
2233         memcpy(context->target_comm, t->comm, TASK_COMM_LEN);
2234 }
2235
2236 /**
2237  * audit_signal_info - record signal info for shutting down audit subsystem
2238  * @sig: signal value
2239  * @t: task being signaled
2240  *
2241  * If the audit subsystem is being terminated, record the task (pid)
2242  * and uid that is doing that.
2243  */
2244 int __audit_signal_info(int sig, struct task_struct *t)
2245 {
2246         struct audit_aux_data_pids *axp;
2247         struct task_struct *tsk = current;
2248         struct audit_context *ctx = tsk->audit_context;
2249         kuid_t uid = current_uid(), t_uid = task_uid(t);
2250
2251         if (audit_pid && t->tgid == audit_pid) {
2252                 if (sig == SIGTERM || sig == SIGHUP || sig == SIGUSR1 || sig == SIGUSR2) {
2253                         audit_sig_pid = tsk->pid;
2254                         if (uid_valid(tsk->loginuid))
2255                                 audit_sig_uid = tsk->loginuid;
2256                         else
2257                                 audit_sig_uid = uid;
2258                         security_task_getsecid(tsk, &audit_sig_sid);
2259                 }
2260                 if (!audit_signals || audit_dummy_context())
2261                         return 0;
2262         }
2263
2264         /* optimize the common case by putting first signal recipient directly
2265          * in audit_context */
2266         if (!ctx->target_pid) {
2267                 ctx->target_pid = t->tgid;
2268                 ctx->target_auid = audit_get_loginuid(t);
2269                 ctx->target_uid = t_uid;
2270                 ctx->target_sessionid = audit_get_sessionid(t);
2271                 security_task_getsecid(t, &ctx->target_sid);
2272                 memcpy(ctx->target_comm, t->comm, TASK_COMM_LEN);
2273                 return 0;
2274         }
2275
2276         axp = (void *)ctx->aux_pids;
2277         if (!axp || axp->pid_count == AUDIT_AUX_PIDS) {
2278                 axp = kzalloc(sizeof(*axp), GFP_ATOMIC);
2279                 if (!axp)
2280                         return -ENOMEM;
2281
2282                 axp->d.type = AUDIT_OBJ_PID;
2283                 axp->d.next = ctx->aux_pids;
2284                 ctx->aux_pids = (void *)axp;
2285         }
2286         BUG_ON(axp->pid_count >= AUDIT_AUX_PIDS);
2287
2288         axp->target_pid[axp->pid_count] = t->tgid;
2289         axp->target_auid[axp->pid_count] = audit_get_loginuid(t);
2290         axp->target_uid[axp->pid_count] = t_uid;
2291         axp->target_sessionid[axp->pid_count] = audit_get_sessionid(t);
2292         security_task_getsecid(t, &axp->target_sid[axp->pid_count]);
2293         memcpy(axp->target_comm[axp->pid_count], t->comm, TASK_COMM_LEN);
2294         axp->pid_count++;
2295
2296         return 0;
2297 }
2298
2299 /**
2300  * __audit_log_bprm_fcaps - store information about a loading bprm and relevant fcaps
2301  * @bprm: pointer to the bprm being processed
2302  * @new: the proposed new credentials
2303  * @old: the old credentials
2304  *
2305  * Simply check if the proc already has the caps given by the file and if not
2306  * store the priv escalation info for later auditing at the end of the syscall
2307  *
2308  * -Eric
2309  */
2310 int __audit_log_bprm_fcaps(struct linux_binprm *bprm,
2311                            const struct cred *new, const struct cred *old)
2312 {
2313         struct audit_aux_data_bprm_fcaps *ax;
2314         struct audit_context *context = current->audit_context;
2315         struct cpu_vfs_cap_data vcaps;
2316         struct dentry *dentry;
2317
2318         ax = kmalloc(sizeof(*ax), GFP_KERNEL);
2319         if (!ax)
2320                 return -ENOMEM;
2321
2322         ax->d.type = AUDIT_BPRM_FCAPS;
2323         ax->d.next = context->aux;
2324         context->aux = (void *)ax;
2325
2326         dentry = dget(bprm->file->f_dentry);
2327         get_vfs_caps_from_disk(dentry, &vcaps);
2328         dput(dentry);
2329
2330         ax->fcap.permitted = vcaps.permitted;
2331         ax->fcap.inheritable = vcaps.inheritable;
2332         ax->fcap.fE = !!(vcaps.magic_etc & VFS_CAP_FLAGS_EFFECTIVE);
2333         ax->fcap_ver = (vcaps.magic_etc & VFS_CAP_REVISION_MASK) >> VFS_CAP_REVISION_SHIFT;
2334
2335         ax->old_pcap.permitted   = old->cap_permitted;
2336         ax->old_pcap.inheritable = old->cap_inheritable;
2337         ax->old_pcap.effective   = old->cap_effective;
2338
2339         ax->new_pcap.permitted   = new->cap_permitted;
2340         ax->new_pcap.inheritable = new->cap_inheritable;
2341         ax->new_pcap.effective   = new->cap_effective;
2342         return 0;
2343 }
2344
2345 /**
2346  * __audit_log_capset - store information about the arguments to the capset syscall
2347  * @pid: target pid of the capset call
2348  * @new: the new credentials
2349  * @old: the old (current) credentials
2350  *
2351  * Record the aguments userspace sent to sys_capset for later printing by the
2352  * audit system if applicable
2353  */
2354 void __audit_log_capset(pid_t pid,
2355                        const struct cred *new, const struct cred *old)
2356 {
2357         struct audit_context *context = current->audit_context;
2358         context->capset.pid = pid;
2359         context->capset.cap.effective   = new->cap_effective;
2360         context->capset.cap.inheritable = new->cap_effective;
2361         context->capset.cap.permitted   = new->cap_permitted;
2362         context->type = AUDIT_CAPSET;
2363 }
2364
2365 void __audit_mmap_fd(int fd, int flags)
2366 {
2367         struct audit_context *context = current->audit_context;
2368         context->mmap.fd = fd;
2369         context->mmap.flags = flags;
2370         context->type = AUDIT_MMAP;
2371 }
2372
2373 static void audit_log_task(struct audit_buffer *ab)
2374 {
2375         kuid_t auid, uid;
2376         kgid_t gid;
2377         unsigned int sessionid;
2378
2379         auid = audit_get_loginuid(current);
2380         sessionid = audit_get_sessionid(current);
2381         current_uid_gid(&uid, &gid);
2382
2383         audit_log_format(ab, "auid=%u uid=%u gid=%u ses=%u",
2384                          from_kuid(&init_user_ns, auid),
2385                          from_kuid(&init_user_ns, uid),
2386                          from_kgid(&init_user_ns, gid),
2387                          sessionid);
2388         audit_log_task_context(ab);
2389         audit_log_format(ab, " pid=%d comm=", current->pid);
2390         audit_log_untrustedstring(ab, current->comm);
2391 }
2392
2393 static void audit_log_abend(struct audit_buffer *ab, char *reason, long signr)
2394 {
2395         audit_log_task(ab);
2396         audit_log_format(ab, " reason=");
2397         audit_log_string(ab, reason);
2398         audit_log_format(ab, " sig=%ld", signr);
2399 }
2400 /**
2401  * audit_core_dumps - record information about processes that end abnormally
2402  * @signr: signal value
2403  *
2404  * If a process ends with a core dump, something fishy is going on and we
2405  * should record the event for investigation.
2406  */
2407 void audit_core_dumps(long signr)
2408 {
2409         struct audit_buffer *ab;
2410
2411         if (!audit_enabled)
2412                 return;
2413
2414         if (signr == SIGQUIT)   /* don't care for those */
2415                 return;
2416
2417         ab = audit_log_start(NULL, GFP_KERNEL, AUDIT_ANOM_ABEND);
2418         if (unlikely(!ab))
2419                 return;
2420         audit_log_abend(ab, "memory violation", signr);
2421         audit_log_end(ab);
2422 }
2423
2424 void __audit_seccomp(unsigned long syscall, long signr, int code)
2425 {
2426         struct audit_buffer *ab;
2427
2428         ab = audit_log_start(NULL, GFP_KERNEL, AUDIT_SECCOMP);
2429         if (unlikely(!ab))
2430                 return;
2431         audit_log_task(ab);
2432         audit_log_format(ab, " sig=%ld", signr);
2433         audit_log_format(ab, " syscall=%ld", syscall);
2434         audit_log_format(ab, " compat=%d", is_compat_task());
2435         audit_log_format(ab, " ip=0x%lx", KSTK_EIP(current));
2436         audit_log_format(ab, " code=0x%x", code);
2437         audit_log_end(ab);
2438 }
2439
2440 struct list_head *audit_killed_trees(void)
2441 {
2442         struct audit_context *ctx = current->audit_context;
2443         if (likely(!ctx || !ctx->in_syscall))
2444                 return NULL;
2445         return &ctx->killed_trees;
2446 }