xref: /NextBSD/sys/kern/kern_exec.c (revision 4557fabb34e865d7f40be64b39c9e34fa41dbb60)
1 /*-
2  * Copyright (c) 1993, David Greenman
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  */
26 
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29 
30 #include "opt_capsicum.h"
31 #include "opt_hwpmc_hooks.h"
32 #include "opt_ktrace.h"
33 #include "opt_thrworkq.h"
34 #include "opt_vm.h"
35 
36 #include <sys/param.h>
37 #include <sys/capsicum.h>
38 #include <sys/systm.h>
39 #include <sys/eventhandler.h>
40 #include <sys/lock.h>
41 #include <sys/mutex.h>
42 #include <sys/sysproto.h>
43 #include <sys/signalvar.h>
44 #include <sys/kernel.h>
45 #include <sys/mount.h>
46 #include <sys/filedesc.h>
47 #include <sys/fcntl.h>
48 #include <sys/acct.h>
49 #include <sys/exec.h>
50 #include <sys/imgact.h>
51 #include <sys/imgact_elf.h>
52 #include <sys/wait.h>
53 #include <sys/malloc.h>
54 #include <sys/priv.h>
55 #include <sys/proc.h>
56 #include <sys/pioctl.h>
57 #include <sys/namei.h>
58 #include <sys/resourcevar.h>
59 #include <sys/rwlock.h>
60 #include <sys/sched.h>
61 #include <sys/sdt.h>
62 #include <sys/sf_buf.h>
63 #include <sys/syscallsubr.h>
64 #include <sys/sysent.h>
65 #include <sys/shm.h>
66 #include <sys/sysctl.h>
67 #ifdef THRWORKQ
68 #include <sys/thrworkq.h>
69 #endif
70 #include <sys/vnode.h>
71 #include <sys/stat.h>
72 #ifdef KTRACE
73 #include <sys/ktrace.h>
74 #endif
75 
76 #include <vm/vm.h>
77 #include <vm/vm_param.h>
78 #include <vm/pmap.h>
79 #include <vm/vm_page.h>
80 #include <vm/vm_map.h>
81 #include <vm/vm_kern.h>
82 #include <vm/vm_extern.h>
83 #include <vm/vm_object.h>
84 #include <vm/vm_pager.h>
85 
86 #ifdef	HWPMC_HOOKS
87 #include <sys/pmckern.h>
88 #endif
89 
90 #include <machine/reg.h>
91 
92 #include <security/audit/audit.h>
93 #include <security/mac/mac_framework.h>
94 
95 #ifdef KDTRACE_HOOKS
96 #include <sys/dtrace_bsd.h>
97 dtrace_execexit_func_t	dtrace_fasttrap_exec;
98 #endif
99 
100 SDT_PROVIDER_DECLARE(proc);
101 SDT_PROBE_DEFINE1(proc, , , exec, "char *");
102 SDT_PROBE_DEFINE1(proc, , , exec__failure, "int");
103 SDT_PROBE_DEFINE1(proc, , , exec__success, "char *");
104 
105 MALLOC_DEFINE(M_PARGS, "proc-args", "Process arguments");
106 
107 int coredump_pack_fileinfo = 1;
108 SYSCTL_INT(_kern, OID_AUTO, coredump_pack_fileinfo, CTLFLAG_RWTUN,
109     &coredump_pack_fileinfo, 0,
110     "Enable file path packing in 'procstat -f' coredump notes");
111 
112 int coredump_pack_vmmapinfo = 1;
113 SYSCTL_INT(_kern, OID_AUTO, coredump_pack_vmmapinfo, CTLFLAG_RWTUN,
114     &coredump_pack_vmmapinfo, 0,
115     "Enable file path packing in 'procstat -v' coredump notes");
116 
117 static int sysctl_kern_ps_strings(SYSCTL_HANDLER_ARGS);
118 static int sysctl_kern_usrstack(SYSCTL_HANDLER_ARGS);
119 static int sysctl_kern_stackprot(SYSCTL_HANDLER_ARGS);
120 static int do_execve(struct thread *td, struct image_args *args,
121     struct mac *mac_p);
122 
123 /* XXX This should be vm_size_t. */
124 SYSCTL_PROC(_kern, KERN_PS_STRINGS, ps_strings, CTLTYPE_ULONG|CTLFLAG_RD,
125     NULL, 0, sysctl_kern_ps_strings, "LU", "");
126 
127 /* XXX This should be vm_size_t. */
128 SYSCTL_PROC(_kern, KERN_USRSTACK, usrstack, CTLTYPE_ULONG|CTLFLAG_RD|
129     CTLFLAG_CAPRD, NULL, 0, sysctl_kern_usrstack, "LU", "");
130 
131 SYSCTL_PROC(_kern, OID_AUTO, stackprot, CTLTYPE_INT|CTLFLAG_RD,
132     NULL, 0, sysctl_kern_stackprot, "I", "");
133 
134 u_long ps_arg_cache_limit = PAGE_SIZE / 16;
135 SYSCTL_ULONG(_kern, OID_AUTO, ps_arg_cache_limit, CTLFLAG_RW,
136     &ps_arg_cache_limit, 0, "");
137 
138 static int disallow_high_osrel;
139 SYSCTL_INT(_kern, OID_AUTO, disallow_high_osrel, CTLFLAG_RW,
140     &disallow_high_osrel, 0,
141     "Disallow execution of binaries built for higher version of the world");
142 
143 static int map_at_zero = 0;
144 SYSCTL_INT(_security_bsd, OID_AUTO, map_at_zero, CTLFLAG_RWTUN, &map_at_zero, 0,
145     "Permit processes to map an object at virtual address 0.");
146 
147 static int
sysctl_kern_ps_strings(SYSCTL_HANDLER_ARGS)148 sysctl_kern_ps_strings(SYSCTL_HANDLER_ARGS)
149 {
150 	struct proc *p;
151 	int error;
152 
153 	p = curproc;
154 #ifdef SCTL_MASK32
155 	if (req->flags & SCTL_MASK32) {
156 		unsigned int val;
157 		val = (unsigned int)p->p_sysent->sv_psstrings;
158 		error = SYSCTL_OUT(req, &val, sizeof(val));
159 	} else
160 #endif
161 		error = SYSCTL_OUT(req, &p->p_sysent->sv_psstrings,
162 		   sizeof(p->p_sysent->sv_psstrings));
163 	return error;
164 }
165 
166 static int
sysctl_kern_usrstack(SYSCTL_HANDLER_ARGS)167 sysctl_kern_usrstack(SYSCTL_HANDLER_ARGS)
168 {
169 	struct proc *p;
170 	int error;
171 
172 	p = curproc;
173 #ifdef SCTL_MASK32
174 	if (req->flags & SCTL_MASK32) {
175 		unsigned int val;
176 		val = (unsigned int)p->p_sysent->sv_usrstack;
177 		error = SYSCTL_OUT(req, &val, sizeof(val));
178 	} else
179 #endif
180 		error = SYSCTL_OUT(req, &p->p_sysent->sv_usrstack,
181 		    sizeof(p->p_sysent->sv_usrstack));
182 	return error;
183 }
184 
185 static int
sysctl_kern_stackprot(SYSCTL_HANDLER_ARGS)186 sysctl_kern_stackprot(SYSCTL_HANDLER_ARGS)
187 {
188 	struct proc *p;
189 
190 	p = curproc;
191 	return (SYSCTL_OUT(req, &p->p_sysent->sv_stackprot,
192 	    sizeof(p->p_sysent->sv_stackprot)));
193 }
194 
195 /*
196  * Each of the items is a pointer to a `const struct execsw', hence the
197  * double pointer here.
198  */
199 static const struct execsw **execsw;
200 
201 #ifndef _SYS_SYSPROTO_H_
202 struct execve_args {
203 	char    *fname;
204 	char    **argv;
205 	char    **envv;
206 };
207 #endif
208 
209 int
sys_execve(struct thread * td,struct execve_args * uap)210 sys_execve(struct thread *td, struct execve_args *uap)
211 {
212 	struct image_args args;
213 	struct vmspace *oldvmspace;
214 	int error;
215 
216 	error = pre_execve(td, &oldvmspace);
217 
218 	if (error != 0)
219 		return (error);
220 	error = exec_copyin_args(&args, uap->fname, UIO_USERSPACE,
221 	    uap->argv, uap->envv);
222 	if (error == 0)
223 		error = kern_execve(td, &args, NULL);
224 	post_execve(td, error, oldvmspace);
225 	return (error);
226 }
227 
228 #ifndef _SYS_SYSPROTO_H_
229 struct fexecve_args {
230 	int	fd;
231 	char	**argv;
232 	char	**envv;
233 }
234 #endif
235 int
sys_fexecve(struct thread * td,struct fexecve_args * uap)236 sys_fexecve(struct thread *td, struct fexecve_args *uap)
237 {
238 	struct image_args args;
239 	struct vmspace *oldvmspace;
240 	int error;
241 
242 	error = pre_execve(td, &oldvmspace);
243 	if (error != 0)
244 		return (error);
245 	error = exec_copyin_args(&args, NULL, UIO_SYSSPACE,
246 	    uap->argv, uap->envv);
247 	if (error == 0) {
248 		args.fd = uap->fd;
249 		error = kern_execve(td, &args, NULL);
250 	}
251 	post_execve(td, error, oldvmspace);
252 	return (error);
253 }
254 
255 #ifndef _SYS_SYSPROTO_H_
256 struct __mac_execve_args {
257 	char	*fname;
258 	char	**argv;
259 	char	**envv;
260 	struct mac	*mac_p;
261 };
262 #endif
263 
264 int
sys___mac_execve(struct thread * td,struct __mac_execve_args * uap)265 sys___mac_execve(struct thread *td, struct __mac_execve_args *uap)
266 {
267 #ifdef MAC
268 	struct image_args args;
269 	struct vmspace *oldvmspace;
270 	int error;
271 
272 	error = pre_execve(td, &oldvmspace);
273 	if (error != 0)
274 		return (error);
275 	error = exec_copyin_args(&args, uap->fname, UIO_USERSPACE,
276 	    uap->argv, uap->envv);
277 	if (error == 0)
278 		error = kern_execve(td, &args, uap->mac_p);
279 	post_execve(td, error, oldvmspace);
280 	return (error);
281 #else
282 	return (ENOSYS);
283 #endif
284 }
285 
286 int
pre_execve(struct thread * td,struct vmspace ** oldvmspace)287 pre_execve(struct thread *td, struct vmspace **oldvmspace)
288 {
289 	struct proc *p;
290 	int error;
291 
292 	KASSERT(td == curthread, ("non-current thread %p", td));
293 	error = 0;
294 	p = td->td_proc;
295 	if ((p->p_flag & P_HADTHREADS) != 0) {
296 		PROC_LOCK(p);
297 		if (thread_single(p, SINGLE_BOUNDARY) != 0)
298 			error = ERESTART;
299 		PROC_UNLOCK(p);
300 	}
301 #ifdef THRWORKQ
302 	if (error == 0)
303 		thrworkq_exit(p);
304 #endif
305 	KASSERT(error != 0 || (td->td_pflags & TDP_EXECVMSPC) == 0,
306 	    ("nested execve"));
307 	*oldvmspace = p->p_vmspace;
308 	return (error);
309 }
310 
311 void
post_execve(struct thread * td,int error,struct vmspace * oldvmspace)312 post_execve(struct thread *td, int error, struct vmspace *oldvmspace)
313 {
314 	struct proc *p;
315 
316 	KASSERT(td == curthread, ("non-current thread %p", td));
317 	p = td->td_proc;
318 	if ((p->p_flag & P_HADTHREADS) != 0) {
319 		PROC_LOCK(p);
320 		/*
321 		 * If success, we upgrade to SINGLE_EXIT state to
322 		 * force other threads to suicide.
323 		 */
324 		if (error == 0)
325 			thread_single(p, SINGLE_EXIT);
326 		else
327 			thread_single_end(p, SINGLE_BOUNDARY);
328 		PROC_UNLOCK(p);
329 	}
330 	if ((td->td_pflags & TDP_EXECVMSPC) != 0) {
331 		KASSERT(p->p_vmspace != oldvmspace,
332 		    ("oldvmspace still used"));
333 		vmspace_free(oldvmspace);
334 		td->td_pflags &= ~TDP_EXECVMSPC;
335 	}
336 }
337 
338 /*
339  * XXX: kern_execve has the astonishing property of not always returning to
340  * the caller.  If sufficiently bad things happen during the call to
341  * do_execve(), it can end up calling exit1(); as a result, callers must
342  * avoid doing anything which they might need to undo (e.g., allocating
343  * memory).
344  */
345 int
kern_execve(struct thread * td,struct image_args * args,struct mac * mac_p)346 kern_execve(struct thread *td, struct image_args *args, struct mac *mac_p)
347 {
348 
349 	AUDIT_ARG_ARGV(args->begin_argv, args->argc,
350 	    args->begin_envv - args->begin_argv);
351 	AUDIT_ARG_ENVV(args->begin_envv, args->envc,
352 	    args->endp - args->begin_envv);
353 	return (do_execve(td, args, mac_p));
354 }
355 
356 /*
357  * In-kernel implementation of execve().  All arguments are assumed to be
358  * userspace pointers from the passed thread.
359  */
360 static int
do_execve(td,args,mac_p)361 do_execve(td, args, mac_p)
362 	struct thread *td;
363 	struct image_args *args;
364 	struct mac *mac_p;
365 {
366 	struct proc *p = td->td_proc;
367 	struct nameidata nd;
368 	struct ucred *newcred = NULL, *oldcred;
369 	struct uidinfo *euip = NULL;
370 	register_t *stack_base;
371 	int error, i;
372 	struct image_params image_params, *imgp;
373 	struct vattr attr;
374 	int (*img_first)(struct image_params *);
375 	struct pargs *oldargs = NULL, *newargs = NULL;
376 	struct sigacts *oldsigacts, *newsigacts;
377 #ifdef KTRACE
378 	struct vnode *tracevp = NULL;
379 	struct ucred *tracecred = NULL;
380 #endif
381 	struct vnode *oldtextvp = NULL, *newtextvp;
382 	cap_rights_t rights;
383 	int credential_changing;
384 	int textset;
385 #ifdef MAC
386 	struct label *interpvplabel = NULL;
387 	int will_transition;
388 #endif
389 #ifdef HWPMC_HOOKS
390 	struct pmckern_procexec pe;
391 #endif
392 	static const char fexecv_proc_title[] = "(fexecv)";
393 
394 	imgp = &image_params;
395 
396 	/*
397 	 * Lock the process and set the P_INEXEC flag to indicate that
398 	 * it should be left alone until we're done here.  This is
399 	 * necessary to avoid race conditions - e.g. in ptrace() -
400 	 * that might allow a local user to illicitly obtain elevated
401 	 * privileges.
402 	 */
403 	PROC_LOCK(p);
404 	KASSERT((p->p_flag & P_INEXEC) == 0,
405 	    ("%s(): process already has P_INEXEC flag", __func__));
406 	p->p_flag |= P_INEXEC;
407 	PROC_UNLOCK(p);
408 
409 	/*
410 	 * Initialize part of the common data
411 	 */
412 	bzero(imgp, sizeof(*imgp));
413 	imgp->proc = p;
414 	imgp->attr = &attr;
415 	imgp->args = args;
416 
417 #ifdef MAC
418 	error = mac_execve_enter(imgp, mac_p);
419 	if (error)
420 		goto exec_fail;
421 #endif
422 
423 	/*
424 	 * Translate the file name. namei() returns a vnode pointer
425 	 *	in ni_vp amoung other things.
426 	 *
427 	 * XXXAUDIT: It would be desirable to also audit the name of the
428 	 * interpreter if this is an interpreted binary.
429 	 */
430 	if (args->fname != NULL) {
431 		NDINIT(&nd, LOOKUP, ISOPEN | LOCKLEAF | FOLLOW | SAVENAME
432 		    | AUDITVNODE1, UIO_SYSSPACE, args->fname, td);
433 	}
434 
435 	SDT_PROBE1(proc, , , exec, args->fname);
436 
437 interpret:
438 	if (args->fname != NULL) {
439 #ifdef CAPABILITY_MODE
440 		/*
441 		 * While capability mode can't reach this point via direct
442 		 * path arguments to execve(), we also don't allow
443 		 * interpreters to be used in capability mode (for now).
444 		 * Catch indirect lookups and return a permissions error.
445 		 */
446 		if (IN_CAPABILITY_MODE(td)) {
447 			error = ECAPMODE;
448 			goto exec_fail;
449 		}
450 #endif
451 		error = namei(&nd);
452 		if (error)
453 			goto exec_fail;
454 
455 		newtextvp = nd.ni_vp;
456 		imgp->vp = newtextvp;
457 	} else {
458 		AUDIT_ARG_FD(args->fd);
459 		/*
460 		 * Descriptors opened only with O_EXEC or O_RDONLY are allowed.
461 		 */
462 		error = fgetvp_exec(td, args->fd,
463 		    cap_rights_init(&rights, CAP_FEXECVE), &newtextvp);
464 		if (error)
465 			goto exec_fail;
466 		vn_lock(newtextvp, LK_EXCLUSIVE | LK_RETRY);
467 		AUDIT_ARG_VNODE1(newtextvp);
468 		imgp->vp = newtextvp;
469 	}
470 
471 	/*
472 	 * Check file permissions (also 'opens' file)
473 	 */
474 	error = exec_check_permissions(imgp);
475 	if (error)
476 		goto exec_fail_dealloc;
477 
478 	imgp->object = imgp->vp->v_object;
479 	if (imgp->object != NULL)
480 		vm_object_reference(imgp->object);
481 
482 	/*
483 	 * Set VV_TEXT now so no one can write to the executable while we're
484 	 * activating it.
485 	 *
486 	 * Remember if this was set before and unset it in case this is not
487 	 * actually an executable image.
488 	 */
489 	textset = VOP_IS_TEXT(imgp->vp);
490 	VOP_SET_TEXT(imgp->vp);
491 
492 	error = exec_map_first_page(imgp);
493 	if (error)
494 		goto exec_fail_dealloc;
495 
496 	imgp->proc->p_osrel = 0;
497 	/*
498 	 *	If the current process has a special image activator it
499 	 *	wants to try first, call it.   For example, emulating shell
500 	 *	scripts differently.
501 	 */
502 	error = -1;
503 	if ((img_first = imgp->proc->p_sysent->sv_imgact_try) != NULL)
504 		error = img_first(imgp);
505 
506 	/*
507 	 *	Loop through the list of image activators, calling each one.
508 	 *	An activator returns -1 if there is no match, 0 on success,
509 	 *	and an error otherwise.
510 	 */
511 	for (i = 0; error == -1 && execsw[i]; ++i) {
512 		if (execsw[i]->ex_imgact == NULL ||
513 		    execsw[i]->ex_imgact == img_first) {
514 			continue;
515 		}
516 		error = (*execsw[i]->ex_imgact)(imgp);
517 	}
518 
519 	if (error) {
520 		if (error == -1) {
521 			if (textset == 0)
522 				VOP_UNSET_TEXT(imgp->vp);
523 			error = ENOEXEC;
524 		}
525 		goto exec_fail_dealloc;
526 	}
527 
528 	/*
529 	 * Special interpreter operation, cleanup and loop up to try to
530 	 * activate the interpreter.
531 	 */
532 	if (imgp->interpreted) {
533 		exec_unmap_first_page(imgp);
534 		/*
535 		 * VV_TEXT needs to be unset for scripts.  There is a short
536 		 * period before we determine that something is a script where
537 		 * VV_TEXT will be set. The vnode lock is held over this
538 		 * entire period so nothing should illegitimately be blocked.
539 		 */
540 		VOP_UNSET_TEXT(imgp->vp);
541 		/* free name buffer and old vnode */
542 		if (args->fname != NULL)
543 			NDFREE(&nd, NDF_ONLY_PNBUF);
544 #ifdef MAC
545 		mac_execve_interpreter_enter(newtextvp, &interpvplabel);
546 #endif
547 		if (imgp->opened) {
548 			VOP_CLOSE(newtextvp, FREAD, td->td_ucred, td);
549 			imgp->opened = 0;
550 		}
551 		vput(newtextvp);
552 		vm_object_deallocate(imgp->object);
553 		imgp->object = NULL;
554 		/* set new name to that of the interpreter */
555 		NDINIT(&nd, LOOKUP, LOCKLEAF | FOLLOW | SAVENAME,
556 		    UIO_SYSSPACE, imgp->interpreter_name, td);
557 		args->fname = imgp->interpreter_name;
558 		goto interpret;
559 	}
560 
561 	/*
562 	 * NB: We unlock the vnode here because it is believed that none
563 	 * of the sv_copyout_strings/sv_fixup operations require the vnode.
564 	 */
565 	VOP_UNLOCK(imgp->vp, 0);
566 
567 	/*
568 	 * Do the best to calculate the full path to the image file.
569 	 */
570 	if (imgp->auxargs != NULL &&
571 	    ((args->fname != NULL && args->fname[0] == '/') ||
572 	     vn_fullpath(td, imgp->vp, &imgp->execpath, &imgp->freepath) != 0))
573 		imgp->execpath = args->fname;
574 
575 	if (disallow_high_osrel &&
576 	    P_OSREL_MAJOR(p->p_osrel) > P_OSREL_MAJOR(__FreeBSD_version)) {
577 		error = ENOEXEC;
578 		uprintf("Osrel %d for image %s too high\n", p->p_osrel,
579 		    imgp->execpath != NULL ? imgp->execpath : "<unresolved>");
580 		vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
581 		goto exec_fail_dealloc;
582 	}
583 
584 	/* ABI enforces the use of Capsicum. Switch into capabilities mode. */
585 	if (SV_PROC_FLAG(p, SV_CAPSICUM))
586 		sys_cap_enter(td, NULL);
587 
588 	/*
589 	 * Copy out strings (args and env) and initialize stack base
590 	 */
591 	if (p->p_sysent->sv_copyout_strings)
592 		stack_base = (*p->p_sysent->sv_copyout_strings)(imgp);
593 	else
594 		stack_base = exec_copyout_strings(imgp);
595 
596 	/*
597 	 * If custom stack fixup routine present for this process
598 	 * let it do the stack setup.
599 	 * Else stuff argument count as first item on stack
600 	 */
601 	if (p->p_sysent->sv_fixup != NULL)
602 		(*p->p_sysent->sv_fixup)(&stack_base, imgp);
603 	else
604 		suword(--stack_base, imgp->args->argc);
605 
606 	if (args->fdp != NULL) {
607 		/* Install a brand new file descriptor table. */
608 		fdinstall_remapped(td, args->fdp);
609 		args->fdp = NULL;
610 	} else {
611 		/*
612 		 * Keep on using the existing file descriptor table. For
613 		 * security and other reasons, the file descriptor table
614 		 * cannot be shared after an exec.
615 		 */
616 		fdunshare(td);
617 		/* close files on exec */
618 		fdcloseexec(td);
619 	}
620 
621 	/*
622 	 * Malloc things before we need locks.
623 	 */
624 	i = imgp->args->begin_envv - imgp->args->begin_argv;
625 	/* Cache arguments if they fit inside our allowance */
626 	if (ps_arg_cache_limit >= i + sizeof(struct pargs)) {
627 		newargs = pargs_alloc(i);
628 		bcopy(imgp->args->begin_argv, newargs->ar_args, i);
629 	}
630 
631 	vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
632 
633 	/*
634 	 * For security and other reasons, signal handlers cannot
635 	 * be shared after an exec. The new process gets a copy of the old
636 	 * handlers. In execsigs(), the new process will have its signals
637 	 * reset.
638 	 */
639 	if (sigacts_shared(p->p_sigacts)) {
640 		oldsigacts = p->p_sigacts;
641 		newsigacts = sigacts_alloc();
642 		sigacts_copy(newsigacts, oldsigacts);
643 	} else {
644 		oldsigacts = NULL;
645 		newsigacts = NULL; /* satisfy gcc */
646 	}
647 
648 	PROC_LOCK(p);
649 	if (oldsigacts)
650 		p->p_sigacts = newsigacts;
651 	oldcred = p->p_ucred;
652 	/* Stop profiling */
653 	stopprofclock(p);
654 
655 	/* reset caught signals */
656 	execsigs(p);
657 
658 	/* name this process - nameiexec(p, ndp) */
659 	bzero(p->p_comm, sizeof(p->p_comm));
660 	if (args->fname)
661 		bcopy(nd.ni_cnd.cn_nameptr, p->p_comm,
662 		    min(nd.ni_cnd.cn_namelen, MAXCOMLEN));
663 	else if (vn_commname(newtextvp, p->p_comm, sizeof(p->p_comm)) != 0)
664 		bcopy(fexecv_proc_title, p->p_comm, sizeof(fexecv_proc_title));
665 	bcopy(p->p_comm, td->td_name, sizeof(td->td_name));
666 #ifdef KTR
667 	sched_clear_tdname(td);
668 #endif
669 
670 	/*
671 	 * mark as execed, wakeup the process that vforked (if any) and tell
672 	 * it that it now has its own resources back
673 	 */
674 	p->p_flag |= P_EXEC;
675 	if ((p->p_flag2 & P2_NOTRACE_EXEC) == 0)
676 		p->p_flag2 &= ~P2_NOTRACE;
677 	if (p->p_flag & P_PPWAIT) {
678 		p->p_flag &= ~(P_PPWAIT | P_PPTRACE);
679 		cv_broadcast(&p->p_pwait);
680 	}
681 
682 	/*
683 	 * Implement image setuid/setgid.
684 	 *
685 	 * Don't honor setuid/setgid if the filesystem prohibits it or if
686 	 * the process is being traced.
687 	 *
688 	 * We disable setuid/setgid/etc in compatibility mode on the basis
689 	 * that most setugid applications are not written with that
690 	 * environment in mind, and will therefore almost certainly operate
691 	 * incorrectly. In principle there's no reason that setugid
692 	 * applications might not be useful in capability mode, so we may want
693 	 * to reconsider this conservative design choice in the future.
694 	 *
695 	 * XXXMAC: For the time being, use NOSUID to also prohibit
696 	 * transitions on the file system.
697 	 */
698 	credential_changing = 0;
699 	credential_changing |= (attr.va_mode & S_ISUID) && oldcred->cr_uid !=
700 	    attr.va_uid;
701 	credential_changing |= (attr.va_mode & S_ISGID) && oldcred->cr_gid !=
702 	    attr.va_gid;
703 #ifdef MAC
704 	will_transition = mac_vnode_execve_will_transition(oldcred, imgp->vp,
705 	    interpvplabel, imgp);
706 	credential_changing |= will_transition;
707 #endif
708 
709 	if (credential_changing &&
710 #ifdef CAPABILITY_MODE
711 	    ((oldcred->cr_flags & CRED_FLAG_CAPMODE) == 0) &&
712 #endif
713 	    (imgp->vp->v_mount->mnt_flag & MNT_NOSUID) == 0 &&
714 	    (p->p_flag & P_TRACED) == 0) {
715 		/*
716 		 * Turn off syscall tracing for set-id programs, except for
717 		 * root.  Record any set-id flags first to make sure that
718 		 * we do not regain any tracing during a possible block.
719 		 */
720 		setsugid(p);
721 
722 #ifdef KTRACE
723 		if (p->p_tracecred != NULL &&
724 		    priv_check_cred(p->p_tracecred, PRIV_DEBUG_DIFFCRED, 0))
725 			ktrprocexec(p, &tracecred, &tracevp);
726 #endif
727 		/*
728 		 * Close any file descriptors 0..2 that reference procfs,
729 		 * then make sure file descriptors 0..2 are in use.
730 		 *
731 		 * Both fdsetugidsafety() and fdcheckstd() may call functions
732 		 * taking sleepable locks, so temporarily drop our locks.
733 		 */
734 		PROC_UNLOCK(p);
735 		VOP_UNLOCK(imgp->vp, 0);
736 		fdsetugidsafety(td);
737 		error = fdcheckstd(td);
738 		if (error != 0)
739 			goto done1;
740 		newcred = crdup(oldcred);
741 		euip = uifind(attr.va_uid);
742 		vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
743 		PROC_LOCK(p);
744 		/*
745 		 * Set the new credentials.
746 		 */
747 		if (attr.va_mode & S_ISUID)
748 			change_euid(newcred, euip);
749 		if (attr.va_mode & S_ISGID)
750 			change_egid(newcred, attr.va_gid);
751 #ifdef MAC
752 		if (will_transition) {
753 			mac_vnode_execve_transition(oldcred, newcred, imgp->vp,
754 			    interpvplabel, imgp);
755 		}
756 #endif
757 		/*
758 		 * Implement correct POSIX saved-id behavior.
759 		 *
760 		 * XXXMAC: Note that the current logic will save the
761 		 * uid and gid if a MAC domain transition occurs, even
762 		 * though maybe it shouldn't.
763 		 */
764 		change_svuid(newcred, newcred->cr_uid);
765 		change_svgid(newcred, newcred->cr_gid);
766 		proc_set_cred(p, newcred);
767 	} else {
768 		if (oldcred->cr_uid == oldcred->cr_ruid &&
769 		    oldcred->cr_gid == oldcred->cr_rgid)
770 			p->p_flag &= ~P_SUGID;
771 		/*
772 		 * Implement correct POSIX saved-id behavior.
773 		 *
774 		 * XXX: It's not clear that the existing behavior is
775 		 * POSIX-compliant.  A number of sources indicate that the
776 		 * saved uid/gid should only be updated if the new ruid is
777 		 * not equal to the old ruid, or the new euid is not equal
778 		 * to the old euid and the new euid is not equal to the old
779 		 * ruid.  The FreeBSD code always updates the saved uid/gid.
780 		 * Also, this code uses the new (replaced) euid and egid as
781 		 * the source, which may or may not be the right ones to use.
782 		 */
783 		if (oldcred->cr_svuid != oldcred->cr_uid ||
784 		    oldcred->cr_svgid != oldcred->cr_gid) {
785 			PROC_UNLOCK(p);
786 			VOP_UNLOCK(imgp->vp, 0);
787 			newcred = crdup(oldcred);
788 			vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
789 			PROC_LOCK(p);
790 			change_svuid(newcred, newcred->cr_uid);
791 			change_svgid(newcred, newcred->cr_gid);
792 			proc_set_cred(p, newcred);
793 		}
794 	}
795 
796 	/*
797 	 * Store the vp for use in procfs.  This vnode was referenced by namei
798 	 * or fgetvp_exec.
799 	 */
800 	oldtextvp = p->p_textvp;
801 	p->p_textvp = newtextvp;
802 
803 #ifdef KDTRACE_HOOKS
804 	/*
805 	 * Tell the DTrace fasttrap provider about the exec if it
806 	 * has declared an interest.
807 	 */
808 	if (dtrace_fasttrap_exec)
809 		dtrace_fasttrap_exec(p);
810 #endif
811 
812 	/*
813 	 * Notify others that we exec'd, and clear the P_INEXEC flag
814 	 * as we're now a bona fide freshly-execed process.
815 	 */
816 	KNOTE_LOCKED(&p->p_klist, NOTE_EXEC);
817 	p->p_flag &= ~P_INEXEC;
818 
819 	/* clear "fork but no exec" flag, as we _are_ execing */
820 	p->p_acflag &= ~AFORK;
821 
822 	/*
823 	 * Free any previous argument cache and replace it with
824 	 * the new argument cache, if any.
825 	 */
826 	oldargs = p->p_args;
827 	p->p_args = newargs;
828 	newargs = NULL;
829 
830 #ifdef	HWPMC_HOOKS
831 	/*
832 	 * Check if system-wide sampling is in effect or if the
833 	 * current process is using PMCs.  If so, do exec() time
834 	 * processing.  This processing needs to happen AFTER the
835 	 * P_INEXEC flag is cleared.
836 	 *
837 	 * The proc lock needs to be released before taking the PMC
838 	 * SX.
839 	 */
840 	if (PMC_SYSTEM_SAMPLING_ACTIVE() || PMC_PROC_IS_USING_PMCS(p)) {
841 		PROC_UNLOCK(p);
842 		VOP_UNLOCK(imgp->vp, 0);
843 		pe.pm_credentialschanged = credential_changing;
844 		pe.pm_entryaddr = imgp->entry_addr;
845 
846 		PMC_CALL_HOOK_X(td, PMC_FN_PROCESS_EXEC, (void *) &pe);
847 		vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
848 	} else
849 		PROC_UNLOCK(p);
850 #else  /* !HWPMC_HOOKS */
851 	PROC_UNLOCK(p);
852 #endif
853 
854 	/* Set values passed into the program in registers. */
855 	if (p->p_sysent->sv_setregs)
856 		(*p->p_sysent->sv_setregs)(td, imgp,
857 		    (u_long)(uintptr_t)stack_base);
858 	else
859 		exec_setregs(td, imgp, (u_long)(uintptr_t)stack_base);
860 
861 	vfs_mark_atime(imgp->vp, td->td_ucred);
862 
863 	SDT_PROBE1(proc, , , exec__success, args->fname);
864 
865 	VOP_UNLOCK(imgp->vp, 0);
866 done1:
867 	/*
868 	 * Free any resources malloc'd earlier that we didn't use.
869 	 */
870 	if (euip != NULL)
871 		uifree(euip);
872 	if (newcred != NULL)
873 		crfree(oldcred);
874 
875 	/*
876 	 * Handle deferred decrement of ref counts.
877 	 */
878 	if (oldtextvp != NULL)
879 		vrele(oldtextvp);
880 #ifdef KTRACE
881 	if (tracevp != NULL)
882 		vrele(tracevp);
883 	if (tracecred != NULL)
884 		crfree(tracecred);
885 #endif
886 	vn_lock(imgp->vp, LK_SHARED | LK_RETRY);
887 	pargs_drop(oldargs);
888 	pargs_drop(newargs);
889 	if (oldsigacts != NULL)
890 		sigacts_free(oldsigacts);
891 
892 exec_fail_dealloc:
893 
894 	/*
895 	 * free various allocated resources
896 	 */
897 	if (imgp->firstpage != NULL)
898 		exec_unmap_first_page(imgp);
899 
900 	if (imgp->vp != NULL) {
901 		if (args->fname)
902 			NDFREE(&nd, NDF_ONLY_PNBUF);
903 		if (imgp->opened)
904 			VOP_CLOSE(imgp->vp, FREAD, td->td_ucred, td);
905 		if (error != 0)
906 			vput(imgp->vp);
907 		else
908 			VOP_UNLOCK(imgp->vp, 0);
909 	}
910 
911 	if (imgp->object != NULL)
912 		vm_object_deallocate(imgp->object);
913 
914 	free(imgp->freepath, M_TEMP);
915 
916 	if (error == 0) {
917 		PROC_LOCK(p);
918 		td->td_dbgflags |= TDB_EXEC;
919 		PROC_UNLOCK(p);
920 
921 		/*
922 		 * Stop the process here if its stop event mask has
923 		 * the S_EXEC bit set.
924 		 */
925 		STOPEVENT(p, S_EXEC, 0);
926 		goto done2;
927 	}
928 
929 exec_fail:
930 	/* we're done here, clear P_INEXEC */
931 	PROC_LOCK(p);
932 	p->p_flag &= ~P_INEXEC;
933 	PROC_UNLOCK(p);
934 
935 	SDT_PROBE1(proc, , , exec__failure, error);
936 
937 done2:
938 #ifdef MAC
939 	mac_execve_exit(imgp);
940 	mac_execve_interpreter_exit(interpvplabel);
941 #endif
942 	exec_free_args(args);
943 
944 	if (error && imgp->vmspace_destroyed) {
945 		/* sorry, no more process anymore. exit gracefully */
946 		exit1(td, 0, SIGABRT);
947 		/* NOT REACHED */
948 	}
949 
950 #ifdef KTRACE
951 	if (error == 0)
952 		ktrprocctor(p);
953 #endif
954 
955 	return (error);
956 }
957 
958 int
exec_map_first_page(imgp)959 exec_map_first_page(imgp)
960 	struct image_params *imgp;
961 {
962 	int rv, i, after, initial_pagein;
963 	vm_page_t ma[VM_INITIAL_PAGEIN];
964 	vm_object_t object;
965 
966 	if (imgp->firstpage != NULL)
967 		exec_unmap_first_page(imgp);
968 
969 	object = imgp->vp->v_object;
970 	if (object == NULL)
971 		return (EACCES);
972 	VM_OBJECT_WLOCK(object);
973 #if VM_NRESERVLEVEL > 0
974 	vm_object_color(object, 0);
975 #endif
976 	ma[0] = vm_page_grab(object, 0, VM_ALLOC_NORMAL);
977 	if (ma[0]->valid != VM_PAGE_BITS_ALL) {
978 		if (!vm_pager_has_page(object, 0, NULL, &after)) {
979 			vm_page_lock(ma[0]);
980 			vm_page_free(ma[0]);
981 			vm_page_unlock(ma[0]);
982 			vm_page_xunbusy(ma[0]);
983 			VM_OBJECT_WUNLOCK(object);
984 			return (EIO);
985 		}
986 		initial_pagein = min(after, VM_INITIAL_PAGEIN);
987 		KASSERT(initial_pagein <= object->size,
988 		    ("%s: initial_pagein %d object->size %ju",
989 		    __func__, initial_pagein, (uintmax_t )object->size));
990 		for (i = 1; i < initial_pagein; i++) {
991 			if ((ma[i] = vm_page_next(ma[i - 1])) != NULL) {
992 				if (ma[i]->valid)
993 					break;
994 				if (vm_page_tryxbusy(ma[i]))
995 					break;
996 			} else {
997 				ma[i] = vm_page_alloc(object, i, VM_ALLOC_NORMAL);
998 				if (ma[i] == NULL)
999 					break;
1000 			}
1001 		}
1002 		initial_pagein = i;
1003 		rv = vm_pager_get_pages(object, ma, initial_pagein, NULL, NULL);
1004 		if (rv != VM_PAGER_OK) {
1005 			for (i = 0; i < initial_pagein; i++) {
1006 				vm_page_lock(ma[i]);
1007 				vm_page_free(ma[i]);
1008 				vm_page_unlock(ma[i]);
1009 				vm_page_xunbusy(ma[i]);
1010 			}
1011 			VM_OBJECT_WUNLOCK(object);
1012 			return (EIO);
1013 		}
1014 		for (i = 1; i < initial_pagein; i++)
1015 			vm_page_readahead_finish(ma[i]);
1016 	}
1017 	vm_page_xunbusy(ma[0]);
1018 	vm_page_lock(ma[0]);
1019 	vm_page_hold(ma[0]);
1020 	vm_page_activate(ma[0]);
1021 	vm_page_unlock(ma[0]);
1022 	VM_OBJECT_WUNLOCK(object);
1023 
1024 	imgp->firstpage = sf_buf_alloc(ma[0], 0);
1025 	imgp->image_header = (char *)sf_buf_kva(imgp->firstpage);
1026 
1027 	return (0);
1028 }
1029 
1030 void
exec_unmap_first_page(imgp)1031 exec_unmap_first_page(imgp)
1032 	struct image_params *imgp;
1033 {
1034 	vm_page_t m;
1035 
1036 	if (imgp->firstpage != NULL) {
1037 		m = sf_buf_page(imgp->firstpage);
1038 		sf_buf_free(imgp->firstpage);
1039 		imgp->firstpage = NULL;
1040 		vm_page_lock(m);
1041 		vm_page_unhold(m);
1042 		vm_page_unlock(m);
1043 	}
1044 }
1045 
1046 /*
1047  * Destroy old address space, and allocate a new stack
1048  *	The new stack is only SGROWSIZ large because it is grown
1049  *	automatically in trap.c.
1050  */
1051 int
exec_new_vmspace(imgp,sv)1052 exec_new_vmspace(imgp, sv)
1053 	struct image_params *imgp;
1054 	struct sysentvec *sv;
1055 {
1056 	int error;
1057 	struct proc *p = imgp->proc;
1058 	struct vmspace *vmspace = p->p_vmspace;
1059 	vm_object_t obj;
1060 	struct rlimit rlim_stack;
1061 	vm_offset_t sv_minuser, stack_addr;
1062 	vm_map_t map;
1063 	u_long ssiz;
1064 
1065 	imgp->vmspace_destroyed = 1;
1066 	imgp->sysent = sv;
1067 
1068 	/* May be called with Giant held */
1069 	EVENTHANDLER_INVOKE(process_exec, p, imgp);
1070 
1071 	/*
1072 	 * Blow away entire process VM, if address space not shared,
1073 	 * otherwise, create a new VM space so that other threads are
1074 	 * not disrupted
1075 	 */
1076 	map = &vmspace->vm_map;
1077 	if (map_at_zero)
1078 		sv_minuser = sv->sv_minuser;
1079 	else
1080 		sv_minuser = MAX(sv->sv_minuser, PAGE_SIZE);
1081 	if (vmspace->vm_refcnt == 1 && vm_map_min(map) == sv_minuser &&
1082 	    vm_map_max(map) == sv->sv_maxuser) {
1083 		shmexit(vmspace);
1084 		pmap_remove_pages(vmspace_pmap(vmspace));
1085 		vm_map_remove(map, vm_map_min(map), vm_map_max(map));
1086 	} else {
1087 		error = vmspace_exec(p, sv_minuser, sv->sv_maxuser);
1088 		if (error)
1089 			return (error);
1090 		vmspace = p->p_vmspace;
1091 		map = &vmspace->vm_map;
1092 	}
1093 
1094 	/* Map a shared page */
1095 	obj = sv->sv_shared_page_obj;
1096 	if (obj != NULL) {
1097 		vm_object_reference(obj);
1098 		error = vm_map_fixed(map, obj, 0,
1099 		    sv->sv_shared_page_base, sv->sv_shared_page_len,
1100 		    VM_PROT_READ | VM_PROT_EXECUTE,
1101 		    VM_PROT_READ | VM_PROT_EXECUTE,
1102 		    MAP_INHERIT_SHARE | MAP_ACC_NO_CHARGE);
1103 		if (error) {
1104 			vm_object_deallocate(obj);
1105 			return (error);
1106 		}
1107 	}
1108 
1109 	/* Allocate a new stack */
1110 	if (imgp->stack_sz != 0) {
1111 		ssiz = trunc_page(imgp->stack_sz);
1112 		PROC_LOCK(p);
1113 		lim_rlimit_proc(p, RLIMIT_STACK, &rlim_stack);
1114 		PROC_UNLOCK(p);
1115 		if (ssiz > rlim_stack.rlim_max)
1116 			ssiz = rlim_stack.rlim_max;
1117 		if (ssiz > rlim_stack.rlim_cur) {
1118 			rlim_stack.rlim_cur = ssiz;
1119 			kern_setrlimit(curthread, RLIMIT_STACK, &rlim_stack);
1120 		}
1121 	} else if (sv->sv_maxssiz != NULL) {
1122 		ssiz = *sv->sv_maxssiz;
1123 	} else {
1124 		ssiz = maxssiz;
1125 	}
1126 	stack_addr = sv->sv_usrstack - ssiz;
1127 	error = vm_map_stack(map, stack_addr, (vm_size_t)ssiz,
1128 	    obj != NULL && imgp->stack_prot != 0 ? imgp->stack_prot :
1129 		sv->sv_stackprot,
1130 	    VM_PROT_ALL, MAP_STACK_GROWS_DOWN);
1131 	if (error)
1132 		return (error);
1133 
1134 	/*
1135 	 * vm_ssize and vm_maxsaddr are somewhat antiquated concepts, but they
1136 	 * are still used to enforce the stack rlimit on the process stack.
1137 	 */
1138 	vmspace->vm_ssize = sgrowsiz >> PAGE_SHIFT;
1139 	vmspace->vm_maxsaddr = (char *)stack_addr;
1140 
1141 	return (0);
1142 }
1143 
1144 /*
1145  * Copy out argument and environment strings from the old process address
1146  * space into the temporary string buffer.
1147  */
1148 int
exec_copyin_args(struct image_args * args,char * fname,enum uio_seg segflg,char ** argv,char ** envv)1149 exec_copyin_args(struct image_args *args, char *fname,
1150     enum uio_seg segflg, char **argv, char **envv)
1151 {
1152 	u_long argp, envp;
1153 	int error;
1154 	size_t length;
1155 
1156 	bzero(args, sizeof(*args));
1157 	if (argv == NULL)
1158 		return (EFAULT);
1159 
1160 	/*
1161 	 * Allocate demand-paged memory for the file name, argument, and
1162 	 * environment strings.
1163 	 */
1164 	error = exec_alloc_args(args);
1165 	if (error != 0)
1166 		return (error);
1167 
1168 	/*
1169 	 * Copy the file name.
1170 	 */
1171 	if (fname != NULL) {
1172 		args->fname = args->buf;
1173 		error = (segflg == UIO_SYSSPACE) ?
1174 		    copystr(fname, args->fname, PATH_MAX, &length) :
1175 		    copyinstr(fname, args->fname, PATH_MAX, &length);
1176 		if (error != 0)
1177 			goto err_exit;
1178 	} else
1179 		length = 0;
1180 
1181 	args->begin_argv = args->buf + length;
1182 	args->endp = args->begin_argv;
1183 	args->stringspace = ARG_MAX;
1184 
1185 	/*
1186 	 * extract arguments first
1187 	 */
1188 	for (;;) {
1189 		error = fueword(argv++, &argp);
1190 		if (error == -1) {
1191 			error = EFAULT;
1192 			goto err_exit;
1193 		}
1194 		if (argp == 0)
1195 			break;
1196 		error = copyinstr((void *)(uintptr_t)argp, args->endp,
1197 		    args->stringspace, &length);
1198 		if (error != 0) {
1199 			if (error == ENAMETOOLONG)
1200 				error = E2BIG;
1201 			goto err_exit;
1202 		}
1203 		args->stringspace -= length;
1204 		args->endp += length;
1205 		args->argc++;
1206 	}
1207 
1208 	args->begin_envv = args->endp;
1209 
1210 	/*
1211 	 * extract environment strings
1212 	 */
1213 	if (envv) {
1214 		for (;;) {
1215 			error = fueword(envv++, &envp);
1216 			if (error == -1) {
1217 				error = EFAULT;
1218 				goto err_exit;
1219 			}
1220 			if (envp == 0)
1221 				break;
1222 			error = copyinstr((void *)(uintptr_t)envp,
1223 			    args->endp, args->stringspace, &length);
1224 			if (error != 0) {
1225 				if (error == ENAMETOOLONG)
1226 					error = E2BIG;
1227 				goto err_exit;
1228 			}
1229 			args->stringspace -= length;
1230 			args->endp += length;
1231 			args->envc++;
1232 		}
1233 	}
1234 
1235 	return (0);
1236 
1237 err_exit:
1238 	exec_free_args(args);
1239 	return (error);
1240 }
1241 
1242 int
exec_copyin_data_fds(struct thread * td,struct image_args * args,const void * data,size_t datalen,const int * fds,size_t fdslen)1243 exec_copyin_data_fds(struct thread *td, struct image_args *args,
1244     const void *data, size_t datalen, const int *fds, size_t fdslen)
1245 {
1246 	struct filedesc *ofdp;
1247 	const char *p;
1248 	int *kfds;
1249 	int error;
1250 
1251 	memset(args, '\0', sizeof(*args));
1252 	ofdp = td->td_proc->p_fd;
1253 	if (datalen >= ARG_MAX || fdslen > ofdp->fd_lastfile + 1)
1254 		return (E2BIG);
1255 	error = exec_alloc_args(args);
1256 	if (error != 0)
1257 		return (error);
1258 
1259 	args->begin_argv = args->buf;
1260 	args->stringspace = ARG_MAX;
1261 
1262 	if (datalen > 0) {
1263 		/*
1264 		 * Argument buffer has been provided. Copy it into the
1265 		 * kernel as a single string and add a terminating null
1266 		 * byte.
1267 		 */
1268 		error = copyin(data, args->begin_argv, datalen);
1269 		if (error != 0)
1270 			goto err_exit;
1271 		args->begin_argv[datalen] = '\0';
1272 		args->endp = args->begin_argv + datalen + 1;
1273 		args->stringspace -= datalen + 1;
1274 
1275 		/*
1276 		 * Traditional argument counting. Count the number of
1277 		 * null bytes.
1278 		 */
1279 		for (p = args->begin_argv; p < args->endp; ++p)
1280 			if (*p == '\0')
1281 				++args->argc;
1282 	} else {
1283 		/* No argument buffer provided. */
1284 		args->endp = args->begin_argv;
1285 	}
1286 	/* There are no environment variables. */
1287 	args->begin_envv = args->endp;
1288 
1289 	/* Create new file descriptor table. */
1290 	kfds = malloc(fdslen * sizeof(int), M_TEMP, M_WAITOK);
1291 	error = copyin(fds, kfds, fdslen * sizeof(int));
1292 	if (error != 0) {
1293 		free(kfds, M_TEMP);
1294 		goto err_exit;
1295 	}
1296 	error = fdcopy_remapped(ofdp, kfds, fdslen, &args->fdp);
1297 	free(kfds, M_TEMP);
1298 	if (error != 0)
1299 		goto err_exit;
1300 
1301 	return (0);
1302 err_exit:
1303 	exec_free_args(args);
1304 	return (error);
1305 }
1306 
1307 /*
1308  * Allocate temporary demand-paged, zero-filled memory for the file name,
1309  * argument, and environment strings.  Returns zero if the allocation succeeds
1310  * and ENOMEM otherwise.
1311  */
1312 int
exec_alloc_args(struct image_args * args)1313 exec_alloc_args(struct image_args *args)
1314 {
1315 
1316 	args->buf = (char *)kmap_alloc_wait(exec_map, PATH_MAX + ARG_MAX);
1317 	return (args->buf != NULL ? 0 : ENOMEM);
1318 }
1319 
1320 void
exec_free_args(struct image_args * args)1321 exec_free_args(struct image_args *args)
1322 {
1323 
1324 	if (args->buf != NULL) {
1325 		kmap_free_wakeup(exec_map, (vm_offset_t)args->buf,
1326 		    PATH_MAX + ARG_MAX);
1327 		args->buf = NULL;
1328 	}
1329 	if (args->fname_buf != NULL) {
1330 		free(args->fname_buf, M_TEMP);
1331 		args->fname_buf = NULL;
1332 	}
1333 	if (args->fdp != NULL)
1334 		fdescfree_remapped(args->fdp);
1335 }
1336 
1337 /*
1338  * Copy strings out to the new process address space, constructing new arg
1339  * and env vector tables. Return a pointer to the base so that it can be used
1340  * as the initial stack pointer.
1341  */
1342 register_t *
exec_copyout_strings(imgp)1343 exec_copyout_strings(imgp)
1344 	struct image_params *imgp;
1345 {
1346 	int argc, envc;
1347 	char **vectp;
1348 	char *stringp;
1349 	uintptr_t destp;
1350 	register_t *stack_base;
1351 	struct ps_strings *arginfo;
1352 	struct proc *p;
1353 	size_t execpath_len;
1354 	int szsigcode, szps;
1355 	char canary[sizeof(long) * 8];
1356 
1357 	szps = sizeof(pagesizes[0]) * MAXPAGESIZES;
1358 	/*
1359 	 * Calculate string base and vector table pointers.
1360 	 * Also deal with signal trampoline code for this exec type.
1361 	 */
1362 	if (imgp->execpath != NULL && imgp->auxargs != NULL)
1363 		execpath_len = strlen(imgp->execpath) + 1;
1364 	else
1365 		execpath_len = 0;
1366 	p = imgp->proc;
1367 	szsigcode = 0;
1368 	arginfo = (struct ps_strings *)p->p_sysent->sv_psstrings;
1369 	if (p->p_sysent->sv_sigcode_base == 0) {
1370 		if (p->p_sysent->sv_szsigcode != NULL)
1371 			szsigcode = *(p->p_sysent->sv_szsigcode);
1372 	}
1373 	destp =	(uintptr_t)arginfo;
1374 
1375 	/*
1376 	 * install sigcode
1377 	 */
1378 	if (szsigcode != 0) {
1379 		destp -= szsigcode;
1380 		destp = rounddown2(destp, sizeof(void *));
1381 		copyout(p->p_sysent->sv_sigcode, (void *)destp, szsigcode);
1382 	}
1383 
1384 	/*
1385 	 * Copy the image path for the rtld.
1386 	 */
1387 	if (execpath_len != 0) {
1388 		destp -= execpath_len;
1389 		imgp->execpathp = destp;
1390 		copyout(imgp->execpath, (void *)destp, execpath_len);
1391 	}
1392 
1393 	/*
1394 	 * Prepare the canary for SSP.
1395 	 */
1396 	arc4rand(canary, sizeof(canary), 0);
1397 	destp -= sizeof(canary);
1398 	imgp->canary = destp;
1399 	copyout(canary, (void *)destp, sizeof(canary));
1400 	imgp->canarylen = sizeof(canary);
1401 
1402 	/*
1403 	 * Prepare the pagesizes array.
1404 	 */
1405 	destp -= szps;
1406 	destp = rounddown2(destp, sizeof(void *));
1407 	imgp->pagesizes = destp;
1408 	copyout(pagesizes, (void *)destp, szps);
1409 	imgp->pagesizeslen = szps;
1410 
1411 	destp -= ARG_MAX - imgp->args->stringspace;
1412 	destp = rounddown2(destp, sizeof(void *));
1413 
1414 	/*
1415 	 * If we have a valid auxargs ptr, prepare some room
1416 	 * on the stack.
1417 	 */
1418 	if (imgp->auxargs) {
1419 		/*
1420 		 * 'AT_COUNT*2' is size for the ELF Auxargs data. This is for
1421 		 * lower compatibility.
1422 		 */
1423 		imgp->auxarg_size = (imgp->auxarg_size) ? imgp->auxarg_size :
1424 		    (AT_COUNT * 2);
1425 		/*
1426 		 * The '+ 2' is for the null pointers at the end of each of
1427 		 * the arg and env vector sets,and imgp->auxarg_size is room
1428 		 * for argument of Runtime loader.
1429 		 */
1430 		vectp = (char **)(destp - (imgp->args->argc +
1431 		    imgp->args->envc + 2 + imgp->auxarg_size)
1432 		    * sizeof(char *));
1433 	} else {
1434 		/*
1435 		 * The '+ 2' is for the null pointers at the end of each of
1436 		 * the arg and env vector sets
1437 		 */
1438 		vectp = (char **)(destp - (imgp->args->argc + imgp->args->envc
1439 		    + 2) * sizeof(char *));
1440 	}
1441 
1442 	/*
1443 	 * vectp also becomes our initial stack base
1444 	 */
1445 	stack_base = (register_t *)vectp;
1446 
1447 	stringp = imgp->args->begin_argv;
1448 	argc = imgp->args->argc;
1449 	envc = imgp->args->envc;
1450 
1451 	/*
1452 	 * Copy out strings - arguments and environment.
1453 	 */
1454 	copyout(stringp, (void *)destp, ARG_MAX - imgp->args->stringspace);
1455 
1456 	/*
1457 	 * Fill in "ps_strings" struct for ps, w, etc.
1458 	 */
1459 	suword(&arginfo->ps_argvstr, (long)(intptr_t)vectp);
1460 	suword32(&arginfo->ps_nargvstr, argc);
1461 
1462 	/*
1463 	 * Fill in argument portion of vector table.
1464 	 */
1465 	for (; argc > 0; --argc) {
1466 		suword(vectp++, (long)(intptr_t)destp);
1467 		while (*stringp++ != 0)
1468 			destp++;
1469 		destp++;
1470 	}
1471 
1472 	/* a null vector table pointer separates the argp's from the envp's */
1473 	suword(vectp++, 0);
1474 
1475 	suword(&arginfo->ps_envstr, (long)(intptr_t)vectp);
1476 	suword32(&arginfo->ps_nenvstr, envc);
1477 
1478 	/*
1479 	 * Fill in environment portion of vector table.
1480 	 */
1481 	for (; envc > 0; --envc) {
1482 		suword(vectp++, (long)(intptr_t)destp);
1483 		while (*stringp++ != 0)
1484 			destp++;
1485 		destp++;
1486 	}
1487 
1488 	/* end of vector table is a null pointer */
1489 	suword(vectp, 0);
1490 
1491 	return (stack_base);
1492 }
1493 
1494 /*
1495  * Check permissions of file to execute.
1496  *	Called with imgp->vp locked.
1497  *	Return 0 for success or error code on failure.
1498  */
1499 int
exec_check_permissions(imgp)1500 exec_check_permissions(imgp)
1501 	struct image_params *imgp;
1502 {
1503 	struct vnode *vp = imgp->vp;
1504 	struct vattr *attr = imgp->attr;
1505 	struct thread *td;
1506 	int error, writecount;
1507 
1508 	td = curthread;
1509 
1510 	/* Get file attributes */
1511 	error = VOP_GETATTR(vp, attr, td->td_ucred);
1512 	if (error)
1513 		return (error);
1514 
1515 #ifdef MAC
1516 	error = mac_vnode_check_exec(td->td_ucred, imgp->vp, imgp);
1517 	if (error)
1518 		return (error);
1519 #endif
1520 
1521 	/*
1522 	 * 1) Check if file execution is disabled for the filesystem that
1523 	 *    this file resides on.
1524 	 * 2) Ensure that at least one execute bit is on. Otherwise, a
1525 	 *    privileged user will always succeed, and we don't want this
1526 	 *    to happen unless the file really is executable.
1527 	 * 3) Ensure that the file is a regular file.
1528 	 */
1529 	if ((vp->v_mount->mnt_flag & MNT_NOEXEC) ||
1530 	    (attr->va_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) == 0 ||
1531 	    (attr->va_type != VREG))
1532 		return (EACCES);
1533 
1534 	/*
1535 	 * Zero length files can't be exec'd
1536 	 */
1537 	if (attr->va_size == 0)
1538 		return (ENOEXEC);
1539 
1540 	/*
1541 	 *  Check for execute permission to file based on current credentials.
1542 	 */
1543 	error = VOP_ACCESS(vp, VEXEC, td->td_ucred, td);
1544 	if (error)
1545 		return (error);
1546 
1547 	/*
1548 	 * Check number of open-for-writes on the file and deny execution
1549 	 * if there are any.
1550 	 */
1551 	error = VOP_GET_WRITECOUNT(vp, &writecount);
1552 	if (error != 0)
1553 		return (error);
1554 	if (writecount != 0)
1555 		return (ETXTBSY);
1556 
1557 	/*
1558 	 * Call filesystem specific open routine (which does nothing in the
1559 	 * general case).
1560 	 */
1561 	error = VOP_OPEN(vp, FREAD, td->td_ucred, td, NULL);
1562 	if (error == 0)
1563 		imgp->opened = 1;
1564 	return (error);
1565 }
1566 
1567 /*
1568  * Exec handler registration
1569  */
1570 int
exec_register(execsw_arg)1571 exec_register(execsw_arg)
1572 	const struct execsw *execsw_arg;
1573 {
1574 	const struct execsw **es, **xs, **newexecsw;
1575 	int count = 2;	/* New slot and trailing NULL */
1576 
1577 	if (execsw)
1578 		for (es = execsw; *es; es++)
1579 			count++;
1580 	newexecsw = malloc(count * sizeof(*es), M_TEMP, M_WAITOK);
1581 	if (newexecsw == NULL)
1582 		return (ENOMEM);
1583 	xs = newexecsw;
1584 	if (execsw)
1585 		for (es = execsw; *es; es++)
1586 			*xs++ = *es;
1587 	*xs++ = execsw_arg;
1588 	*xs = NULL;
1589 	if (execsw)
1590 		free(execsw, M_TEMP);
1591 	execsw = newexecsw;
1592 	return (0);
1593 }
1594 
1595 int
exec_unregister(execsw_arg)1596 exec_unregister(execsw_arg)
1597 	const struct execsw *execsw_arg;
1598 {
1599 	const struct execsw **es, **xs, **newexecsw;
1600 	int count = 1;
1601 
1602 	if (execsw == NULL)
1603 		panic("unregister with no handlers left?\n");
1604 
1605 	for (es = execsw; *es; es++) {
1606 		if (*es == execsw_arg)
1607 			break;
1608 	}
1609 	if (*es == NULL)
1610 		return (ENOENT);
1611 	for (es = execsw; *es; es++)
1612 		if (*es != execsw_arg)
1613 			count++;
1614 	newexecsw = malloc(count * sizeof(*es), M_TEMP, M_WAITOK);
1615 	if (newexecsw == NULL)
1616 		return (ENOMEM);
1617 	xs = newexecsw;
1618 	for (es = execsw; *es; es++)
1619 		if (*es != execsw_arg)
1620 			*xs++ = *es;
1621 	*xs = NULL;
1622 	if (execsw)
1623 		free(execsw, M_TEMP);
1624 	execsw = newexecsw;
1625 	return (0);
1626 }
1627