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