xref: /freebsd/sys/kern/imgact_shell.c (revision 22cf89c938886d14f5796fc49f9f020c23ea8eaf)
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 <sys/cdefs.h>
30 #include <sys/param.h>
31 #include <sys/vnode.h>
32 #include <sys/proc.h>
33 #include <sys/sbuf.h>
34 #include <sys/systm.h>
35 #include <sys/sysproto.h>
36 #include <sys/exec.h>
37 #include <sys/imgact.h>
38 #include <sys/kernel.h>
39 
40 #if BYTE_ORDER == LITTLE_ENDIAN
41 #define SHELLMAGIC	0x2123 /* #! */
42 #else
43 #define SHELLMAGIC	0x2321
44 #endif
45 
46 /*
47  * At the time of this writing, MAXSHELLCMDLEN == PAGE_SIZE.  This is
48  * significant because the caller has only mapped in one page of the
49  * file we're reading.
50  */
51 #if MAXSHELLCMDLEN > PAGE_SIZE
52 #error "MAXSHELLCMDLEN is larger than a single page!"
53 #endif
54 
55 /*
56  * MAXSHELLCMDLEN must be at least MAXINTERP plus the size of the `#!'
57  * prefix and terminating newline.
58  */
59 CTASSERT(MAXSHELLCMDLEN >= MAXINTERP + 3);
60 
61 /**
62  * Shell interpreter image activator. An interpreter name beginning at
63  * imgp->args->begin_argv is the minimal successful exit requirement.
64  *
65  * If the given file is a shell-script, then the first line will start
66  * with the two characters `#!' (aka SHELLMAGIC), followed by the name
67  * of the shell-interpreter to run, followed by zero or more tokens.
68  *
69  * The interpreter is then started up such that it will see:
70  *    arg[0] -> The name of interpreter as specified after `#!' in the
71  *		first line of the script.  The interpreter name must
72  *		not be longer than MAXSHELLCMDLEN bytes.
73  *    arg[1] -> *If* there are any additional tokens on the first line,
74  *		then we add a new arg[1], which is a copy of the rest of
75  *		that line.  The copy starts at the first token after the
76  *		interpreter name.  We leave it to the interpreter to
77  *		parse the tokens in that value.
78  *    arg[x] -> the full pathname of the script.  This will either be
79  *		arg[2] or arg[1], depending on whether or not tokens
80  *		were found after the interpreter name.
81  *  arg[x+1] -> all the arguments that were specified on the original
82  *		command line.
83  *
84  * This processing is described in the execve(2) man page.
85  */
86 
87 /*
88  * HISTORICAL NOTE: From 1993 to mid-2005, FreeBSD parsed out the tokens as
89  * found on the first line of the script, and setup each token as a separate
90  * value in arg[].  This extra processing did not match the behavior of other
91  * OS's, and caused a few subtle problems.  For one, it meant the kernel was
92  * deciding how those values should be parsed (wrt characters for quoting or
93  * comments, etc), while the interpreter might have other rules for parsing.
94  * It also meant the interpreter had no way of knowing which arguments came
95  * from the first line of the shell script, and which arguments were specified
96  * by the user on the command line.  That extra processing was dropped in the
97  * 6.x branch on May 28, 2005 (matching __FreeBSD_version 600029).
98  */
99 int
100 exec_shell_imgact(struct image_params *imgp)
101 {
102 	const char *image_header = imgp->image_header;
103 	const char *ihp, *interpb, *interpe, *maxp, *optb, *opte, *fname;
104 	int error, offset;
105 	size_t length;
106 	struct vattr vattr;
107 	struct sbuf *sname;
108 
109 	/* a shell script? */
110 	if (((const short *)image_header)[0] != SHELLMAGIC)
111 		return (-1);
112 
113 	/*
114 	 * Don't allow a shell script to be the shell for a shell
115 	 *	script. :-)
116 	 */
117 	if (imgp->interpreted & IMGACT_SHELL)
118 		return (ENOEXEC);
119 
120 	imgp->interpreted |= IMGACT_SHELL;
121 
122 	/*
123 	 * At this point we have the first page of the file mapped.
124 	 * However, we don't know how far into the page the contents are
125 	 * valid -- the actual file might be much shorter than the page.
126 	 * So find out the file size.
127 	 */
128 	error = VOP_GETATTR(imgp->vp, &vattr, imgp->proc->p_ucred);
129 	if (error)
130 		return (error);
131 
132 	/*
133 	 * Copy shell name and arguments from image_header into a string
134 	 * buffer.
135 	 */
136 	maxp = &image_header[MIN(vattr.va_size, MAXSHELLCMDLEN)];
137 	ihp = &image_header[2];
138 
139 	/*
140 	 * Find the beginning and end of the interpreter_name.  If the
141 	 * line does not include any interpreter, or if the name which
142 	 * was found is too long, we bail out.
143 	 */
144 	while (ihp < maxp && ((*ihp == ' ') || (*ihp == '\t')))
145 		ihp++;
146 	interpb = ihp;
147 	while (ihp < maxp && ((*ihp != ' ') && (*ihp != '\t') && (*ihp != '\n')
148 	    && (*ihp != '\0')))
149 		ihp++;
150 	interpe = ihp;
151 	if (interpb == interpe)
152 		return (ENOEXEC);
153 	if (interpe - interpb >= MAXINTERP)
154 		return (ENAMETOOLONG);
155 
156 	/*
157 	 * Find the beginning of the options (if any), and the end-of-line.
158 	 * Then trim the trailing blanks off the value.  Note that some
159 	 * other operating systems do *not* trim the trailing whitespace...
160 	 */
161 	while (ihp < maxp && ((*ihp == ' ') || (*ihp == '\t')))
162 		ihp++;
163 	optb = ihp;
164 	while (ihp < maxp && ((*ihp != '\n') && (*ihp != '\0')))
165 		ihp++;
166 	opte = ihp;
167 	if (opte == maxp)
168 		return (ENOEXEC);
169 	while (--ihp > optb && ((*ihp == ' ') || (*ihp == '\t')))
170 		opte = ihp;
171 
172 	if (imgp->args->fname != NULL) {
173 		fname = imgp->args->fname;
174 		sname = NULL;
175 	} else {
176 		sname = sbuf_new_auto();
177 		sbuf_printf(sname, "/dev/fd/%d", imgp->args->fd);
178 		sbuf_finish(sname);
179 		fname = sbuf_data(sname);
180 	}
181 
182 	/*
183 	 * We need to "pop" (remove) the present value of arg[0], and "push"
184 	 * either two or three new values in the arg[] list.  To do this,
185 	 * we first shift all the other values in the `begin_argv' area to
186 	 * provide the exact amount of room for the values added.  Set up
187 	 * `offset' as the number of bytes to be added to the `begin_argv'
188 	 * area, and 'length' as the number of bytes being removed.
189 	 */
190 	offset = interpe - interpb + 1;			/* interpreter */
191 	if (opte > optb)				/* options (if any) */
192 		offset += opte - optb + 1;
193 	offset += strlen(fname) + 1;			/* fname of script */
194 	length = (imgp->args->argc == 0) ? 0 :
195 	    strlen(imgp->args->begin_argv) + 1;		/* bytes to delete */
196 
197 	error = exec_args_adjust_args(imgp->args, length, offset);
198 	if (error != 0) {
199 		if (sname != NULL)
200 			sbuf_delete(sname);
201 		return (error);
202 	}
203 
204 	/*
205 	 * If there was no arg[0] when we started, then the interpreter_name
206 	 * is adding an argument (instead of replacing the arg[0] we started
207 	 * with).  And we're always adding an argument when we include the
208 	 * full pathname of the original script.
209 	 */
210 	if (imgp->args->argc == 0)
211 		imgp->args->argc = 1;
212 	imgp->args->argc++;
213 
214 	/*
215 	 * The original arg[] list has been shifted appropriately.  Copy in
216 	 * the interpreter name and options-string.
217 	 */
218 	length = interpe - interpb;
219 	bcopy(interpb, imgp->args->begin_argv, length);
220 	*(imgp->args->begin_argv + length) = '\0';
221 	offset = length + 1;
222 	if (opte > optb) {
223 		length = opte - optb;
224 		bcopy(optb, imgp->args->begin_argv + offset, length);
225 		*(imgp->args->begin_argv + offset + length) = '\0';
226 		offset += length + 1;
227 		imgp->args->argc++;
228 	}
229 
230 	/*
231 	 * Finally, add the filename onto the end for the interpreter to
232 	 * use and copy the interpreter's name to imgp->interpreter_name
233 	 * for exec to use.
234 	 */
235 	error = copystr(fname, imgp->args->begin_argv + offset,
236 	    imgp->args->stringspace, NULL);
237 
238 	if (error == 0)
239 		imgp->interpreter_name = imgp->args->begin_argv;
240 
241 	if (sname != NULL)
242 		sbuf_delete(sname);
243 	return (error);
244 }
245 
246 /*
247  * Tell kern_execve.c about it, with a little help from the linker.
248  */
249 static struct execsw shell_execsw = {
250 	.ex_imgact = exec_shell_imgact,
251 	.ex_name = "#!"
252 };
253 EXEC_SET(shell, shell_execsw);
254