xref: /freebsd/sys/kern/kern_exec.c (revision ef5d438ed4bc17ad7ece3e40fe4d1f9baf3aadf7)
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  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *	This product includes software developed by David Greenman
16  * 4. The name of the developer may not be used to endorse or promote products
17  *    derived from this software without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  *
31  *	$Id: kern_exec.c,v 1.34 1996/01/20 21:36:30 bde Exp $
32  */
33 
34 #include <sys/param.h>
35 #include <sys/systm.h>
36 #include <sys/sysproto.h>
37 #include <sys/signalvar.h>
38 #include <sys/kernel.h>
39 #include <sys/mount.h>
40 #include <sys/filedesc.h>
41 #include <sys/fcntl.h>
42 #include <sys/acct.h>
43 #include <sys/exec.h>
44 #include <sys/imgact.h>
45 #include <sys/wait.h>
46 #include <sys/malloc.h>
47 #include <sys/sysent.h>
48 #include <sys/syslog.h>
49 #include <sys/shm.h>
50 #include <sys/sysctl.h>
51 
52 #include <vm/vm.h>
53 #include <vm/vm_param.h>
54 #include <vm/vm_prot.h>
55 #include <vm/lock.h>
56 #include <vm/pmap.h>
57 #include <vm/vm_map.h>
58 #include <vm/vm_kern.h>
59 #include <vm/vm_extern.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 caddr_t ps_strings = (caddr_t)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 
107 	imgp = &image_params;
108 
109 	/*
110 	 * Initialize part of the common data
111 	 */
112 	imgp->proc = p;
113 	imgp->uap = uap;
114 	imgp->attr = &attr;
115 	imgp->image_header = NULL;
116 	imgp->argc = imgp->envc = 0;
117 	imgp->entry_addr = 0;
118 	imgp->vmspace_destroyed = 0;
119 	imgp->interpreted = 0;
120 	imgp->interpreter_name[0] = '\0';
121 
122 	/*
123 	 * Allocate temporary demand zeroed space for argument and
124 	 *	environment strings
125 	 */
126 	imgp->stringbase = (char *)kmem_alloc_pageable(exec_map, ARG_MAX);
127 	if (imgp->stringbase == NULL) {
128 		error = ENOMEM;
129 		goto exec_fail;
130 	}
131 	imgp->stringp = imgp->stringbase;
132 	imgp->stringspace = ARG_MAX;
133 
134 	/*
135 	 * Translate the file name. namei() returns a vnode pointer
136 	 *	in ni_vp amoung other things.
137 	 */
138 	ndp = &nd;
139 	NDINIT(ndp, LOOKUP, LOCKLEAF | FOLLOW | SAVENAME,
140 	    UIO_USERSPACE, uap->fname, p);
141 
142 interpret:
143 
144 	error = namei(ndp);
145 	if (error) {
146 		kmem_free(exec_map, (vm_offset_t)imgp->stringbase, ARG_MAX);
147 		goto exec_fail;
148 	}
149 
150 	imgp->vp = ndp->ni_vp;
151 	if (imgp->vp == NULL) {
152 		error = ENOEXEC;
153 		goto exec_fail_dealloc;
154 	}
155 
156 	/*
157 	 * Check file permissions (also 'opens' file)
158 	 */
159 	error = exec_check_permissions(imgp);
160 
161 	/*
162 	 * Lose the lock on the vnode. It's no longer needed, and must not
163 	 * exist for the pagefault paging to work below.
164 	 */
165 	VOP_UNLOCK(imgp->vp);
166 
167 	if (error)
168 		goto exec_fail_dealloc;
169 
170 	/*
171 	 * Map the image header (first page) of the file into
172 	 *	kernel address space
173 	 */
174 	error = vm_mmap(kernel_map,			/* map */
175 			(vm_offset_t *)&imgp->image_header, /* address */
176 			PAGE_SIZE,			/* size */
177 			VM_PROT_READ, 			/* protection */
178 			VM_PROT_READ, 			/* max protection */
179 			0,	 			/* flags */
180 			(caddr_t)imgp->vp,		/* vnode */
181 			0);				/* offset */
182 	if (error) {
183 		uprintf("mmap failed: %d\n",error);
184 		goto exec_fail_dealloc;
185 	}
186 
187 	/*
188 	 * Loop through list of image activators, calling each one.
189 	 *	If there is no match, the activator returns -1. If there
190 	 *	is a match, but there was an error during the activation,
191 	 *	the error is returned. Otherwise 0 means success. If the
192 	 *	image is interpreted, loop back up and try activating
193 	 *	the interpreter.
194 	 */
195 	for (i = 0; execsw[i]; ++i) {
196 		if (execsw[i]->ex_imgact)
197 			error = (*execsw[i]->ex_imgact)(imgp);
198 		else
199 			continue;
200 
201 		if (error == -1)
202 			continue;
203 		if (error)
204 			goto exec_fail_dealloc;
205 		if (imgp->interpreted) {
206 			/* free old vnode and name buffer */
207 			vrele(ndp->ni_vp);
208 			FREE(ndp->ni_cnd.cn_pnbuf, M_NAMEI);
209 			if (vm_map_remove(kernel_map, (vm_offset_t)imgp->image_header,
210 			    (vm_offset_t)imgp->image_header + PAGE_SIZE))
211 				panic("execve: header dealloc failed (1)");
212 
213 			/* set new name to that of the interpreter */
214 			NDINIT(ndp, LOOKUP, LOCKLEAF | FOLLOW | SAVENAME,
215 			    UIO_SYSSPACE, imgp->interpreter_name, p);
216 			goto interpret;
217 		}
218 		break;
219 	}
220 	/* If we made it through all the activators and none matched, exit. */
221 	if (error == -1) {
222 		error = ENOEXEC;
223 		goto exec_fail_dealloc;
224 	}
225 
226 	/*
227 	 * Copy out strings (args and env) and initialize stack base
228 	 */
229 	stack_base = exec_copyout_strings(imgp);
230 	p->p_vmspace->vm_minsaddr = (char *)stack_base;
231 
232 	/*
233 	 * If custom stack fixup routine present for this process
234 	 * let it do the stack setup.
235 	 * Else stuff argument count as first item on stack
236 	 */
237 	if (p->p_sysent->sv_fixup)
238 		(*p->p_sysent->sv_fixup)(&stack_base, imgp);
239 	else
240 		suword(--stack_base, imgp->argc);
241 
242 	/* close files on exec */
243 	fdcloseexec(p);
244 
245 	/* reset caught signals */
246 	execsigs(p);
247 
248 	/* name this process - nameiexec(p, ndp) */
249 	len = min(ndp->ni_cnd.cn_namelen,MAXCOMLEN);
250 	bcopy(ndp->ni_cnd.cn_nameptr, p->p_comm, len);
251 	p->p_comm[len] = 0;
252 
253 	/*
254 	 * mark as executable, wakeup any process that was vforked and tell
255 	 * it that it now has it's own resources back
256 	 */
257 	p->p_flag |= P_EXEC;
258 	if (p->p_pptr && (p->p_flag & P_PPWAIT)) {
259 		p->p_flag &= ~P_PPWAIT;
260 		wakeup((caddr_t)p->p_pptr);
261 	}
262 
263 	/*
264 	 * Implement image setuid/setgid. Disallow if the process is
265 	 * being traced.
266 	 */
267 	if ((attr.va_mode & (VSUID | VSGID)) &&
268 	    (p->p_flag & P_TRACED) == 0) {
269 		/*
270 		 * Turn off syscall tracing for set-id programs, except for
271 		 * root.
272 		 */
273 		if (p->p_tracep && suser(p->p_ucred, &p->p_acflag)) {
274 			p->p_traceflag = 0;
275 			vrele(p->p_tracep);
276 			p->p_tracep = NULL;
277 		}
278 		/*
279 		 * Set the new credentials.
280 		 */
281 		p->p_ucred = crcopy(p->p_ucred);
282 		if (attr.va_mode & VSUID)
283 			p->p_ucred->cr_uid = attr.va_uid;
284 		if (attr.va_mode & VSGID)
285 			p->p_ucred->cr_groups[0] = attr.va_gid;
286 		p->p_flag |= P_SUGID;
287 	} else {
288 		p->p_flag &= ~P_SUGID;
289 	}
290 
291 	/*
292 	 * Implement correct POSIX saved-id behavior.
293 	 */
294 	p->p_cred->p_svuid = p->p_ucred->cr_uid;
295 	p->p_cred->p_svgid = p->p_ucred->cr_gid;
296 
297 	/*
298 	 * Store the vp for use in procfs
299 	 */
300 	if (p->p_textvp)		/* release old reference */
301 		vrele(p->p_textvp);
302 	VREF(ndp->ni_vp);
303 	p->p_textvp = ndp->ni_vp;
304 
305 	/*
306 	 * If tracing the process, trap to debugger so breakpoints
307 	 * 	can be set before the program executes.
308 	 */
309 	if (p->p_flag & P_TRACED)
310 		psignal(p, SIGTRAP);
311 
312 	/* clear "fork but no exec" flag, as we _are_ execing */
313 	p->p_acflag &= ~AFORK;
314 
315 	/* Set entry address */
316 	setregs(p, imgp->entry_addr, (u_long)stack_base);
317 
318 	/*
319 	 * free various allocated resources
320 	 */
321 	kmem_free(exec_map, (vm_offset_t)imgp->stringbase, ARG_MAX);
322 	if (vm_map_remove(kernel_map, (vm_offset_t)imgp->image_header,
323 	    (vm_offset_t)imgp->image_header + PAGE_SIZE))
324 		panic("execve: header dealloc failed (2)");
325 	vrele(ndp->ni_vp);
326 	FREE(ndp->ni_cnd.cn_pnbuf, M_NAMEI);
327 
328 	return (0);
329 
330 exec_fail_dealloc:
331 	if (imgp->stringbase != NULL)
332 		kmem_free(exec_map, (vm_offset_t)imgp->stringbase, ARG_MAX);
333 	if (imgp->image_header && imgp->image_header != (char *)-1)
334 		if (vm_map_remove(kernel_map, (vm_offset_t)imgp->image_header,
335 		    (vm_offset_t)imgp->image_header + PAGE_SIZE))
336 			panic("execve: header dealloc failed (3)");
337 	if (ndp->ni_vp)
338 		vrele(ndp->ni_vp);
339 	FREE(ndp->ni_cnd.cn_pnbuf, M_NAMEI);
340 
341 exec_fail:
342 	if (imgp->vmspace_destroyed) {
343 		/* sorry, no more process anymore. exit gracefully */
344 		exit1(p, W_EXITCODE(0, SIGABRT));
345 		/* NOT REACHED */
346 		return(0);
347 	} else {
348 		return(error);
349 	}
350 }
351 
352 /*
353  * Destroy old address space, and allocate a new stack
354  *	The new stack is only SGROWSIZ large because it is grown
355  *	automatically in trap.c.
356  */
357 int
358 exec_new_vmspace(imgp)
359 	struct image_params *imgp;
360 {
361 	int error;
362 	struct vmspace *vmspace = imgp->proc->p_vmspace;
363 	caddr_t	stack_addr = (caddr_t) (USRSTACK - SGROWSIZ);
364 
365 	imgp->vmspace_destroyed = 1;
366 
367 	/* Blow away entire process VM */
368 	if (vmspace->vm_shm)
369 		shmexit(imgp->proc);
370 	vm_map_remove(&vmspace->vm_map, 0, USRSTACK);
371 
372 	/* Allocate a new stack */
373 	error = vm_map_find(&vmspace->vm_map, NULL, 0, (vm_offset_t *)&stack_addr,
374 	    SGROWSIZ, FALSE, VM_PROT_ALL, VM_PROT_ALL, 0);
375 	if (error)
376 		return(error);
377 
378 	vmspace->vm_ssize = SGROWSIZ >> PAGE_SHIFT;
379 
380 	/* Initialize maximum stack address */
381 	vmspace->vm_maxsaddr = (char *)USRSTACK - MAXSSIZ;
382 
383 	return(0);
384 }
385 
386 /*
387  * Copy out argument and environment strings from the old process
388  *	address space into the temporary string buffer.
389  */
390 int
391 exec_extract_strings(imgp)
392 	struct image_params *imgp;
393 {
394 	char	**argv, **envv;
395 	char	*argp, *envp;
396 	int	error, length;
397 
398 	/*
399 	 * extract arguments first
400 	 */
401 
402 	argv = imgp->uap->argv;
403 
404 	if (argv) {
405 		while ((argp = (caddr_t) fuword(argv++))) {
406 			if (argp == (caddr_t) -1)
407 				return (EFAULT);
408 			if ((error = copyinstr(argp, imgp->stringp,
409 			    imgp->stringspace, &length))) {
410 				if (error == ENAMETOOLONG)
411 					return(E2BIG);
412 				return (error);
413 			}
414 			imgp->stringspace -= length;
415 			imgp->stringp += length;
416 			imgp->argc++;
417 		}
418 	}
419 
420 	/*
421 	 * extract environment strings
422 	 */
423 
424 	envv = imgp->uap->envv;
425 
426 	if (envv) {
427 		while ((envp = (caddr_t) fuword(envv++))) {
428 			if (envp == (caddr_t) -1)
429 				return (EFAULT);
430 			if ((error = copyinstr(envp, imgp->stringp,
431 			    imgp->stringspace, &length))) {
432 				if (error == ENAMETOOLONG)
433 					return(E2BIG);
434 				return (error);
435 			}
436 			imgp->stringspace -= length;
437 			imgp->stringp += length;
438 			imgp->envc++;
439 		}
440 	}
441 
442 	return (0);
443 }
444 
445 /*
446  * Copy strings out to the new process address space, constructing
447  *	new arg and env vector tables. Return a pointer to the base
448  *	so that it can be used as the initial stack pointer.
449  */
450 int *
451 exec_copyout_strings(imgp)
452 	struct image_params *imgp;
453 {
454 	int argc, envc;
455 	char **vectp;
456 	char *stringp, *destp;
457 	int *stack_base;
458 	struct ps_strings *arginfo;
459 
460 	/*
461 	 * Calculate string base and vector table pointers.
462 	 */
463 	arginfo = PS_STRINGS;
464 	destp =	(caddr_t)arginfo - SPARE_USRSPACE -
465 		roundup((ARG_MAX - imgp->stringspace), sizeof(char *));
466 
467 	/*
468 	 * The '+ 2' is for the null pointers at the end of each of the
469 	 *	arg and	env vector sets
470 	 */
471 	vectp = (char **) (destp -
472 		(imgp->argc + imgp->envc + 2) * sizeof(char *));
473 
474 	/*
475 	 * vectp also becomes our initial stack base
476 	 */
477 	stack_base = (int *)vectp;
478 
479 	stringp = imgp->stringbase;
480 	argc = imgp->argc;
481 	envc = imgp->envc;
482 
483 	/*
484 	 * Copy out strings - arguments and environment.
485 	 */
486 	copyout(stringp, destp, ARG_MAX - imgp->stringspace);
487 
488 	/*
489 	 * Fill in "ps_strings" struct for ps, w, etc.
490 	 */
491 	suword(&arginfo->ps_argvstr, (int)vectp);
492 	suword(&arginfo->ps_nargvstr, argc);
493 
494 	/*
495 	 * Fill in argument portion of vector table.
496 	 */
497 	for (; argc > 0; --argc) {
498 		suword(vectp++, (int)destp);
499 		while (*stringp++ != 0)
500 			destp++;
501 		destp++;
502 	}
503 
504 	/* a null vector table pointer seperates the argp's from the envp's */
505 	suword(vectp++, NULL);
506 
507 	suword(&arginfo->ps_envstr, (int)vectp);
508 	suword(&arginfo->ps_nenvstr, envc);
509 
510 	/*
511 	 * Fill in environment portion of vector table.
512 	 */
513 	for (; envc > 0; --envc) {
514 		suword(vectp++, (int)destp);
515 		while (*stringp++ != 0)
516 			destp++;
517 		destp++;
518 	}
519 
520 	/* end of vector table is a null pointer */
521 	suword(vectp, NULL);
522 
523 	return (stack_base);
524 }
525 
526 /*
527  * Check permissions of file to execute.
528  *	Return 0 for success or error code on failure.
529  */
530 static int
531 exec_check_permissions(imgp)
532 	struct image_params *imgp;
533 {
534 	struct proc *p = imgp->proc;
535 	struct vnode *vp = imgp->vp;
536 	struct vattr *attr = imgp->attr;
537 	int error;
538 
539 	/*
540 	 * Check number of open-for-writes on the file and deny execution
541 	 *	if there are any.
542 	 */
543 	if (vp->v_writecount) {
544 		return (ETXTBSY);
545 	}
546 
547 	/* Get file attributes */
548 	error = VOP_GETATTR(vp, attr, p->p_ucred, p);
549 	if (error)
550 		return (error);
551 
552 	/*
553 	 * 1) Check if file execution is disabled for the filesystem that this
554 	 *	file resides on.
555 	 * 2) Insure that at least one execute bit is on - otherwise root
556 	 *	will always succeed, and we don't want to happen unless the
557 	 *	file really is executable.
558 	 * 3) Insure that the file is a regular file.
559 	 */
560 	if ((vp->v_mount->mnt_flag & MNT_NOEXEC) ||
561 	    ((attr->va_mode & 0111) == 0) ||
562 	    (attr->va_type != VREG)) {
563 		return (EACCES);
564 	}
565 
566 	/*
567 	 * Zero length files can't be exec'd
568 	 */
569 	if (attr->va_size == 0)
570 		return (ENOEXEC);
571 
572 	/*
573 	 * Disable setuid/setgid if the filesystem prohibits it or if
574 	 *	the process is being traced.
575 	 */
576         if ((vp->v_mount->mnt_flag & MNT_NOSUID) || (p->p_flag & P_TRACED))
577 		attr->va_mode &= ~(VSUID | VSGID);
578 
579 	/*
580 	 *  Check for execute permission to file based on current credentials.
581 	 *	Then call filesystem specific open routine (which does nothing
582 	 *	in the general case).
583 	 */
584 	error = VOP_ACCESS(vp, VEXEC, p->p_ucred, p);
585 	if (error)
586 		return (error);
587 
588 	error = VOP_OPEN(vp, FREAD, p->p_ucred, p);
589 	if (error)
590 		return (error);
591 
592 	return (0);
593 }
594