xref: /freebsd/sys/kern/kern_exec.c (revision 0de89efe5c443f213c7ea28773ef2dc6cf3af2ed)
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  *	$Id: kern_exec.c,v 1.65 1997/09/02 20:05:38 bde Exp $
27  */
28 
29 #include <sys/param.h>
30 #include <sys/systm.h>
31 #include <sys/sysproto.h>
32 #include <sys/signalvar.h>
33 #include <sys/kernel.h>
34 #include <sys/mount.h>
35 #include <sys/filedesc.h>
36 #include <sys/fcntl.h>
37 #include <sys/acct.h>
38 #include <sys/exec.h>
39 #include <sys/imgact.h>
40 #include <sys/imgact_elf.h>
41 #include <sys/wait.h>
42 #include <sys/proc.h>
43 #include <sys/malloc.h>
44 #include <sys/namei.h>
45 #include <sys/sysent.h>
46 #include <sys/shm.h>
47 #include <sys/sysctl.h>
48 #include <sys/vnode.h>
49 #include <sys/buf.h>
50 
51 #include <vm/vm.h>
52 #include <vm/vm_param.h>
53 #include <vm/vm_prot.h>
54 #include <sys/lock.h>
55 #include <vm/pmap.h>
56 #include <vm/vm_map.h>
57 #include <vm/vm_kern.h>
58 #include <vm/vm_extern.h>
59 #include <vm/vm_object.h>
60 
61 #include <machine/reg.h>
62 
63 static int *exec_copyout_strings __P((struct image_params *));
64 
65 static int exec_check_permissions(struct image_params *);
66 
67 /*
68  * XXX trouble here if sizeof(caddr_t) != sizeof(int), other parts
69  * of the sysctl code also assumes this, and sizeof(int) == sizeof(long).
70  */
71 static struct ps_strings *ps_strings = PS_STRINGS;
72 SYSCTL_INT(_kern, KERN_PS_STRINGS, ps_strings, 0, &ps_strings, 0, "");
73 
74 static caddr_t usrstack = (caddr_t)USRSTACK;
75 SYSCTL_INT(_kern, KERN_USRSTACK, usrstack, 0, &usrstack, 0, "");
76 
77 /*
78  * execsw_set is constructed for us by the linker.  Each of the items
79  * is a pointer to a `const struct execsw', hence the double pointer here.
80  */
81 static const struct execsw **execsw =
82 	(const struct execsw **)&execsw_set.ls_items[0];
83 
84 #ifndef _SYS_SYSPROTO_H_
85 struct execve_args {
86         char    *fname;
87         char    **argv;
88         char    **envv;
89 };
90 #endif
91 
92 /*
93  * execve() system call.
94  */
95 int
96 execve(p, uap, retval)
97 	struct proc *p;
98 	register struct execve_args *uap;
99 	int *retval;
100 {
101 	struct nameidata nd, *ndp;
102 	int *stack_base;
103 	int error, len, i;
104 	struct image_params image_params, *imgp;
105 	struct vattr attr;
106 	struct buf *bp = NULL;
107 
108 	imgp = &image_params;
109 
110 	/*
111 	 * Initialize part of the common data
112 	 */
113 	imgp->proc = p;
114 	imgp->uap = uap;
115 	imgp->attr = &attr;
116 	imgp->image_header = NULL;
117 	imgp->argc = imgp->envc = 0;
118 	imgp->argv0 = NULL;
119 	imgp->entry_addr = 0;
120 	imgp->vmspace_destroyed = 0;
121 	imgp->interpreted = 0;
122 	imgp->interpreter_name[0] = '\0';
123 	imgp->auxargs = NULL;
124 
125 	/*
126 	 * Allocate temporary demand zeroed space for argument and
127 	 *	environment strings
128 	 */
129 	imgp->stringbase = (char *)kmem_alloc_wait(exec_map, ARG_MAX);
130 	if (imgp->stringbase == NULL) {
131 		error = ENOMEM;
132 		goto exec_fail;
133 	}
134 	imgp->stringp = imgp->stringbase;
135 	imgp->stringspace = ARG_MAX;
136 
137 	/*
138 	 * Translate the file name. namei() returns a vnode pointer
139 	 *	in ni_vp amoung other things.
140 	 */
141 	ndp = &nd;
142 	NDINIT(ndp, LOOKUP, LOCKLEAF | FOLLOW | SAVENAME,
143 	    UIO_USERSPACE, uap->fname, p);
144 
145 interpret:
146 
147 	error = namei(ndp);
148 	if (error) {
149 		kmem_free_wakeup(exec_map, (vm_offset_t)imgp->stringbase, ARG_MAX);
150 		goto exec_fail;
151 	}
152 
153 	imgp->vp = ndp->ni_vp;
154 
155 	/*
156 	 * Check file permissions (also 'opens' file)
157 	 */
158 	error = exec_check_permissions(imgp);
159 	if (error) {
160 		VOP_UNLOCK(imgp->vp, 0, p);
161 		goto exec_fail_dealloc;
162 	}
163 
164 	/*
165 	 * Get the image header, which we define here as meaning the first
166 	 * page of the executable.
167 	 */
168 	if (imgp->vp->v_object && imgp->vp->v_mount &&
169 	    imgp->vp->v_mount->mnt_stat.f_iosize >= PAGE_SIZE &&
170 	    imgp->vp->v_object->un_pager.vnp.vnp_size >=
171 	    imgp->vp->v_mount->mnt_stat.f_iosize) {
172 		/*
173 		 * Get a buffer with (at least) the first page.
174 		 */
175 		error = bread(imgp->vp, 0, imgp->vp->v_mount->mnt_stat.f_iosize,
176 		     p->p_ucred, &bp);
177 		imgp->image_header = bp->b_data;
178 	} else {
179 		int resid;
180 
181 		/*
182 		 * The filesystem block size is too small, so do this the hard
183 		 * way. Malloc some space and read PAGE_SIZE worth of the image
184 		 * header into it.
185 		 */
186 		imgp->image_header = malloc(PAGE_SIZE, M_TEMP, M_WAITOK);
187 		error = vn_rdwr(UIO_READ, imgp->vp, (void *)imgp->image_header, PAGE_SIZE, 0,
188 		    UIO_SYSSPACE, IO_NODELOCKED, p->p_ucred, &resid, p);
189 		/*
190 		 * Clear out any remaining junk.
191 		 */
192 		if (!error && resid)
193 			bzero((char *)imgp->image_header + PAGE_SIZE - resid, resid);
194 	}
195 	VOP_UNLOCK(imgp->vp, 0, p);
196 	if (error)
197 		goto exec_fail_dealloc;
198 
199 	/*
200 	 * Loop through list of image activators, calling each one.
201 	 *	If there is no match, the activator returns -1. If there
202 	 *	is a match, but there was an error during the activation,
203 	 *	the error is returned. Otherwise 0 means success. If the
204 	 *	image is interpreted, loop back up and try activating
205 	 *	the interpreter.
206 	 */
207 	for (i = 0; execsw[i]; ++i) {
208 		if (execsw[i]->ex_imgact)
209 			error = (*execsw[i]->ex_imgact)(imgp);
210 		else
211 			continue;
212 		if (error == -1)
213 			continue;
214 		if (error)
215 			goto exec_fail_dealloc;
216 		if (imgp->interpreted) {
217 			/* free old bp/image_header */
218 			if (bp != NULL) {
219 				brelse(bp);
220 				bp = NULL;
221 			} else {
222 				free((void *)imgp->image_header, M_TEMP);
223 				imgp->image_header = NULL;
224 			}
225 			/* free old vnode and name buffer */
226 			vrele(ndp->ni_vp);
227 			zfree(namei_zone, ndp->ni_cnd.cn_pnbuf);
228 			/* set new name to that of the interpreter */
229 			NDINIT(ndp, LOOKUP, LOCKLEAF | FOLLOW | SAVENAME,
230 			    UIO_SYSSPACE, imgp->interpreter_name, p);
231 			goto interpret;
232 		}
233 		break;
234 	}
235 	/* If we made it through all the activators and none matched, exit. */
236 	if (error == -1) {
237 		error = ENOEXEC;
238 		goto exec_fail_dealloc;
239 	}
240 
241 	/*
242 	 * Copy out strings (args and env) and initialize stack base
243 	 */
244 	stack_base = exec_copyout_strings(imgp);
245 	p->p_vmspace->vm_minsaddr = (char *)stack_base;
246 
247 	/*
248 	 * If custom stack fixup routine present for this process
249 	 * let it do the stack setup.
250 	 * Else stuff argument count as first item on stack
251 	 */
252 	if (p->p_sysent->sv_fixup)
253 		(*p->p_sysent->sv_fixup)(&stack_base, imgp);
254 	else
255 		suword(--stack_base, imgp->argc);
256 
257 	/*
258 	 * For security and other reasons, the file descriptor table cannot
259 	 * be shared after an exec.
260 	 */
261 	if (p->p_fd->fd_refcnt > 1) {
262 		struct filedesc *tmp;
263 
264 		tmp = fdcopy(p);
265 		fdfree(p);
266 		p->p_fd = tmp;
267 	}
268 
269 	/* close files on exec */
270 	fdcloseexec(p);
271 
272 	/* reset caught signals */
273 	execsigs(p);
274 
275 	/* name this process - nameiexec(p, ndp) */
276 	len = min(ndp->ni_cnd.cn_namelen,MAXCOMLEN);
277 	bcopy(ndp->ni_cnd.cn_nameptr, p->p_comm, len);
278 	p->p_comm[len] = 0;
279 
280 	/*
281 	 * mark as execed, wakeup the process that vforked (if any) and tell
282 	 * it that it now has it's own resources back
283 	 */
284 	p->p_flag |= P_EXEC;
285 	if (p->p_pptr && (p->p_flag & P_PPWAIT)) {
286 		p->p_flag &= ~P_PPWAIT;
287 		wakeup((caddr_t)p->p_pptr);
288 	}
289 
290 	/*
291 	 * Implement image setuid/setgid.
292 	 *
293 	 * Don't honor setuid/setgid if the filesystem prohibits it or if
294 	 * the process is being traced.
295 	 */
296 	if ((attr.va_mode & (VSUID | VSGID)) &&
297 	    (imgp->vp->v_mount->mnt_flag & MNT_NOSUID) == 0 &&
298 	    (p->p_flag & P_TRACED) == 0) {
299 		/*
300 		 * Turn off syscall tracing for set-id programs, except for
301 		 * root.
302 		 */
303 		if (p->p_tracep && suser(p->p_ucred, &p->p_acflag)) {
304 			p->p_traceflag = 0;
305 			vrele(p->p_tracep);
306 			p->p_tracep = NULL;
307 		}
308 		/*
309 		 * Set the new credentials.
310 		 */
311 		p->p_ucred = crcopy(p->p_ucred);
312 		if (attr.va_mode & VSUID)
313 			p->p_ucred->cr_uid = attr.va_uid;
314 		if (attr.va_mode & VSGID)
315 			p->p_ucred->cr_groups[0] = attr.va_gid;
316 		p->p_flag |= P_SUGID;
317 	} else {
318 	        if (p->p_ucred->cr_uid == p->p_cred->p_ruid &&
319 		    p->p_ucred->cr_gid == p->p_cred->p_rgid)
320 			p->p_flag &= ~P_SUGID;
321 	}
322 
323 	/*
324 	 * Implement correct POSIX saved-id behavior.
325 	 */
326 	p->p_cred->p_svuid = p->p_ucred->cr_uid;
327 	p->p_cred->p_svgid = p->p_ucred->cr_gid;
328 
329 	/*
330 	 * Store the vp for use in procfs
331 	 */
332 	if (p->p_textvp)		/* release old reference */
333 		vrele(p->p_textvp);
334 	VREF(ndp->ni_vp);
335 	p->p_textvp = ndp->ni_vp;
336 
337 	/*
338 	 * If tracing the process, trap to debugger so breakpoints
339 	 * 	can be set before the program executes.
340 	 */
341 	if (p->p_flag & P_TRACED)
342 		psignal(p, SIGTRAP);
343 
344 	/* clear "fork but no exec" flag, as we _are_ execing */
345 	p->p_acflag &= ~AFORK;
346 
347 	/* Set entry address */
348 	setregs(p, imgp->entry_addr, (u_long)stack_base);
349 
350 	/*
351 	 * free various allocated resources
352 	 */
353 	kmem_free_wakeup(exec_map, (vm_offset_t)imgp->stringbase, ARG_MAX);
354 	if (bp != NULL)
355 		brelse(bp);
356 	else if (imgp->image_header != NULL)
357 		free((void *)imgp->image_header, M_TEMP);
358 	vrele(ndp->ni_vp);
359 	zfree(namei_zone, ndp->ni_cnd.cn_pnbuf);
360 
361 	return (0);
362 
363 exec_fail_dealloc:
364 	if (imgp->stringbase != NULL)
365 		kmem_free_wakeup(exec_map, (vm_offset_t)imgp->stringbase, ARG_MAX);
366 	if (bp != NULL)
367 		brelse(bp);
368 	else if (imgp->image_header != NULL)
369 		free((void *)imgp->image_header, M_TEMP);
370 	if (ndp->ni_vp) {
371 		vrele(ndp->ni_vp);
372 		zfree(namei_zone, ndp->ni_cnd.cn_pnbuf);
373 	}
374 
375 exec_fail:
376 	if (imgp->vmspace_destroyed) {
377 		/* sorry, no more process anymore. exit gracefully */
378 		exit1(p, W_EXITCODE(0, SIGABRT));
379 		/* NOT REACHED */
380 		return(0);
381 	} else {
382 		return(error);
383 	}
384 }
385 
386 /*
387  * Destroy old address space, and allocate a new stack
388  *	The new stack is only SGROWSIZ large because it is grown
389  *	automatically in trap.c.
390  */
391 int
392 exec_new_vmspace(imgp)
393 	struct image_params *imgp;
394 {
395 	int error;
396 	struct vmspace *vmspace = imgp->proc->p_vmspace;
397 	caddr_t	stack_addr = (caddr_t) (USRSTACK - SGROWSIZ);
398 	vm_map_t map = &vmspace->vm_map;
399 
400 	imgp->vmspace_destroyed = 1;
401 
402 	/*
403 	 * Blow away entire process VM, if address space not shared,
404 	 * otherwise, create a new VM space so that other threads are
405 	 * not disrupted
406 	 */
407 	if (vmspace->vm_refcnt == 1) {
408 		if (vmspace->vm_shm)
409 			shmexit(imgp->proc);
410 		pmap_remove_pages(&vmspace->vm_pmap, 0, USRSTACK);
411 		vm_map_remove(map, 0, USRSTACK);
412 	} else {
413 		vmspace_exec(imgp->proc);
414 		vmspace = imgp->proc->p_vmspace;
415 		map = &vmspace->vm_map;
416 	}
417 
418 	/* Allocate a new stack */
419 	error = vm_map_find(map, NULL, 0, (vm_offset_t *)&stack_addr,
420 	    SGROWSIZ, FALSE, VM_PROT_ALL, VM_PROT_ALL, 0);
421 	if (error)
422 		return(error);
423 
424 	vmspace->vm_ssize = SGROWSIZ >> PAGE_SHIFT;
425 
426 	/* Initialize maximum stack address */
427 	vmspace->vm_maxsaddr = (char *)USRSTACK - MAXSSIZ;
428 
429 	return(0);
430 }
431 
432 /*
433  * Copy out argument and environment strings from the old process
434  *	address space into the temporary string buffer.
435  */
436 int
437 exec_extract_strings(imgp)
438 	struct image_params *imgp;
439 {
440 	char	**argv, **envv;
441 	char	*argp, *envp;
442 	int	error, length;
443 
444 	/*
445 	 * extract arguments first
446 	 */
447 
448 	argv = imgp->uap->argv;
449 
450 	if (argv) {
451 		argp = (caddr_t) fuword(argv);
452 		if (argp == (caddr_t) -1)
453 			return (EFAULT);
454 		if (argp)
455 			argv++;
456 		if (imgp->argv0)
457 			argp = imgp->argv0;
458 		if (argp) {
459 			do {
460 				if (argp == (caddr_t) -1)
461 					return (EFAULT);
462 				if ((error = copyinstr(argp, imgp->stringp,
463 				    imgp->stringspace, &length))) {
464 					if (error == ENAMETOOLONG)
465 						return(E2BIG);
466 					return (error);
467 				}
468 				imgp->stringspace -= length;
469 				imgp->stringp += length;
470 				imgp->argc++;
471 			} while ((argp = (caddr_t) fuword(argv++)));
472 		}
473 	}
474 
475 	/*
476 	 * extract environment strings
477 	 */
478 
479 	envv = imgp->uap->envv;
480 
481 	if (envv) {
482 		while ((envp = (caddr_t) fuword(envv++))) {
483 			if (envp == (caddr_t) -1)
484 				return (EFAULT);
485 			if ((error = copyinstr(envp, imgp->stringp,
486 			    imgp->stringspace, &length))) {
487 				if (error == ENAMETOOLONG)
488 					return(E2BIG);
489 				return (error);
490 			}
491 			imgp->stringspace -= length;
492 			imgp->stringp += length;
493 			imgp->envc++;
494 		}
495 	}
496 
497 	return (0);
498 }
499 
500 /*
501  * Copy strings out to the new process address space, constructing
502  *	new arg and env vector tables. Return a pointer to the base
503  *	so that it can be used as the initial stack pointer.
504  */
505 int *
506 exec_copyout_strings(imgp)
507 	struct image_params *imgp;
508 {
509 	int argc, envc;
510 	char **vectp;
511 	char *stringp, *destp;
512 	int *stack_base;
513 	struct ps_strings *arginfo;
514 	int szsigcode;
515 
516 	/*
517 	 * Calculate string base and vector table pointers.
518 	 * Also deal with signal trampoline code for this exec type.
519 	 */
520 	arginfo = PS_STRINGS;
521 	szsigcode = *(imgp->proc->p_sysent->sv_szsigcode);
522 	destp =	(caddr_t)arginfo - szsigcode - SPARE_USRSPACE -
523 		roundup((ARG_MAX - imgp->stringspace), sizeof(char *));
524 
525 	/*
526 	 * install sigcode
527 	 */
528 	if (szsigcode)
529 		copyout(imgp->proc->p_sysent->sv_sigcode,
530 			((caddr_t)arginfo - szsigcode), szsigcode);
531 
532 	/*
533 	 * If we have a valid auxargs ptr, prepare some room
534 	 * on the stack.
535 	 */
536 	if (imgp->auxargs)
537 	/*
538 	 * The '+ 2' is for the null pointers at the end of each of the
539 	 * arg and env vector sets, and 'AT_COUNT*2' is room for the
540 	 * ELF Auxargs data.
541 	 */
542 		vectp = (char **)(destp - (imgp->argc + imgp->envc + 2 +
543 				  AT_COUNT*2) * sizeof(char*));
544 	else
545 	/*
546 	 * The '+ 2' is for the null pointers at the end of each of the
547 	 * arg and env vector sets
548 	 */
549 		vectp = (char **)
550 			(destp - (imgp->argc + imgp->envc + 2) * sizeof(char*));
551 
552 	/*
553 	 * vectp also becomes our initial stack base
554 	 */
555 	stack_base = (int *)vectp;
556 
557 	stringp = imgp->stringbase;
558 	argc = imgp->argc;
559 	envc = imgp->envc;
560 
561 	/*
562 	 * Copy out strings - arguments and environment.
563 	 */
564 	copyout(stringp, destp, ARG_MAX - imgp->stringspace);
565 
566 	/*
567 	 * Fill in "ps_strings" struct for ps, w, etc.
568 	 */
569 	suword(&arginfo->ps_argvstr, (int)vectp);
570 	suword(&arginfo->ps_nargvstr, argc);
571 
572 	/*
573 	 * Fill in argument portion of vector table.
574 	 */
575 	for (; argc > 0; --argc) {
576 		suword(vectp++, (int)destp);
577 		while (*stringp++ != 0)
578 			destp++;
579 		destp++;
580 	}
581 
582 	/* a null vector table pointer seperates the argp's from the envp's */
583 	suword(vectp++, 0);
584 
585 	suword(&arginfo->ps_envstr, (int)vectp);
586 	suword(&arginfo->ps_nenvstr, envc);
587 
588 	/*
589 	 * Fill in environment portion of vector table.
590 	 */
591 	for (; envc > 0; --envc) {
592 		suword(vectp++, (int)destp);
593 		while (*stringp++ != 0)
594 			destp++;
595 		destp++;
596 	}
597 
598 	/* end of vector table is a null pointer */
599 	suword(vectp, 0);
600 
601 	return (stack_base);
602 }
603 
604 /*
605  * Check permissions of file to execute.
606  *	Return 0 for success or error code on failure.
607  */
608 static int
609 exec_check_permissions(imgp)
610 	struct image_params *imgp;
611 {
612 	struct proc *p = imgp->proc;
613 	struct vnode *vp = imgp->vp;
614 	struct vattr *attr = imgp->attr;
615 	int error;
616 
617 	/* Get file attributes */
618 	error = VOP_GETATTR(vp, attr, p->p_ucred, p);
619 	if (error)
620 		return (error);
621 
622 	/*
623 	 * 1) Check if file execution is disabled for the filesystem that this
624 	 *	file resides on.
625 	 * 2) Insure that at least one execute bit is on - otherwise root
626 	 *	will always succeed, and we don't want to happen unless the
627 	 *	file really is executable.
628 	 * 3) Insure that the file is a regular file.
629 	 */
630 	if ((vp->v_mount->mnt_flag & MNT_NOEXEC) ||
631 	    ((attr->va_mode & 0111) == 0) ||
632 	    (attr->va_type != VREG)) {
633 		return (EACCES);
634 	}
635 
636 	/*
637 	 * Zero length files can't be exec'd
638 	 */
639 	if (attr->va_size == 0)
640 		return (ENOEXEC);
641 
642 	/*
643 	 *  Check for execute permission to file based on current credentials.
644 	 */
645 	error = VOP_ACCESS(vp, VEXEC, p->p_ucred, p);
646 	if (error)
647 		return (error);
648 
649 	/*
650 	 * Check number of open-for-writes on the file and deny execution
651 	 * if there are any.
652 	 */
653 	if (vp->v_writecount)
654 		return (ETXTBSY);
655 
656 	/*
657 	 * Call filesystem specific open routine (which does nothing in the
658 	 * general case).
659 	 */
660 	error = VOP_OPEN(vp, FREAD, p->p_ucred, p);
661 	if (error)
662 		return (error);
663 
664 	return (0);
665 }
666