1 /*-
2 * SPDX-License-Identifier: BSD-2-Clause
3 *
4 * Copyright (c) 1993, David Greenman
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * SUCH DAMAGE.
27 */
28
29 #include "opt_capsicum.h"
30 #include "opt_hwpmc_hooks.h"
31 #include "opt_hwt_hooks.h"
32 #include "opt_ktrace.h"
33 #include "opt_vm.h"
34
35 #include <sys/systm.h>
36 #include <sys/acct.h>
37 #include <sys/asan.h>
38 #include <sys/capsicum.h>
39 #include <sys/compressor.h>
40 #include <sys/dirent.h>
41 #include <sys/eventhandler.h>
42 #include <sys/exec.h>
43 #include <sys/fcntl.h>
44 #include <sys/filedesc.h>
45 #include <sys/imgact.h>
46 #include <sys/imgact_elf.h>
47 #include <sys/kernel.h>
48 #include <sys/limits.h>
49 #include <sys/lock.h>
50 #include <sys/malloc.h>
51 #include <sys/mman.h>
52 #include <sys/mount.h>
53 #include <sys/mutex.h>
54 #include <sys/namei.h>
55 #include <sys/priv.h>
56 #include <sys/proc.h>
57 #include <sys/ptrace.h>
58 #include <sys/reg.h>
59 #include <sys/resourcevar.h>
60 #include <sys/rwlock.h>
61 #include <sys/sched.h>
62 #include <sys/sdt.h>
63 #include <sys/sf_buf.h>
64 #include <sys/shm.h>
65 #include <sys/signalvar.h>
66 #include <sys/smp.h>
67 #include <sys/stat.h>
68 #include <sys/syscallsubr.h>
69 #include <sys/sysctl.h>
70 #include <sys/sysent.h>
71 #include <sys/sysproto.h>
72 #include <sys/timers.h>
73 #include <sys/ucoredump.h>
74 #include <sys/umtxvar.h>
75 #include <sys/vnode.h>
76 #include <sys/wait.h>
77 #ifdef KTRACE
78 #include <sys/ktrace.h>
79 #endif
80
81 #include <vm/vm.h>
82 #include <vm/vm_param.h>
83 #include <vm/pmap.h>
84 #include <vm/vm_page.h>
85 #include <vm/vm_map.h>
86 #include <vm/vm_kern.h>
87 #include <vm/vm_extern.h>
88 #include <vm/vm_object.h>
89 #include <vm/vm_pager.h>
90
91 #ifdef HWPMC_HOOKS
92 #include <sys/pmckern.h>
93 #endif
94
95 #ifdef HWT_HOOKS
96 #include <dev/hwt/hwt_hook.h>
97 #endif
98
99 #include <security/audit/audit.h>
100 #include <security/mac/mac_framework.h>
101
102 #ifdef KDTRACE_HOOKS
103 #include <sys/dtrace_bsd.h>
104 dtrace_execexit_func_t dtrace_fasttrap_exec;
105 #endif
106
107 SDT_PROVIDER_DECLARE(proc);
108 SDT_PROBE_DEFINE1(proc, , , exec, "char *");
109 SDT_PROBE_DEFINE1(proc, , , exec__failure, "int");
110 SDT_PROBE_DEFINE1(proc, , , exec__success, "char *");
111
112 MALLOC_DEFINE(M_PARGS, "proc-args", "Process arguments");
113
114 int coredump_pack_fileinfo = 1;
115 SYSCTL_INT(_kern, OID_AUTO, coredump_pack_fileinfo, CTLFLAG_RWTUN,
116 &coredump_pack_fileinfo, 0,
117 "Enable file path packing in 'procstat -f' coredump notes");
118
119 int coredump_pack_vmmapinfo = 1;
120 SYSCTL_INT(_kern, OID_AUTO, coredump_pack_vmmapinfo, CTLFLAG_RWTUN,
121 &coredump_pack_vmmapinfo, 0,
122 "Enable file path packing in 'procstat -v' coredump notes");
123
124 static int sysctl_kern_ps_strings(SYSCTL_HANDLER_ARGS);
125 static int sysctl_kern_usrstack(SYSCTL_HANDLER_ARGS);
126 static int sysctl_kern_stackprot(SYSCTL_HANDLER_ARGS);
127 static int do_execve(struct thread *td, struct image_args *args,
128 struct mac *mac_p, struct vmspace *oldvmspace);
129
130 /* XXX This should be vm_size_t. */
131 SYSCTL_PROC(_kern, KERN_PS_STRINGS, ps_strings, CTLTYPE_ULONG|CTLFLAG_RD|
132 CTLFLAG_CAPRD|CTLFLAG_MPSAFE, NULL, 0, sysctl_kern_ps_strings, "LU",
133 "Location of process' ps_strings structure");
134
135 /* XXX This should be vm_size_t. */
136 SYSCTL_PROC(_kern, KERN_USRSTACK, usrstack, CTLTYPE_ULONG|CTLFLAG_RD|
137 CTLFLAG_CAPRD|CTLFLAG_MPSAFE, NULL, 0, sysctl_kern_usrstack, "LU",
138 "Top of process stack");
139
140 SYSCTL_PROC(_kern, OID_AUTO, stackprot, CTLTYPE_INT|CTLFLAG_RD|CTLFLAG_MPSAFE,
141 NULL, 0, sysctl_kern_stackprot, "I",
142 "Stack memory permissions");
143
144 u_long ps_arg_cache_limit = PAGE_SIZE / 16;
145 SYSCTL_ULONG(_kern, OID_AUTO, ps_arg_cache_limit, CTLFLAG_RW,
146 &ps_arg_cache_limit, 0,
147 "Process' command line characters cache limit");
148
149 static int disallow_high_osrel;
150 SYSCTL_INT(_kern, OID_AUTO, disallow_high_osrel, CTLFLAG_RW,
151 &disallow_high_osrel, 0,
152 "Disallow execution of binaries built for higher version of the world");
153
154 static int map_at_zero = 0;
155 SYSCTL_INT(_security_bsd, OID_AUTO, map_at_zero, CTLFLAG_RWTUN, &map_at_zero, 0,
156 "Permit processes to map an object at virtual address 0.");
157
158 static int core_dump_can_intr = 1;
159 SYSCTL_INT(_kern, OID_AUTO, core_dump_can_intr, CTLFLAG_RWTUN,
160 &core_dump_can_intr, 0,
161 "Core dumping interruptible with SIGKILL");
162
163 static int
sysctl_kern_ps_strings(SYSCTL_HANDLER_ARGS)164 sysctl_kern_ps_strings(SYSCTL_HANDLER_ARGS)
165 {
166 struct proc *p;
167 vm_offset_t ps_strings;
168
169 p = curproc;
170 #ifdef SCTL_MASK32
171 if (req->flags & SCTL_MASK32) {
172 unsigned int val;
173 val = (unsigned int)PROC_PS_STRINGS(p);
174 return (SYSCTL_OUT(req, &val, sizeof(val)));
175 }
176 #endif
177 ps_strings = PROC_PS_STRINGS(p);
178 return (SYSCTL_OUT(req, &ps_strings, sizeof(ps_strings)));
179 }
180
181 static int
sysctl_kern_usrstack(SYSCTL_HANDLER_ARGS)182 sysctl_kern_usrstack(SYSCTL_HANDLER_ARGS)
183 {
184 struct proc *p;
185 vm_offset_t val;
186
187 p = curproc;
188 #ifdef SCTL_MASK32
189 if (req->flags & SCTL_MASK32) {
190 unsigned int val32;
191
192 val32 = round_page((unsigned int)p->p_vmspace->vm_stacktop);
193 return (SYSCTL_OUT(req, &val32, sizeof(val32)));
194 }
195 #endif
196 val = round_page(p->p_vmspace->vm_stacktop);
197 return (SYSCTL_OUT(req, &val, sizeof(val)));
198 }
199
200 static int
sysctl_kern_stackprot(SYSCTL_HANDLER_ARGS)201 sysctl_kern_stackprot(SYSCTL_HANDLER_ARGS)
202 {
203 struct proc *p;
204
205 p = curproc;
206 return (SYSCTL_OUT(req, &p->p_sysent->sv_stackprot,
207 sizeof(p->p_sysent->sv_stackprot)));
208 }
209
210 /*
211 * Each of the items is a pointer to a `const struct execsw', hence the
212 * double pointer here.
213 */
214 static const struct execsw **execsw;
215
216 #ifndef _SYS_SYSPROTO_H_
217 struct execve_args {
218 char *fname;
219 char **argv;
220 char **envv;
221 };
222 #endif
223
224 int
sys_execve(struct thread * td,struct execve_args * uap)225 sys_execve(struct thread *td, struct execve_args *uap)
226 {
227 struct image_args args;
228 struct vmspace *oldvmspace;
229 int error;
230
231 error = pre_execve(td, &oldvmspace);
232 if (error != 0)
233 return (error);
234 error = exec_copyin_args(&args, uap->fname, uap->argv, uap->envv);
235 if (error == 0)
236 error = kern_execve(td, &args, NULL, oldvmspace);
237 post_execve(td, error, oldvmspace);
238 AUDIT_SYSCALL_EXIT(error == EJUSTRETURN ? 0 : error, td);
239 return (error);
240 }
241
242 #ifndef _SYS_SYSPROTO_H_
243 struct fexecve_args {
244 int fd;
245 char **argv;
246 char **envv;
247 };
248 #endif
249 int
sys_fexecve(struct thread * td,struct fexecve_args * uap)250 sys_fexecve(struct thread *td, struct fexecve_args *uap)
251 {
252 struct image_args args;
253 struct vmspace *oldvmspace;
254 int error;
255
256 error = pre_execve(td, &oldvmspace);
257 if (error != 0)
258 return (error);
259 error = exec_copyin_args(&args, NULL, uap->argv, uap->envv);
260 if (error == 0) {
261 args.fd = uap->fd;
262 error = kern_execve(td, &args, NULL, oldvmspace);
263 }
264 post_execve(td, error, oldvmspace);
265 AUDIT_SYSCALL_EXIT(error == EJUSTRETURN ? 0 : error, td);
266 return (error);
267 }
268
269 #ifndef _SYS_SYSPROTO_H_
270 struct __mac_execve_args {
271 char *fname;
272 char **argv;
273 char **envv;
274 struct mac *mac_p;
275 };
276 #endif
277
278 int
sys___mac_execve(struct thread * td,struct __mac_execve_args * uap)279 sys___mac_execve(struct thread *td, struct __mac_execve_args *uap)
280 {
281 #ifdef MAC
282 struct image_args args;
283 struct vmspace *oldvmspace;
284 int error;
285
286 error = pre_execve(td, &oldvmspace);
287 if (error != 0)
288 return (error);
289 error = exec_copyin_args(&args, uap->fname, uap->argv, uap->envv);
290 if (error == 0)
291 error = kern_execve(td, &args, uap->mac_p, oldvmspace);
292 post_execve(td, error, oldvmspace);
293 AUDIT_SYSCALL_EXIT(error == EJUSTRETURN ? 0 : error, td);
294 return (error);
295 #else
296 return (ENOSYS);
297 #endif
298 }
299
300 int
pre_execve(struct thread * td,struct vmspace ** oldvmspace)301 pre_execve(struct thread *td, struct vmspace **oldvmspace)
302 {
303 struct proc *p;
304 int error;
305
306 KASSERT(td == curthread, ("non-current thread %p", td));
307 error = 0;
308 p = td->td_proc;
309 if ((p->p_flag & P_HADTHREADS) != 0) {
310 PROC_LOCK(p);
311 if (thread_single(p, SINGLE_BOUNDARY) != 0)
312 error = ERESTART;
313 PROC_UNLOCK(p);
314 }
315 KASSERT(error != 0 || (td->td_pflags & TDP_EXECVMSPC) == 0,
316 ("nested execve"));
317 *oldvmspace = p->p_vmspace;
318 return (error);
319 }
320
321 void
post_execve(struct thread * td,int error,struct vmspace * oldvmspace)322 post_execve(struct thread *td, int error, struct vmspace *oldvmspace)
323 {
324 struct proc *p;
325
326 KASSERT(td == curthread, ("non-current thread %p", td));
327 p = td->td_proc;
328 if ((p->p_flag & P_HADTHREADS) != 0) {
329 PROC_LOCK(p);
330 /*
331 * If success, we upgrade to SINGLE_EXIT state to
332 * force other threads to suicide.
333 */
334 if (error == EJUSTRETURN)
335 thread_single(p, SINGLE_EXIT);
336 else
337 thread_single_end(p, SINGLE_BOUNDARY);
338 PROC_UNLOCK(p);
339 }
340 exec_cleanup(td, oldvmspace);
341 }
342
343 /*
344 * kern_execve() has the astonishing property of not always returning
345 * to the caller. If sufficiently bad things happen during the call
346 * to do_execve(), it can end up calling exit2(). Callers must avoid
347 * doing anything which they might need to undo (e.g., allocating
348 * memory), unless called from the ptrace(PT_SC_REMOTERQ) handler.
349 */
350 int
kern_execve(struct thread * td,struct image_args * args,struct mac * mac_p,struct vmspace * oldvmspace)351 kern_execve(struct thread *td, struct image_args *args, struct mac *mac_p,
352 struct vmspace *oldvmspace)
353 {
354
355 TSEXEC(td->td_proc->p_pid, args->begin_argv);
356 AUDIT_ARG_ARGV(args->begin_argv, args->argc,
357 exec_args_get_begin_envv(args) - args->begin_argv);
358 AUDIT_ARG_ENVV(exec_args_get_begin_envv(args), args->envc,
359 args->endp - exec_args_get_begin_envv(args));
360 #ifdef KTRACE
361 if (KTRPOINT(td, KTR_ARGS)) {
362 ktrdata(KTR_ARGS, args->begin_argv,
363 exec_args_get_begin_envv(args) - args->begin_argv);
364 }
365 if (KTRPOINT(td, KTR_ENVS)) {
366 ktrdata(KTR_ENVS, exec_args_get_begin_envv(args),
367 args->endp - exec_args_get_begin_envv(args));
368 }
369 #endif
370 /* Must have at least one argument. */
371 if (args->argc == 0) {
372 exec_free_args(args);
373 return (EINVAL);
374 }
375 return (do_execve(td, args, mac_p, oldvmspace));
376 }
377
378 static void
execve_nosetid(struct image_params * imgp)379 execve_nosetid(struct image_params *imgp)
380 {
381 imgp->credential_setid = false;
382 if (imgp->newcred != NULL) {
383 crfree(imgp->newcred);
384 imgp->newcred = NULL;
385 }
386 }
387
388 /*
389 * Returns true if the execblock was obtained, in this case the
390 * process lock is kept. Returns false if the execblock was not
391 * obtained, but the function slept and the lock was dropped.
392 */
393 bool
execve_block(struct thread * td,struct proc * p)394 execve_block(struct thread *td, struct proc *p)
395 {
396 PROC_LOCK_ASSERT(p, MA_OWNED);
397 MPASS(td == curthread);
398 MPASS(p != td->td_proc || (p->p_flag & P_INEXEC) == 0);
399
400 if (p != td->td_proc && (p->p_flag & P_INEXEC) != 0) {
401 p->p_flag |= P_INEXEC_WAIT;
402 msleep(&p->p_execblock, &p->p_mtx, PDROP, "inexec", 0);
403 return (false);
404 }
405 MPASS(p->p_execblock < UINT_MAX);
406 p->p_execblock++;
407 return (true);
408 }
409
410 /*
411 * Might drop the process lock internally, callers must re-check the
412 * invariants afterward.
413 */
414 void
execve_block_wait(struct thread * td,struct proc * p)415 execve_block_wait(struct thread *td, struct proc *p)
416 {
417 PROC_ASSERT_HELD(p);
418 PROC_LOCK_ASSERT(p, MA_OWNED);
419
420 while (!execve_block(td, p))
421 PROC_LOCK(p);
422 }
423
424 void
execve_unblock(struct thread * td,struct proc * p)425 execve_unblock(struct thread *td, struct proc *p)
426 {
427 PROC_LOCK_ASSERT(p, MA_OWNED);
428 MPASS(td == curthread);
429
430 MPASS(p->p_execblock > 0);
431 p->p_execblock--;
432 if (p->p_execblock == 0 && (p->p_flag & P_INEXEC_WAIT) != 0) {
433 p->p_flag &= ~P_INEXEC_WAIT;
434 wakeup(&p->p_execblock);
435 }
436 }
437
438 void
execve_block_pass(struct thread * td)439 execve_block_pass(struct thread *td)
440 {
441 struct proc *p;
442
443 MPASS(td == curthread);
444 p = td->td_proc;
445 PROC_LOCK_ASSERT(p, MA_OWNED);
446
447 while (p->p_execblock != 0) {
448 p->p_flag |= P_INEXEC_WAIT;
449 msleep(&p->p_execblock, &p->p_mtx, 0, "exeblk", 0);
450 }
451 }
452
453 /*
454 * In-kernel implementation of execve(). All arguments are assumed to be
455 * userspace pointers from the passed thread.
456 */
457 static int
do_execve(struct thread * td,struct image_args * args,struct mac * mac_p,struct vmspace * oldvmspace)458 do_execve(struct thread *td, struct image_args *args, struct mac *mac_p,
459 struct vmspace *oldvmspace)
460 {
461 struct proc *p = td->td_proc;
462 struct nameidata nd;
463 struct ucred *oldcred;
464 struct uidinfo *euip = NULL;
465 uintptr_t stack_base;
466 struct image_params image_params, *imgp;
467 struct vattr attr;
468 struct pargs *oldargs = NULL, *newargs = NULL;
469 struct sigacts *oldsigacts = NULL, *newsigacts = NULL;
470 #ifdef KTRACE
471 struct ktr_io_params *kiop;
472 #endif
473 struct vnode *oldtextvp, *newtextvp;
474 struct vnode *oldtextdvp, *newtextdvp;
475 char *oldbinname, *newbinname;
476 bool credential_changing;
477 #ifdef MAC
478 struct label *interpvplabel = NULL;
479 bool will_transition;
480 #endif
481 #ifdef HWPMC_HOOKS
482 struct pmckern_procexec pe;
483 #endif
484 int error, i, orig_osrel;
485 uint32_t orig_fctl0;
486 const Elf_Brandinfo *orig_brandinfo;
487 size_t freepath_size;
488 static const char fexecv_proc_title[] = "(fexecv)";
489
490 imgp = &image_params;
491 oldtextvp = oldtextdvp = NULL;
492 newtextvp = newtextdvp = NULL;
493 newbinname = oldbinname = NULL;
494 #ifdef KTRACE
495 kiop = NULL;
496 #endif
497
498 /*
499 * Lock the process and set the P_INEXEC flag to indicate that
500 * it should be left alone until we're done here. This is
501 * necessary to avoid race conditions - e.g. in ptrace() -
502 * that might allow a local user to illicitly obtain elevated
503 * privileges.
504 */
505 PROC_LOCK(p);
506 KASSERT((p->p_flag & P_INEXEC) == 0,
507 ("%s(): process already has P_INEXEC flag", __func__));
508 execve_block_pass(td);
509 p->p_flag |= P_INEXEC;
510 PROC_UNLOCK(p);
511
512 /*
513 * Initialize part of the common data
514 */
515 bzero(imgp, sizeof(*imgp));
516 imgp->proc = p;
517 imgp->td = td;
518 imgp->attr = &attr;
519 imgp->args = args;
520 oldcred = p->p_ucred;
521 orig_osrel = p->p_osrel;
522 orig_fctl0 = p->p_fctl0;
523 orig_brandinfo = p->p_elf_brandinfo;
524
525 #ifdef MAC
526 error = mac_execve_enter(imgp, mac_p);
527 if (error)
528 goto exec_fail;
529 #endif
530
531 SDT_PROBE1(proc, , , exec, args->fname);
532
533 interpret:
534 if (args->fname != NULL) {
535 #ifdef CAPABILITY_MODE
536 if (CAP_TRACING(td))
537 ktrcapfail(CAPFAIL_NAMEI, args->fname);
538 /*
539 * While capability mode can't reach this point via direct
540 * path arguments to execve(), we also don't allow
541 * interpreters to be used in capability mode (for now).
542 * Catch indirect lookups and return a permissions error.
543 */
544 if (IN_CAPABILITY_MODE(td)) {
545 error = ECAPMODE;
546 goto exec_fail;
547 }
548 #endif
549
550 /*
551 * Translate the file name. namei() returns a vnode
552 * pointer in ni_vp among other things.
553 */
554 NDINIT(&nd, LOOKUP, ISOPEN | LOCKLEAF | LOCKSHARED | FOLLOW |
555 AUDITVNODE1 | WANTPARENT, UIO_SYSSPACE,
556 args->fname);
557
558 error = namei(&nd);
559 if (error)
560 goto exec_fail;
561
562 newtextvp = nd.ni_vp;
563 newtextdvp = nd.ni_dvp;
564 nd.ni_dvp = NULL;
565 newbinname = malloc(nd.ni_cnd.cn_namelen + 1, M_PARGS,
566 M_WAITOK);
567 memcpy(newbinname, nd.ni_cnd.cn_nameptr, nd.ni_cnd.cn_namelen);
568 newbinname[nd.ni_cnd.cn_namelen] = '\0';
569 imgp->vp = newtextvp;
570
571 if (atomic_load_8(&newtextdvp->v_type) != VDIR) {
572 struct vnode *dvp1;
573 char *buf1;
574 size_t buf1len;
575
576 /*
577 * The newtextdvp vnode might be not a
578 * directory when reclaimed or when the image
579 * is mounted over a regular file. In the
580 * latter case, try to resolve the containing
581 * directory.
582 *
583 * In any case, p_textdvp must be either a
584 * directory or reclaimed.
585 */
586 VOP_UNLOCK(imgp->vp);
587 dvp1 = newtextdvp;
588 buf1len = MAXNAMLEN + 1;
589 buf1 = malloc(buf1len, M_TEMP, M_WAITOK);
590 error = vn_vptocnp(&dvp1, buf1, &buf1len);
591 if (error == 0) {
592 if (atomic_load_8(&dvp1->v_type) == VDIR) {
593 newtextdvp = dvp1;
594 } else {
595 vrele(dvp1);
596 newtextdvp = NULL;
597 }
598 } else {
599 newtextdvp = NULL;
600 }
601 free(buf1, M_TEMP);
602 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
603 }
604
605 /*
606 * Do the best to calculate the full path to the image file.
607 */
608 if (args->fname[0] == '/') {
609 imgp->execpath = args->fname;
610 } else if (newtextdvp != NULL) {
611 VOP_UNLOCK(imgp->vp);
612 freepath_size = MAXPATHLEN;
613 if (vn_fullpath_hardlink(newtextvp, newtextdvp,
614 newbinname, nd.ni_cnd.cn_namelen, &imgp->execpath,
615 &imgp->freepath, &freepath_size) != 0)
616 imgp->execpath = args->fname;
617 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
618 }
619 } else if (imgp->interpreter_vp) {
620 /*
621 * An image activator has already provided an open vnode
622 */
623 newtextvp = imgp->interpreter_vp;
624 imgp->interpreter_vp = NULL;
625 if (vn_fullpath(newtextvp, &imgp->execpath,
626 &imgp->freepath) != 0)
627 imgp->execpath = args->fname;
628 vn_lock(newtextvp, LK_SHARED | LK_RETRY);
629 AUDIT_ARG_VNODE1(newtextvp);
630 imgp->vp = newtextvp;
631 } else {
632 AUDIT_ARG_FD(args->fd);
633
634 /*
635 * If the descriptors was not opened with O_PATH, then
636 * we require that it was opened with O_EXEC or
637 * O_RDONLY. In either case, exec_check_permissions()
638 * below checks _current_ file access mode regardless
639 * of the permissions additionally checked at the
640 * open(2).
641 */
642 error = fgetvp_exec(td, args->fd, &cap_fexecve_rights,
643 &newtextvp);
644 if (error != 0)
645 goto exec_fail;
646
647 if (vn_fullpath(newtextvp, &imgp->execpath,
648 &imgp->freepath) != 0)
649 imgp->execpath = args->fname;
650 vn_lock(newtextvp, LK_SHARED | LK_RETRY);
651 AUDIT_ARG_VNODE1(newtextvp);
652 imgp->vp = newtextvp;
653 }
654
655 /*
656 * Check file permissions. Also 'opens' file and sets its vnode to
657 * text mode.
658 */
659 error = exec_check_permissions(imgp);
660 if (error)
661 goto exec_fail_dealloc;
662
663 imgp->object = imgp->vp->v_object;
664 if (imgp->object != NULL)
665 vm_object_reference(imgp->object);
666
667 error = exec_map_first_page(imgp);
668 if (error)
669 goto exec_fail_dealloc;
670
671 imgp->proc->p_osrel = 0;
672 imgp->proc->p_fctl0 = 0;
673 imgp->proc->p_elf_brandinfo = NULL;
674
675 /*
676 * Implement image setuid/setgid.
677 *
678 * Determine new credentials before attempting image activators
679 * so that it can be used by process_exec handlers to determine
680 * credential/setid changes.
681 *
682 * Don't honor setuid/setgid if the filesystem prohibits it or if
683 * the process is being traced.
684 *
685 * We disable setuid/setgid/etc in capability mode on the basis
686 * that most setugid applications are not written with that
687 * environment in mind, and will therefore almost certainly operate
688 * incorrectly. In principle there's no reason that setugid
689 * applications might not be useful in capability mode, so we may want
690 * to reconsider this conservative design choice in the future.
691 *
692 * XXXMAC: For the time being, use NOSUID to also prohibit
693 * transitions on the file system.
694 */
695 credential_changing = false;
696 credential_changing |= (attr.va_mode & S_ISUID) &&
697 oldcred->cr_uid != attr.va_uid;
698 credential_changing |= (attr.va_mode & S_ISGID) &&
699 oldcred->cr_gid != attr.va_gid;
700 #ifdef MAC
701 will_transition = mac_vnode_execve_will_transition(oldcred, imgp->vp,
702 interpvplabel, imgp) != 0;
703 credential_changing |= will_transition;
704 #endif
705
706 /* Don't inherit PROC_PDEATHSIG_CTL value if setuid/setgid. */
707 if (credential_changing)
708 imgp->proc->p_pdeathsig = 0;
709
710 if (credential_changing &&
711 #ifdef CAPABILITY_MODE
712 ((oldcred->cr_flags & CRED_FLAG_CAPMODE) == 0) &&
713 #endif
714 (imgp->vp->v_mount->mnt_flag & MNT_NOSUID) == 0 &&
715 (p->p_flag & P_TRACED) == 0) {
716 imgp->credential_setid = true;
717 VOP_UNLOCK(imgp->vp);
718 imgp->newcred = crdup(oldcred);
719 if (attr.va_mode & S_ISUID) {
720 euip = uifind(attr.va_uid);
721 change_euid(imgp->newcred, euip);
722 }
723 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
724 if (attr.va_mode & S_ISGID)
725 change_egid(imgp->newcred, attr.va_gid);
726 /*
727 * Implement correct POSIX saved-id behavior.
728 *
729 * XXXMAC: Note that the current logic will save the
730 * uid and gid if a MAC domain transition occurs, even
731 * though maybe it shouldn't.
732 */
733 change_svuid(imgp->newcred, imgp->newcred->cr_uid);
734 change_svgid(imgp->newcred, imgp->newcred->cr_gid);
735 } else {
736 /*
737 * Implement correct POSIX saved-id behavior.
738 *
739 * XXX: It's not clear that the existing behavior is
740 * POSIX-compliant. A number of sources indicate that the
741 * saved uid/gid should only be updated if the new ruid is
742 * not equal to the old ruid, or the new euid is not equal
743 * to the old euid and the new euid is not equal to the old
744 * ruid. The FreeBSD code always updates the saved uid/gid.
745 * Also, this code uses the new (replaced) euid and egid as
746 * the source, which may or may not be the right ones to use.
747 */
748 if (oldcred->cr_svuid != oldcred->cr_uid ||
749 oldcred->cr_svgid != oldcred->cr_gid) {
750 VOP_UNLOCK(imgp->vp);
751 imgp->newcred = crdup(oldcred);
752 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
753 change_svuid(imgp->newcred, imgp->newcred->cr_uid);
754 change_svgid(imgp->newcred, imgp->newcred->cr_gid);
755 }
756 }
757 /* The new credentials are installed into the process later. */
758
759 /*
760 * Loop through the list of image activators, calling each one.
761 * An activator returns -1 if there is no match, 0 on success,
762 * and an error otherwise.
763 */
764 error = -1;
765 for (i = 0; error == -1 && execsw[i]; ++i) {
766 if (execsw[i]->ex_imgact == NULL)
767 continue;
768 error = (*execsw[i]->ex_imgact)(imgp);
769 }
770
771 if (error) {
772 if (error == -1)
773 error = ENOEXEC;
774 goto exec_fail_dealloc;
775 }
776
777 /*
778 * Special interpreter operation, cleanup and loop up to try to
779 * activate the interpreter.
780 */
781 if ((imgp->interpreted & ~IMGACT_INTERP_ELF) != 0) {
782 exec_unmap_first_page(imgp);
783 /*
784 * The text reference needs to be removed for scripts.
785 * There is a short period before we determine that
786 * something is a script where text reference is active.
787 * The vnode lock is held over this entire period
788 * so nothing should illegitimately be blocked.
789 */
790 MPASS(imgp->textset);
791 VOP_UNSET_TEXT_CHECKED(newtextvp);
792 imgp->textset = false;
793 /* free name buffer and old vnode */
794 #ifdef MAC
795 mac_execve_interpreter_enter(newtextvp, &interpvplabel);
796 #endif
797 if (imgp->opened) {
798 VOP_CLOSE(newtextvp, FREAD, td->td_ucred, td);
799 imgp->opened = false;
800 }
801 vput(newtextvp);
802 imgp->vp = newtextvp = NULL;
803 if (args->fname != NULL) {
804 if (newtextdvp != NULL) {
805 vrele(newtextdvp);
806 newtextdvp = NULL;
807 }
808 NDFREE_PNBUF(&nd);
809 free(newbinname, M_PARGS);
810 newbinname = NULL;
811 }
812 vm_object_deallocate(imgp->object);
813 imgp->object = NULL;
814 execve_nosetid(imgp);
815 imgp->execpath = NULL;
816 free(imgp->freepath, M_TEMP);
817 imgp->freepath = NULL;
818 /* set new name to that of the interpreter */
819 if (imgp->interpreter_vp) {
820 args->fname = NULL;
821 } else {
822 args->fname = imgp->interpreter_name;
823 }
824 goto interpret;
825 }
826
827 /*
828 * NB: We unlock the vnode here because it is believed that none
829 * of the sv_copyout_strings/sv_fixup operations require the vnode.
830 */
831 VOP_UNLOCK(imgp->vp);
832
833 if (disallow_high_osrel &&
834 P_OSREL_MAJOR(p->p_osrel) > P_OSREL_MAJOR(__FreeBSD_version)) {
835 error = ENOEXEC;
836 uprintf("Osrel %d for image %s too high\n", p->p_osrel,
837 imgp->execpath != NULL ? imgp->execpath : "<unresolved>");
838 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
839 goto exec_fail_dealloc;
840 }
841
842 /*
843 * Copy out strings (args and env) and initialize stack base.
844 */
845 error = (*p->p_sysent->sv_copyout_strings)(imgp, &stack_base);
846 if (error != 0) {
847 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
848 goto exec_fail_dealloc;
849 }
850
851 /*
852 * Stack setup.
853 */
854 error = (*p->p_sysent->sv_fixup)(&stack_base, imgp);
855 if (error != 0) {
856 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
857 goto exec_fail_dealloc;
858 }
859
860 /*
861 * For security and other reasons, the file descriptor table cannot be
862 * shared after an exec.
863 */
864 fdunshare(td);
865 pdunshare(td);
866 /* close files on exec */
867 fdcloseexec(td);
868
869 /*
870 * Malloc things before we need locks.
871 */
872 i = exec_args_get_begin_envv(imgp->args) - imgp->args->begin_argv;
873 /* Cache arguments if they fit inside our allowance */
874 if (ps_arg_cache_limit >= i + sizeof(struct pargs)) {
875 newargs = pargs_alloc(i);
876 bcopy(imgp->args->begin_argv, newargs->ar_args, i);
877 }
878
879 /*
880 * For security and other reasons, signal handlers cannot
881 * be shared after an exec. The new process gets a copy of the old
882 * handlers. In execsigs(), the new process will have its signals
883 * reset.
884 */
885 if (sigacts_shared(p->p_sigacts)) {
886 oldsigacts = p->p_sigacts;
887 newsigacts = sigacts_alloc();
888 sigacts_copy(newsigacts, oldsigacts);
889 }
890
891 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
892
893 PROC_LOCK(p);
894 if (oldsigacts)
895 p->p_sigacts = newsigacts;
896 /* Stop profiling */
897 stopprofclock(p);
898
899 /* reset caught signals */
900 execsigs(p);
901
902 /* name this process - nameiexec(p, ndp) */
903 bzero(p->p_comm, sizeof(p->p_comm));
904 if (args->fname)
905 bcopy(nd.ni_cnd.cn_nameptr, p->p_comm,
906 min(nd.ni_cnd.cn_namelen, MAXCOMLEN));
907 else if (vn_commname(newtextvp, p->p_comm, sizeof(p->p_comm)) != 0)
908 bcopy(fexecv_proc_title, p->p_comm, sizeof(fexecv_proc_title));
909 bcopy(p->p_comm, td->td_name, sizeof(td->td_name));
910 #ifdef KTR
911 sched_clear_tdname(td);
912 #endif
913
914 /*
915 * mark as execed, wakeup the process that vforked (if any) and tell
916 * it that it now has its own resources back
917 */
918 p->p_flag |= P_EXEC;
919 td->td_pflags2 &= ~TDP2_UEXTERR;
920 if ((p->p_flag2 & P2_NOTRACE_EXEC) == 0)
921 p->p_flag2 &= ~P2_NOTRACE;
922 if ((p->p_flag2 & P2_STKGAP_DISABLE_EXEC) == 0)
923 p->p_flag2 &= ~P2_STKGAP_DISABLE;
924 p->p_flag2 &= ~(P2_MEMBAR_PRIVE | P2_MEMBAR_PRIVE_SYNCORE |
925 P2_MEMBAR_GLOBE);
926 if (p->p_flag & P_PPWAIT) {
927 p->p_flag &= ~(P_PPWAIT | P_PPTRACE);
928 cv_broadcast(&p->p_pwait);
929 /* STOPs are no longer ignored, arrange for AST */
930 signotify(td);
931 }
932
933 if ((imgp->sysent->sv_setid_allowed != NULL &&
934 !(*imgp->sysent->sv_setid_allowed)(td, imgp)) ||
935 (p->p_flag2 & P2_NO_NEW_PRIVS) != 0)
936 execve_nosetid(imgp);
937
938 /*
939 * Implement image setuid/setgid installation.
940 */
941 if (imgp->credential_setid) {
942 /*
943 * Turn off syscall tracing for set-id programs, except for
944 * root. Record any set-id flags first to make sure that
945 * we do not regain any tracing during a possible block.
946 */
947 setsugid(p);
948 #ifdef KTRACE
949 kiop = ktrprocexec(p);
950 #endif
951 /*
952 * Close any file descriptors 0..2 that reference procfs,
953 * then make sure file descriptors 0..2 are in use.
954 *
955 * Both fdsetugidsafety() and fdcheckstd() may call functions
956 * taking sleepable locks, so temporarily drop our locks.
957 */
958 PROC_UNLOCK(p);
959 VOP_UNLOCK(imgp->vp);
960 fdsetugidsafety(td);
961 error = fdcheckstd(td);
962 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
963 if (error != 0)
964 goto exec_fail_dealloc;
965 PROC_LOCK(p);
966 #ifdef MAC
967 if (will_transition) {
968 mac_vnode_execve_transition(oldcred, imgp->newcred,
969 imgp->vp, interpvplabel, imgp);
970 }
971 #endif
972 } else {
973 if (oldcred->cr_uid == oldcred->cr_ruid &&
974 oldcred->cr_gid == oldcred->cr_rgid)
975 p->p_flag &= ~P_SUGID;
976 }
977 /*
978 * Set the new credentials.
979 */
980 if (imgp->newcred != NULL) {
981 proc_set_cred(p, imgp->newcred);
982 crfree(oldcred);
983 oldcred = NULL;
984 }
985
986 /*
987 * Store the vp for use in kern.proc.pathname. This vnode was
988 * referenced by namei() or by fexecve variant of fname handling.
989 */
990 oldtextvp = p->p_textvp;
991 p->p_textvp = newtextvp;
992 oldtextdvp = p->p_textdvp;
993 p->p_textdvp = newtextdvp;
994 newtextdvp = NULL;
995 oldbinname = p->p_binname;
996 p->p_binname = newbinname;
997 newbinname = NULL;
998
999 #ifdef KDTRACE_HOOKS
1000 /*
1001 * Tell the DTrace fasttrap provider about the exec if it
1002 * has declared an interest.
1003 */
1004 if (dtrace_fasttrap_exec)
1005 dtrace_fasttrap_exec(p);
1006 #endif
1007
1008 /*
1009 * Notify others that we exec'd, and clear the P_INEXEC flag
1010 * as we're now a bona fide freshly-execed process.
1011 */
1012 KNOTE_LOCKED(p->p_klist, NOTE_EXEC);
1013 MPASS(p->p_execblock == 0);
1014 if ((p->p_flag & P_INEXEC_WAIT) != 0)
1015 wakeup(&p->p_execblock);
1016 p->p_flag &= ~(P_INEXEC | P_INEXEC_WAIT);
1017
1018 /* clear "fork but no exec" flag, as we _are_ execing */
1019 p->p_acflag &= ~AFORK;
1020
1021 /*
1022 * Free any previous argument cache and replace it with
1023 * the new argument cache, if any.
1024 */
1025 oldargs = p->p_args;
1026 p->p_args = newargs;
1027 newargs = NULL;
1028
1029 PROC_UNLOCK(p);
1030
1031 #ifdef HWPMC_HOOKS
1032 /*
1033 * Check if system-wide sampling is in effect or if the
1034 * current process is using PMCs. If so, do exec() time
1035 * processing. This processing needs to happen AFTER the
1036 * P_INEXEC flag is cleared.
1037 */
1038 if (PMC_SYSTEM_SAMPLING_ACTIVE() || PMC_PROC_IS_USING_PMCS(p)) {
1039 VOP_UNLOCK(imgp->vp);
1040 pe.pm_credentialschanged = credential_changing;
1041 pe.pm_baseaddr = imgp->reloc_base;
1042 pe.pm_dynaddr = imgp->et_dyn_addr;
1043
1044 PMC_CALL_HOOK_X(td, PMC_FN_PROCESS_EXEC, (void *) &pe);
1045 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
1046 }
1047 #endif
1048
1049 #ifdef HWT_HOOKS
1050 if ((td->td_proc->p_flag2 & P2_HWT) != 0) {
1051 struct hwt_record_entry ent;
1052
1053 VOP_UNLOCK(imgp->vp);
1054 ent.fullpath = imgp->execpath;
1055 ent.addr = imgp->et_dyn_addr;
1056 ent.baseaddr = imgp->reloc_base;
1057 ent.record_type = HWT_RECORD_EXECUTABLE;
1058 HWT_CALL_HOOK(td, HWT_EXEC, &ent);
1059 vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
1060 }
1061 #endif
1062
1063 /* Set values passed into the program in registers. */
1064 (*p->p_sysent->sv_setregs)(td, imgp, stack_base);
1065
1066 VOP_UPDATE_ATIME(imgp->vp, NULL);
1067
1068 SDT_PROBE1(proc, , , exec__success, args->fname);
1069
1070 exec_fail_dealloc:
1071 if (error != 0) {
1072 p->p_osrel = orig_osrel;
1073 p->p_fctl0 = orig_fctl0;
1074 p->p_elf_brandinfo = orig_brandinfo;
1075 }
1076
1077 if (imgp->firstpage != NULL)
1078 exec_unmap_first_page(imgp);
1079
1080 if (imgp->vp != NULL) {
1081 if (imgp->opened)
1082 VOP_CLOSE(imgp->vp, FREAD, td->td_ucred, td);
1083 if (imgp->textset)
1084 VOP_UNSET_TEXT_CHECKED(imgp->vp);
1085 if (error != 0)
1086 vput(imgp->vp);
1087 else
1088 VOP_UNLOCK(imgp->vp);
1089 if (args->fname != NULL)
1090 NDFREE_PNBUF(&nd);
1091 if (newtextdvp != NULL)
1092 vrele(newtextdvp);
1093 free(newbinname, M_PARGS);
1094 }
1095
1096 if (imgp->object != NULL)
1097 vm_object_deallocate(imgp->object);
1098
1099 free(imgp->freepath, M_TEMP);
1100
1101 if (error == 0) {
1102 if (p->p_ptevents & PTRACE_EXEC) {
1103 PROC_LOCK(p);
1104 if (p->p_ptevents & PTRACE_EXEC)
1105 td->td_dbgflags |= TDB_EXEC;
1106 PROC_UNLOCK(p);
1107 }
1108 } else {
1109 exec_fail:
1110 /* we're done here, clear P_INEXEC */
1111 PROC_LOCK(p);
1112 if ((p->p_flag & P_INEXEC_WAIT) != 0)
1113 wakeup(&p->p_execblock);
1114 p->p_flag &= ~(P_INEXEC | P_INEXEC_WAIT);
1115 PROC_UNLOCK(p);
1116
1117 SDT_PROBE1(proc, , , exec__failure, error);
1118 }
1119
1120 if (imgp->newcred != NULL && oldcred != NULL)
1121 crfree(imgp->newcred);
1122
1123 #ifdef MAC
1124 mac_execve_exit(imgp);
1125 mac_execve_interpreter_exit(interpvplabel);
1126 #endif
1127 exec_free_args(args);
1128
1129 /*
1130 * Handle deferred decrement of ref counts.
1131 */
1132 if (oldtextvp != NULL)
1133 vrele(oldtextvp);
1134 if (oldtextdvp != NULL)
1135 vrele(oldtextdvp);
1136 free(oldbinname, M_PARGS);
1137 #ifdef KTRACE
1138 ktr_io_params_free(kiop);
1139 #endif
1140 pargs_drop(oldargs);
1141 pargs_drop(newargs);
1142 if (oldsigacts != NULL)
1143 sigacts_free(oldsigacts);
1144 if (euip != NULL)
1145 uifree(euip);
1146
1147 if (error && imgp->vmspace_destroyed) {
1148 /* sorry, no more process anymore. exit gracefully */
1149 exec_cleanup(td, oldvmspace);
1150 kern_exit(td, 0, SIGABRT);
1151 }
1152
1153 #ifdef KTRACE
1154 if (error == 0)
1155 ktrprocctor(p);
1156 #endif
1157
1158 /*
1159 * We don't want cpu_set_syscall_retval() to overwrite any of
1160 * the register values put in place by exec_setregs().
1161 * Implementations of cpu_set_syscall_retval() will leave
1162 * registers unmodified when returning EJUSTRETURN.
1163 */
1164 return (error == 0 ? EJUSTRETURN : error);
1165 }
1166
1167 void
exec_cleanup(struct thread * td,struct vmspace * oldvmspace)1168 exec_cleanup(struct thread *td, struct vmspace *oldvmspace)
1169 {
1170 if ((td->td_pflags & TDP_EXECVMSPC) != 0) {
1171 KASSERT(td->td_proc->p_vmspace != oldvmspace,
1172 ("oldvmspace still used"));
1173 vmspace_free(oldvmspace);
1174 td->td_pflags &= ~TDP_EXECVMSPC;
1175 }
1176 }
1177
1178 int
exec_map_first_page(struct image_params * imgp)1179 exec_map_first_page(struct image_params *imgp)
1180 {
1181 vm_object_t object;
1182 vm_page_t m;
1183 int error;
1184
1185 if (imgp->firstpage != NULL)
1186 exec_unmap_first_page(imgp);
1187
1188 object = imgp->vp->v_object;
1189 if (object == NULL)
1190 return (EACCES);
1191 #if VM_NRESERVLEVEL > 0
1192 if ((object->flags & OBJ_COLORED) == 0) {
1193 VM_OBJECT_WLOCK(object);
1194 vm_object_color(object, 0);
1195 VM_OBJECT_WUNLOCK(object);
1196 }
1197 #endif
1198 error = vm_page_grab_valid_unlocked(&m, object, 0,
1199 VM_ALLOC_COUNT(VM_INITIAL_PAGEIN) |
1200 VM_ALLOC_NORMAL | VM_ALLOC_NOBUSY | VM_ALLOC_WIRED);
1201
1202 if (error != VM_PAGER_OK)
1203 return (EIO);
1204 imgp->firstpage = sf_buf_alloc(m, 0);
1205 imgp->image_header = sf_buf_kva(imgp->firstpage);
1206
1207 return (0);
1208 }
1209
1210 void
exec_unmap_first_page(struct image_params * imgp)1211 exec_unmap_first_page(struct image_params *imgp)
1212 {
1213 vm_page_t m;
1214
1215 if (imgp->firstpage != NULL) {
1216 m = sf_buf_page(imgp->firstpage);
1217 sf_buf_free(imgp->firstpage);
1218 imgp->firstpage = NULL;
1219 vm_page_unwire(m, PQ_ACTIVE);
1220 }
1221 }
1222
1223 void
exec_onexec_old(struct thread * td)1224 exec_onexec_old(struct thread *td)
1225 {
1226 sigfastblock_clear(td);
1227 umtx_exec(td->td_proc);
1228 }
1229
1230 /*
1231 * This is an optimization which removes the unmanaged shared page
1232 * mapping. In combination with pmap_remove_pages(), which cleans all
1233 * managed mappings in the process' vmspace pmap, no work will be left
1234 * for pmap_remove(min, max).
1235 */
1236 void
exec_free_abi_mappings(struct proc * p)1237 exec_free_abi_mappings(struct proc *p)
1238 {
1239 struct vmspace *vmspace;
1240
1241 vmspace = p->p_vmspace;
1242 if (refcount_load(&vmspace->vm_refcnt) != 1)
1243 return;
1244
1245 if (!PROC_HAS_SHP(p))
1246 return;
1247
1248 pmap_remove(vmspace_pmap(vmspace), vmspace->vm_shp_base,
1249 vmspace->vm_shp_base + p->p_sysent->sv_shared_page_len);
1250 }
1251
1252 /*
1253 * Run down the current address space and install a new one.
1254 */
1255 int
exec_new_vmspace(struct image_params * imgp,struct sysentvec * sv)1256 exec_new_vmspace(struct image_params *imgp, struct sysentvec *sv)
1257 {
1258 int error;
1259 struct proc *p = imgp->proc;
1260 struct vmspace *vmspace = p->p_vmspace;
1261 struct thread *td = curthread;
1262 vm_offset_t sv_minuser;
1263 vm_map_t map;
1264
1265 imgp->vmspace_destroyed = true;
1266 imgp->sysent = sv;
1267
1268 if (p->p_sysent->sv_onexec_old != NULL)
1269 p->p_sysent->sv_onexec_old(td);
1270 itimers_exec(p);
1271
1272 EVENTHANDLER_DIRECT_INVOKE(process_exec, p, imgp);
1273
1274 /*
1275 * Blow away entire process VM, if address space not shared,
1276 * otherwise, create a new VM space so that other threads are
1277 * not disrupted
1278 */
1279 map = &vmspace->vm_map;
1280 if (map_at_zero)
1281 sv_minuser = sv->sv_minuser;
1282 else
1283 sv_minuser = MAX(sv->sv_minuser, PAGE_SIZE);
1284 if (refcount_load(&vmspace->vm_refcnt) == 1 &&
1285 vm_map_min(map) == sv_minuser &&
1286 vm_map_max(map) == sv->sv_maxuser &&
1287 cpu_exec_vmspace_reuse(p, map)) {
1288 exec_free_abi_mappings(p);
1289 shmexit(vmspace);
1290 pmap_remove_pages(vmspace_pmap(vmspace));
1291 vm_map_remove(map, vm_map_min(map), vm_map_max(map));
1292 /*
1293 * An exec terminates mlockall(MCL_FUTURE).
1294 * ASLR and W^X states must be re-evaluated.
1295 */
1296 vm_map_lock(map);
1297 vm_map_modflags(map, 0, MAP_WIREFUTURE | MAP_ASLR |
1298 MAP_ASLR_IGNSTART | MAP_ASLR_STACK | MAP_WXORX);
1299 vm_map_unlock(map);
1300 } else {
1301 error = vmspace_exec(p, sv_minuser, sv->sv_maxuser);
1302 if (error)
1303 return (error);
1304 vmspace = p->p_vmspace;
1305 map = &vmspace->vm_map;
1306 }
1307 map->flags |= imgp->map_flags;
1308
1309 return (sv->sv_onexec != NULL ? sv->sv_onexec(p, imgp) : 0);
1310 }
1311
1312 /*
1313 * Compute the stack size limit and map the main process stack.
1314 * Map the shared page.
1315 */
1316 int
exec_map_stack(struct image_params * imgp)1317 exec_map_stack(struct image_params *imgp)
1318 {
1319 struct rlimit rlim_stack;
1320 struct sysentvec *sv;
1321 struct proc *p;
1322 vm_map_t map;
1323 struct vmspace *vmspace;
1324 vm_offset_t stack_addr, stack_top;
1325 vm_offset_t sharedpage_addr;
1326 u_long ssiz;
1327 int error, find_space, stack_off;
1328 vm_prot_t stack_prot;
1329 vm_object_t obj;
1330
1331 p = imgp->proc;
1332 sv = p->p_sysent;
1333
1334 if (imgp->stack_sz != 0) {
1335 ssiz = trunc_page(imgp->stack_sz);
1336 PROC_LOCK(p);
1337 lim_rlimit_proc(p, RLIMIT_STACK, &rlim_stack);
1338 PROC_UNLOCK(p);
1339 if (ssiz > rlim_stack.rlim_max)
1340 ssiz = rlim_stack.rlim_max;
1341 if (ssiz > rlim_stack.rlim_cur) {
1342 rlim_stack.rlim_cur = ssiz;
1343 kern_setrlimit(curthread, RLIMIT_STACK, &rlim_stack);
1344 }
1345 } else if (sv->sv_maxssiz != NULL) {
1346 ssiz = *sv->sv_maxssiz;
1347 } else {
1348 ssiz = maxssiz;
1349 }
1350
1351 vmspace = p->p_vmspace;
1352 map = &vmspace->vm_map;
1353
1354 stack_prot = sv->sv_shared_page_obj != NULL && imgp->stack_prot != 0 ?
1355 imgp->stack_prot : sv->sv_stackprot;
1356 if ((map->flags & MAP_ASLR_STACK) != 0) {
1357 stack_addr = round_page((vm_offset_t)p->p_vmspace->vm_daddr +
1358 lim_max(curthread, RLIMIT_DATA));
1359 find_space = VMFS_ANY_SPACE;
1360 } else {
1361 stack_addr = sv->sv_usrstack - ssiz;
1362 find_space = VMFS_NO_SPACE;
1363 }
1364 error = vm_map_find(map, NULL, 0, &stack_addr, (vm_size_t)ssiz,
1365 sv->sv_usrstack, find_space, stack_prot, VM_PROT_ALL,
1366 MAP_STACK_AREA);
1367 if (error != KERN_SUCCESS) {
1368 uprintf("exec_new_vmspace: mapping stack size %#jx prot %#x "
1369 "failed, mach error %d errno %d\n", (uintmax_t)ssiz,
1370 stack_prot, error, vm_mmap_to_errno(error));
1371 return (vm_mmap_to_errno(error));
1372 }
1373
1374 stack_top = stack_addr + ssiz;
1375 if ((map->flags & MAP_ASLR_STACK) != 0) {
1376 /* Randomize within the first page of the stack. */
1377 arc4rand(&stack_off, sizeof(stack_off), 0);
1378 stack_top -= rounddown2(stack_off & PAGE_MASK, sizeof(void *));
1379 }
1380
1381 /* Map a shared page */
1382 obj = sv->sv_shared_page_obj;
1383 if (obj == NULL) {
1384 sharedpage_addr = 0;
1385 goto out;
1386 }
1387
1388 /*
1389 * If randomization is disabled then the shared page will
1390 * be mapped at address specified in sysentvec.
1391 * Otherwise any address above .data section can be selected.
1392 * Same logic is used for stack address randomization.
1393 * If the address randomization is applied map a guard page
1394 * at the top of UVA.
1395 */
1396 vm_object_reference(obj);
1397 if ((imgp->imgp_flags & IMGP_ASLR_SHARED_PAGE) != 0) {
1398 sharedpage_addr = round_page((vm_offset_t)p->p_vmspace->vm_daddr +
1399 lim_max(curthread, RLIMIT_DATA));
1400
1401 error = vm_map_fixed(map, NULL, 0,
1402 sv->sv_maxuser - PAGE_SIZE, PAGE_SIZE,
1403 VM_PROT_NONE, VM_PROT_NONE, MAP_CREATE_GUARD);
1404 if (error != KERN_SUCCESS) {
1405 /*
1406 * This is not fatal, so let's just print a warning
1407 * and continue.
1408 */
1409 uprintf("%s: Mapping guard page at the top of UVA failed"
1410 " mach error %d errno %d",
1411 __func__, error, vm_mmap_to_errno(error));
1412 }
1413
1414 error = vm_map_find(map, obj, 0,
1415 &sharedpage_addr, sv->sv_shared_page_len,
1416 sv->sv_maxuser, VMFS_ANY_SPACE,
1417 VM_PROT_READ | VM_PROT_EXECUTE,
1418 VM_PROT_READ | VM_PROT_EXECUTE,
1419 MAP_INHERIT_SHARE | MAP_ACC_NO_CHARGE);
1420 } else {
1421 sharedpage_addr = sv->sv_shared_page_base;
1422 error = vm_map_fixed(map, obj, 0,
1423 sharedpage_addr, sv->sv_shared_page_len,
1424 VM_PROT_READ | VM_PROT_EXECUTE,
1425 VM_PROT_READ | VM_PROT_EXECUTE,
1426 MAP_INHERIT_SHARE | MAP_ACC_NO_CHARGE);
1427 }
1428 if (error != KERN_SUCCESS) {
1429 uprintf("%s: mapping shared page at addr: %p"
1430 "failed, mach error %d errno %d\n", __func__,
1431 (void *)sharedpage_addr, error, vm_mmap_to_errno(error));
1432 vm_object_deallocate(obj);
1433 return (vm_mmap_to_errno(error));
1434 }
1435 out:
1436 /*
1437 * vm_ssize and vm_maxsaddr are somewhat antiquated concepts, but they
1438 * are still used to enforce the stack rlimit on the process stack.
1439 */
1440 vmspace->vm_maxsaddr = (char *)stack_addr;
1441 vmspace->vm_stacktop = stack_top;
1442 vmspace->vm_ssize = sgrowsiz >> PAGE_SHIFT;
1443 vmspace->vm_shp_base = sharedpage_addr;
1444
1445 return (0);
1446 }
1447
1448 /*
1449 * Copy out argument and environment strings from the old process address
1450 * space into the temporary string buffer.
1451 */
1452 int
exec_copyin_args(struct image_args * args,const char * fname,char ** argv,char ** envv)1453 exec_copyin_args(struct image_args *args, const char *fname,
1454 char **argv, char **envv)
1455 {
1456 u_long arg, env;
1457 int error;
1458
1459 bzero(args, sizeof(*args));
1460 if (argv == NULL)
1461 return (EFAULT);
1462
1463 /*
1464 * Allocate demand-paged memory for the file name, argument, and
1465 * environment strings.
1466 */
1467 error = exec_alloc_args(args);
1468 if (error != 0)
1469 return (error);
1470
1471 /*
1472 * Copy the file name.
1473 */
1474 error = exec_args_add_fname(args, fname, UIO_USERSPACE);
1475 if (error != 0)
1476 goto err_exit;
1477
1478 /*
1479 * extract arguments first
1480 */
1481 for (;;) {
1482 error = fueword(argv++, &arg);
1483 if (error == -1) {
1484 error = EFAULT;
1485 goto err_exit;
1486 }
1487 if (arg == 0)
1488 break;
1489 error = exec_args_add_arg(args, (char *)(uintptr_t)arg,
1490 UIO_USERSPACE);
1491 if (error != 0)
1492 goto err_exit;
1493 }
1494
1495 /*
1496 * extract environment strings
1497 */
1498 if (envv) {
1499 for (;;) {
1500 error = fueword(envv++, &env);
1501 if (error == -1) {
1502 error = EFAULT;
1503 goto err_exit;
1504 }
1505 if (env == 0)
1506 break;
1507 error = exec_args_add_env(args,
1508 (char *)(uintptr_t)env, UIO_USERSPACE);
1509 if (error != 0)
1510 goto err_exit;
1511 }
1512 }
1513
1514 return (0);
1515
1516 err_exit:
1517 exec_free_args(args);
1518 return (error);
1519 }
1520
1521 struct exec_args_kva {
1522 void *addr;
1523 u_int gen;
1524 SLIST_ENTRY(exec_args_kva) next;
1525 };
1526
1527 DPCPU_DEFINE_STATIC(struct exec_args_kva *, exec_args_kva);
1528
1529 static SLIST_HEAD(, exec_args_kva) exec_args_kva_freelist;
1530 static struct mtx exec_args_kva_mtx;
1531 static u_int exec_args_gen;
1532
1533 static void
exec_prealloc_args_kva(void * arg __unused)1534 exec_prealloc_args_kva(void *arg __unused)
1535 {
1536 struct exec_args_kva *argkva;
1537 u_int i;
1538
1539 SLIST_INIT(&exec_args_kva_freelist);
1540 mtx_init(&exec_args_kva_mtx, "exec args kva", NULL, MTX_DEF);
1541 for (i = 0; i < exec_map_entries; i++) {
1542 argkva = malloc(sizeof(*argkva), M_PARGS, M_WAITOK);
1543 argkva->addr = kmap_alloc_wait(exec_map, exec_map_entry_size,
1544 ptoa(exec_map_guard_pages));
1545 argkva->gen = exec_args_gen;
1546 SLIST_INSERT_HEAD(&exec_args_kva_freelist, argkva, next);
1547 }
1548 }
1549 SYSINIT(exec_args_kva, SI_SUB_EXEC, SI_ORDER_ANY, exec_prealloc_args_kva, NULL);
1550
1551 static void *
exec_alloc_args_kva(void ** cookie)1552 exec_alloc_args_kva(void **cookie)
1553 {
1554 struct exec_args_kva *argkva;
1555
1556 argkva = (void *)atomic_readandclear_ptr(
1557 (uintptr_t *)DPCPU_PTR(exec_args_kva));
1558 if (argkva == NULL) {
1559 mtx_lock(&exec_args_kva_mtx);
1560 while ((argkva = SLIST_FIRST(&exec_args_kva_freelist)) == NULL)
1561 (void)mtx_sleep(&exec_args_kva_freelist,
1562 &exec_args_kva_mtx, 0, "execkva", 0);
1563 SLIST_REMOVE_HEAD(&exec_args_kva_freelist, next);
1564 mtx_unlock(&exec_args_kva_mtx);
1565 }
1566 kasan_mark(argkva->addr, exec_map_entry_size, exec_map_entry_size, 0);
1567 *(struct exec_args_kva **)cookie = argkva;
1568 return (argkva->addr);
1569 }
1570
1571 static void
exec_release_args_kva(struct exec_args_kva * argkva,u_int gen)1572 exec_release_args_kva(struct exec_args_kva *argkva, u_int gen)
1573 {
1574 vm_offset_t base;
1575
1576 base = (vm_offset_t)argkva->addr;
1577 kasan_mark(argkva->addr, 0, exec_map_entry_size, KASAN_EXEC_ARGS_FREED);
1578 if (argkva->gen != gen) {
1579 (void)vm_map_madvise(exec_map, base, base + exec_map_entry_size,
1580 MADV_FREE);
1581 argkva->gen = gen;
1582 }
1583 if (!atomic_cmpset_ptr((uintptr_t *)DPCPU_PTR(exec_args_kva),
1584 (uintptr_t)NULL, (uintptr_t)argkva)) {
1585 mtx_lock(&exec_args_kva_mtx);
1586 SLIST_INSERT_HEAD(&exec_args_kva_freelist, argkva, next);
1587 wakeup_one(&exec_args_kva_freelist);
1588 mtx_unlock(&exec_args_kva_mtx);
1589 }
1590 }
1591
1592 static void
exec_free_args_kva(void * cookie)1593 exec_free_args_kva(void *cookie)
1594 {
1595
1596 exec_release_args_kva(cookie, exec_args_gen);
1597 }
1598
1599 static void
exec_args_kva_lowmem(void * arg __unused,int flags __unused)1600 exec_args_kva_lowmem(void *arg __unused, int flags __unused)
1601 {
1602 SLIST_HEAD(, exec_args_kva) head;
1603 struct exec_args_kva *argkva;
1604 u_int gen;
1605 int i;
1606
1607 gen = atomic_fetchadd_int(&exec_args_gen, 1) + 1;
1608
1609 /*
1610 * Force an madvise of each KVA range. Any currently allocated ranges
1611 * will have MADV_FREE applied once they are freed.
1612 */
1613 SLIST_INIT(&head);
1614 mtx_lock(&exec_args_kva_mtx);
1615 SLIST_SWAP(&head, &exec_args_kva_freelist, exec_args_kva);
1616 mtx_unlock(&exec_args_kva_mtx);
1617 while ((argkva = SLIST_FIRST(&head)) != NULL) {
1618 SLIST_REMOVE_HEAD(&head, next);
1619 exec_release_args_kva(argkva, gen);
1620 }
1621
1622 CPU_FOREACH(i) {
1623 argkva = (void *)atomic_readandclear_ptr(
1624 (uintptr_t *)DPCPU_ID_PTR(i, exec_args_kva));
1625 if (argkva != NULL)
1626 exec_release_args_kva(argkva, gen);
1627 }
1628 }
1629 EVENTHANDLER_DEFINE(vm_lowmem, exec_args_kva_lowmem, NULL,
1630 EVENTHANDLER_PRI_ANY);
1631
1632 /*
1633 * Allocate temporary demand-paged, zero-filled memory for the file name,
1634 * argument, and environment strings.
1635 */
1636 int
exec_alloc_args(struct image_args * args)1637 exec_alloc_args(struct image_args *args)
1638 {
1639
1640 args->buf = exec_alloc_args_kva(&args->bufkva);
1641 return (0);
1642 }
1643
1644 void
exec_free_args(struct image_args * args)1645 exec_free_args(struct image_args *args)
1646 {
1647
1648 if (args->buf != NULL) {
1649 exec_free_args_kva(args->bufkva);
1650 args->buf = NULL;
1651 }
1652 if (args->fname_buf != NULL) {
1653 free(args->fname_buf, M_TEMP);
1654 args->fname_buf = NULL;
1655 }
1656 }
1657
1658 /*
1659 * A set to functions to fill struct image args.
1660 *
1661 * NOTE: exec_args_add_fname() must be called (possibly with a NULL
1662 * fname) before the other functions. All exec_args_add_arg() calls must
1663 * be made before any exec_args_add_env() calls. exec_args_adjust_args()
1664 * may be called any time after exec_args_add_fname().
1665 *
1666 * exec_args_add_fname() - install path to be executed
1667 * exec_args_add_arg() - append an argument string
1668 * exec_args_add_env() - append an env string
1669 * exec_args_adjust_args() - adjust location of the argument list to
1670 * allow new arguments to be prepended
1671 */
1672 int
exec_args_add_fname(struct image_args * args,const char * fname,enum uio_seg segflg)1673 exec_args_add_fname(struct image_args *args, const char *fname,
1674 enum uio_seg segflg)
1675 {
1676 int error;
1677 size_t length;
1678
1679 KASSERT(args->fname == NULL, ("fname already appended"));
1680 KASSERT(args->endp == NULL, ("already appending to args"));
1681
1682 if (fname != NULL) {
1683 args->fname = args->buf;
1684 error = segflg == UIO_SYSSPACE ?
1685 copystr(fname, args->fname, PATH_MAX, &length) :
1686 copyinstr(fname, args->fname, PATH_MAX, &length);
1687 if (error != 0)
1688 return (error == ENAMETOOLONG ? E2BIG : error);
1689 } else
1690 length = 0;
1691
1692 /* Set up for _arg_*()/_env_*() */
1693 args->endp = args->buf + length;
1694 /* begin_argv must be set and kept updated */
1695 args->begin_argv = args->endp;
1696 KASSERT(exec_map_entry_size - length >= ARG_MAX,
1697 ("too little space remaining for arguments %zu < %zu",
1698 exec_map_entry_size - length, (size_t)ARG_MAX));
1699 args->stringspace = ARG_MAX;
1700
1701 return (0);
1702 }
1703
1704 static int
exec_args_add_str(struct image_args * args,const char * str,enum uio_seg segflg,int * countp)1705 exec_args_add_str(struct image_args *args, const char *str,
1706 enum uio_seg segflg, int *countp)
1707 {
1708 int error;
1709 size_t length;
1710
1711 KASSERT(args->endp != NULL, ("endp not initialized"));
1712 KASSERT(args->begin_argv != NULL, ("begin_argp not initialized"));
1713
1714 error = (segflg == UIO_SYSSPACE) ?
1715 copystr(str, args->endp, args->stringspace, &length) :
1716 copyinstr(str, args->endp, args->stringspace, &length);
1717 if (error != 0)
1718 return (error == ENAMETOOLONG ? E2BIG : error);
1719 args->stringspace -= length;
1720 args->endp += length;
1721 (*countp)++;
1722
1723 return (0);
1724 }
1725
1726 int
exec_args_add_arg(struct image_args * args,const char * argp,enum uio_seg segflg)1727 exec_args_add_arg(struct image_args *args, const char *argp,
1728 enum uio_seg segflg)
1729 {
1730
1731 KASSERT(args->envc == 0, ("appending args after env"));
1732
1733 return (exec_args_add_str(args, argp, segflg, &args->argc));
1734 }
1735
1736 int
exec_args_add_env(struct image_args * args,const char * envp,enum uio_seg segflg)1737 exec_args_add_env(struct image_args *args, const char *envp,
1738 enum uio_seg segflg)
1739 {
1740
1741 if (args->envc == 0)
1742 args->begin_envv = args->endp;
1743
1744 return (exec_args_add_str(args, envp, segflg, &args->envc));
1745 }
1746
1747 int
exec_args_adjust_args(struct image_args * args,size_t consume,ssize_t extend)1748 exec_args_adjust_args(struct image_args *args, size_t consume, ssize_t extend)
1749 {
1750 ssize_t offset;
1751
1752 KASSERT(args->endp != NULL, ("endp not initialized"));
1753 KASSERT(args->begin_argv != NULL, ("begin_argp not initialized"));
1754
1755 offset = extend - consume;
1756 if (args->stringspace < offset)
1757 return (E2BIG);
1758 memmove(args->begin_argv + extend, args->begin_argv + consume,
1759 args->endp - (args->begin_argv + consume));
1760 if (args->envc > 0)
1761 args->begin_envv += offset;
1762 args->endp += offset;
1763 args->stringspace -= offset;
1764 return (0);
1765 }
1766
1767 char *
exec_args_get_begin_envv(struct image_args * args)1768 exec_args_get_begin_envv(struct image_args *args)
1769 {
1770
1771 KASSERT(args->endp != NULL, ("endp not initialized"));
1772
1773 if (args->envc > 0)
1774 return (args->begin_envv);
1775 return (args->endp);
1776 }
1777
1778 /*
1779 * Copy strings out to the new process address space, constructing new arg
1780 * and env vector tables. Return a pointer to the base so that it can be used
1781 * as the initial stack pointer.
1782 */
1783 int
exec_copyout_strings(struct image_params * imgp,uintptr_t * stack_base)1784 exec_copyout_strings(struct image_params *imgp, uintptr_t *stack_base)
1785 {
1786 int argc, envc;
1787 char **vectp;
1788 char *stringp;
1789 uintptr_t destp, ustringp;
1790 struct ps_strings *arginfo;
1791 struct proc *p;
1792 struct sysentvec *sysent;
1793 size_t execpath_len;
1794 int error, szsigcode;
1795 char canary[sizeof(long) * 8];
1796
1797 p = imgp->proc;
1798 sysent = p->p_sysent;
1799
1800 destp = PROC_PS_STRINGS(p);
1801 arginfo = imgp->ps_strings = (void *)destp;
1802
1803 /*
1804 * Install sigcode.
1805 */
1806 if (sysent->sv_shared_page_base == 0 && sysent->sv_szsigcode != NULL) {
1807 szsigcode = *(sysent->sv_szsigcode);
1808 destp -= szsigcode;
1809 destp = rounddown2(destp, sizeof(void *));
1810 error = copyout(sysent->sv_sigcode, (void *)destp, szsigcode);
1811 if (error != 0)
1812 return (error);
1813 }
1814
1815 /*
1816 * Copy the image path for the rtld.
1817 */
1818 if (imgp->execpath != NULL && imgp->auxargs != NULL) {
1819 execpath_len = strlen(imgp->execpath) + 1;
1820 destp -= execpath_len;
1821 destp = rounddown2(destp, sizeof(void *));
1822 imgp->execpathp = (void *)destp;
1823 error = copyout(imgp->execpath, imgp->execpathp, execpath_len);
1824 if (error != 0)
1825 return (error);
1826 }
1827
1828 /*
1829 * Prepare the canary for SSP.
1830 */
1831 arc4rand(canary, sizeof(canary), 0);
1832 destp -= sizeof(canary);
1833 imgp->canary = (void *)destp;
1834 error = copyout(canary, imgp->canary, sizeof(canary));
1835 if (error != 0)
1836 return (error);
1837 imgp->canarylen = sizeof(canary);
1838
1839 /*
1840 * Prepare the pagesizes array.
1841 */
1842 imgp->pagesizeslen = sizeof(pagesizes[0]) * MAXPAGESIZES;
1843 destp -= imgp->pagesizeslen;
1844 destp = rounddown2(destp, sizeof(void *));
1845 imgp->pagesizes = (void *)destp;
1846 error = copyout(pagesizes, imgp->pagesizes, imgp->pagesizeslen);
1847 if (error != 0)
1848 return (error);
1849
1850 /*
1851 * Allocate room for the argument and environment strings.
1852 */
1853 destp -= ARG_MAX - imgp->args->stringspace;
1854 destp = rounddown2(destp, sizeof(void *));
1855 ustringp = destp;
1856
1857 if (imgp->auxargs) {
1858 /*
1859 * Allocate room on the stack for the ELF auxargs
1860 * array. It has up to AT_COUNT entries.
1861 */
1862 destp -= AT_COUNT * sizeof(Elf_Auxinfo);
1863 destp = rounddown2(destp, sizeof(void *));
1864 }
1865
1866 vectp = (char **)destp;
1867
1868 /*
1869 * Allocate room for the argv[] and env vectors including the
1870 * terminating NULL pointers.
1871 */
1872 vectp -= imgp->args->argc + 1 + imgp->args->envc + 1;
1873
1874 /*
1875 * vectp also becomes our initial stack base
1876 */
1877 *stack_base = (uintptr_t)vectp;
1878
1879 stringp = imgp->args->begin_argv;
1880 argc = imgp->args->argc;
1881 envc = imgp->args->envc;
1882
1883 /*
1884 * Copy out strings - arguments and environment.
1885 */
1886 error = copyout(stringp, (void *)ustringp,
1887 ARG_MAX - imgp->args->stringspace);
1888 if (error != 0)
1889 return (error);
1890
1891 /*
1892 * Fill in "ps_strings" struct for ps, w, etc.
1893 */
1894 imgp->argv = vectp;
1895 if (suword(&arginfo->ps_argvstr, (long)(intptr_t)vectp) != 0 ||
1896 suword32(&arginfo->ps_nargvstr, argc) != 0)
1897 return (EFAULT);
1898
1899 /*
1900 * Fill in argument portion of vector table.
1901 */
1902 for (; argc > 0; --argc) {
1903 if (suword(vectp++, ustringp) != 0)
1904 return (EFAULT);
1905 while (*stringp++ != 0)
1906 ustringp++;
1907 ustringp++;
1908 }
1909
1910 /* a null vector table pointer separates the argp's from the envp's */
1911 if (suword(vectp++, 0) != 0)
1912 return (EFAULT);
1913
1914 imgp->envv = vectp;
1915 if (suword(&arginfo->ps_envstr, (long)(intptr_t)vectp) != 0 ||
1916 suword32(&arginfo->ps_nenvstr, envc) != 0)
1917 return (EFAULT);
1918
1919 /*
1920 * Fill in environment portion of vector table.
1921 */
1922 for (; envc > 0; --envc) {
1923 if (suword(vectp++, ustringp) != 0)
1924 return (EFAULT);
1925 while (*stringp++ != 0)
1926 ustringp++;
1927 ustringp++;
1928 }
1929
1930 /* end of vector table is a null pointer */
1931 if (suword(vectp, 0) != 0)
1932 return (EFAULT);
1933
1934 if (imgp->auxargs) {
1935 vectp++;
1936 error = imgp->sysent->sv_copyout_auxargs(imgp,
1937 (uintptr_t)vectp);
1938 if (error != 0)
1939 return (error);
1940 }
1941
1942 return (0);
1943 }
1944
1945 /*
1946 * Check permissions of file to execute.
1947 * Called with imgp->vp locked.
1948 * Return 0 for success or error code on failure.
1949 */
1950 int
exec_check_permissions(struct image_params * imgp)1951 exec_check_permissions(struct image_params *imgp)
1952 {
1953 struct vnode *vp = imgp->vp;
1954 struct vattr *attr = imgp->attr;
1955 struct thread *td;
1956 int error;
1957
1958 td = curthread;
1959
1960 /* Get file attributes */
1961 error = VOP_GETATTR(vp, attr, td->td_ucred);
1962 if (error)
1963 return (error);
1964
1965 #ifdef MAC
1966 error = mac_vnode_check_exec(td->td_ucred, imgp->vp, imgp);
1967 if (error)
1968 return (error);
1969 #endif
1970
1971 /*
1972 * 1) Check if file execution is disabled for the filesystem that
1973 * this file resides on.
1974 * 2) Ensure that at least one execute bit is on. Otherwise, a
1975 * privileged user will always succeed, and we don't want this
1976 * to happen unless the file really is executable.
1977 * 3) Ensure that the file is a regular file.
1978 */
1979 if ((vp->v_mount->mnt_flag & MNT_NOEXEC) ||
1980 (attr->va_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) == 0 ||
1981 (attr->va_type != VREG))
1982 return (EACCES);
1983
1984 /*
1985 * Zero length files can't be exec'd
1986 */
1987 if (attr->va_size == 0)
1988 return (ENOEXEC);
1989
1990 /*
1991 * Check for execute permission to file based on current credentials.
1992 */
1993 error = VOP_ACCESS(vp, VEXEC, td->td_ucred, td);
1994 if (error)
1995 return (error);
1996
1997 /*
1998 * Check number of open-for-writes on the file and deny execution
1999 * if there are any.
2000 *
2001 * Add a text reference now so no one can write to the
2002 * executable while we're activating it.
2003 *
2004 * Remember if this was set before and unset it in case this is not
2005 * actually an executable image.
2006 */
2007 error = VOP_SET_TEXT(vp);
2008 if (error != 0)
2009 return (error);
2010 imgp->textset = true;
2011
2012 /*
2013 * Call filesystem specific open routine (which does nothing in the
2014 * general case).
2015 */
2016 error = VOP_OPEN(vp, FREAD, td->td_ucred, td, NULL);
2017 if (error == 0)
2018 imgp->opened = true;
2019 return (error);
2020 }
2021
2022 /*
2023 * Exec handler registration
2024 */
2025 int
exec_register(const struct execsw * execsw_arg)2026 exec_register(const struct execsw *execsw_arg)
2027 {
2028 const struct execsw **es, **xs, **newexecsw;
2029 u_int count = 2; /* New slot and trailing NULL */
2030
2031 if (execsw)
2032 for (es = execsw; *es; es++)
2033 count++;
2034 newexecsw = malloc(count * sizeof(*es), M_TEMP, M_WAITOK);
2035 xs = newexecsw;
2036 if (execsw)
2037 for (es = execsw; *es; es++)
2038 *xs++ = *es;
2039 *xs++ = execsw_arg;
2040 *xs = NULL;
2041 if (execsw)
2042 free(execsw, M_TEMP);
2043 execsw = newexecsw;
2044 return (0);
2045 }
2046
2047 int
exec_unregister(const struct execsw * execsw_arg)2048 exec_unregister(const struct execsw *execsw_arg)
2049 {
2050 const struct execsw **es, **xs, **newexecsw;
2051 int count = 1;
2052
2053 if (execsw == NULL)
2054 panic("unregister with no handlers left?\n");
2055
2056 for (es = execsw; *es; es++) {
2057 if (*es == execsw_arg)
2058 break;
2059 }
2060 if (*es == NULL)
2061 return (ENOENT);
2062 for (es = execsw; *es; es++)
2063 if (*es != execsw_arg)
2064 count++;
2065 newexecsw = malloc(count * sizeof(*es), M_TEMP, M_WAITOK);
2066 xs = newexecsw;
2067 for (es = execsw; *es; es++)
2068 if (*es != execsw_arg)
2069 *xs++ = *es;
2070 *xs = NULL;
2071 if (execsw)
2072 free(execsw, M_TEMP);
2073 execsw = newexecsw;
2074 return (0);
2075 }
2076
2077 /*
2078 * Write out a core segment to the compression stream.
2079 */
2080 static int
compress_chunk(struct coredump_params * cp,char * base,char * buf,size_t len)2081 compress_chunk(struct coredump_params *cp, char *base, char *buf, size_t len)
2082 {
2083 size_t chunk_len;
2084 int error;
2085
2086 error = 0;
2087 while (len > 0) {
2088 chunk_len = MIN(len, CORE_BUF_SIZE);
2089
2090 /*
2091 * We can get EFAULT error here.
2092 * In that case zero out the current chunk of the segment.
2093 */
2094 error = copyin(base, buf, chunk_len);
2095 if (error != 0)
2096 bzero(buf, chunk_len);
2097 error = compressor_write(cp->comp, buf, chunk_len);
2098 if (error != 0)
2099 break;
2100 base += chunk_len;
2101 len -= chunk_len;
2102 }
2103 return (error);
2104 }
2105
2106 int
core_write(struct coredump_params * cp,const void * base,size_t len,off_t offset,enum uio_seg seg,size_t * resid)2107 core_write(struct coredump_params *cp, const void *base, size_t len,
2108 off_t offset, enum uio_seg seg, size_t *resid)
2109 {
2110 return ((*cp->cdw->write_fn)(cp->cdw, base, len, offset, seg,
2111 cp->active_cred, resid, cp->td));
2112 }
2113
2114 static int
core_extend(struct coredump_params * cp,off_t newsz)2115 core_extend(struct coredump_params *cp, off_t newsz)
2116 {
2117 return ((*cp->cdw->extend_fn)(cp->cdw, newsz, cp->active_cred));
2118 }
2119
2120 int
core_output(char * base,size_t len,off_t offset,struct coredump_params * cp,void * tmpbuf)2121 core_output(char *base, size_t len, off_t offset, struct coredump_params *cp,
2122 void *tmpbuf)
2123 {
2124 vm_map_t map;
2125 size_t resid, runlen;
2126 int error;
2127 bool success;
2128
2129 KASSERT((uintptr_t)base % PAGE_SIZE == 0,
2130 ("%s: user address %p is not page-aligned", __func__, base));
2131
2132 if (cp->comp != NULL)
2133 return (compress_chunk(cp, base, tmpbuf, len));
2134
2135 error = 0;
2136 map = &cp->td->td_proc->p_vmspace->vm_map;
2137 for (; len > 0; base += runlen, offset += runlen, len -= runlen) {
2138 /*
2139 * Attempt to page in all virtual pages in the range. If a
2140 * virtual page is not backed by the pager, it is represented as
2141 * a hole in the file. This can occur with zero-filled
2142 * anonymous memory or truncated files, for example.
2143 */
2144 for (runlen = 0; runlen < len; runlen += PAGE_SIZE) {
2145 if (core_dump_can_intr && curproc_sigkilled())
2146 return (EINTR);
2147 error = vm_fault(map, (uintptr_t)base + runlen,
2148 VM_PROT_READ, VM_FAULT_NOFILL, NULL);
2149 if (runlen == 0)
2150 success = error == KERN_SUCCESS;
2151 else if ((error == KERN_SUCCESS) != success)
2152 break;
2153 }
2154
2155 if (success) {
2156 error = core_write(cp, base, runlen, offset,
2157 UIO_USERSPACE, &resid);
2158 if (error != 0) {
2159 if (error != EFAULT)
2160 break;
2161
2162 /*
2163 * EFAULT may be returned if the user mapping
2164 * could not be accessed, e.g., because a mapped
2165 * file has been truncated. Skip the page if no
2166 * progress was made, to protect against a
2167 * hypothetical scenario where vm_fault() was
2168 * successful but core_write() returns EFAULT
2169 * anyway.
2170 */
2171 runlen -= resid;
2172 if (runlen == 0) {
2173 success = false;
2174 runlen = PAGE_SIZE;
2175 }
2176 }
2177 }
2178 if (!success) {
2179 error = core_extend(cp, offset + runlen);
2180 if (error != 0)
2181 break;
2182 }
2183 }
2184 return (error);
2185 }
2186
2187 /*
2188 * Drain into a core file.
2189 */
2190 int
sbuf_drain_core_output(void * arg,const char * data,int len)2191 sbuf_drain_core_output(void *arg, const char *data, int len)
2192 {
2193 struct coredump_params *cp;
2194 struct proc *p;
2195 int error, locked;
2196
2197 cp = arg;
2198 p = cp->td->td_proc;
2199
2200 /*
2201 * Some kern_proc out routines that print to this sbuf may
2202 * call us with the process lock held. Draining with the
2203 * non-sleepable lock held is unsafe. The lock is needed for
2204 * those routines when dumping a live process. In our case we
2205 * can safely release the lock before draining and acquire
2206 * again after.
2207 */
2208 locked = PROC_LOCKED(p);
2209 if (locked)
2210 PROC_UNLOCK(p);
2211 if (cp->comp != NULL)
2212 error = compressor_write(cp->comp, __DECONST(char *, data),
2213 len);
2214 else
2215 error = core_write(cp, __DECONST(void *, data), len, cp->offset,
2216 UIO_SYSSPACE, NULL);
2217 if (locked)
2218 PROC_LOCK(p);
2219 if (error != 0)
2220 return (-error);
2221 cp->offset += len;
2222 return (len);
2223 }
2224