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