Source file src/cmd/go/internal/work/security.go

     1  // Copyright 2018 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Checking of compiler and linker flags.
     6  // We must avoid flags like -fplugin=, which can allow
     7  // arbitrary code execution during the build.
     8  // Do not make changes here without carefully
     9  // considering the implications.
    10  // (That's why the code is isolated in a file named security.go.)
    11  //
    12  // Note that -Wl,foo means split foo on commas and pass to
    13  // the linker, so that -Wl,-foo,bar means pass -foo bar to
    14  // the linker. Similarly -Wa,foo for the assembler and so on.
    15  // If any of these are permitted, the wildcard portion must
    16  // disallow commas.
    17  //
    18  // Note also that GNU binutils accept any argument @foo
    19  // as meaning "read more flags from the file foo", so we must
    20  // guard against any command-line argument beginning with @,
    21  // even things like "-I @foo".
    22  // We use load.SafeArg (which is even more conservative)
    23  // to reject these.
    24  //
    25  // Even worse, gcc -I@foo (one arg) turns into cc1 -I @foo (two args),
    26  // so although gcc doesn't expand the @foo, cc1 will.
    27  // So out of paranoia, we reject @ at the beginning of every
    28  // flag argument that might be split into its own argument.
    29  
    30  package work
    31  
    32  import (
    33  	"fmt"
    34  	"internal/lazyregexp"
    35  	"regexp"
    36  	"strings"
    37  
    38  	"cmd/go/internal/cfg"
    39  	"cmd/go/internal/load"
    40  )
    41  
    42  var re = lazyregexp.New
    43  
    44  var validCompilerFlags = []*lazyregexp.Regexp{
    45  	re(`-D([A-Za-z_][A-Za-z0-9_]*)(=[^@\-]*)?`),
    46  	re(`-U([A-Za-z_][A-Za-z0-9_]*)`),
    47  	re(`-F([^@\-].*)`),
    48  	re(`-I([^@\-].*)`),
    49  	re(`-O`),
    50  	re(`-O([^@\-].*)`),
    51  	re(`-W`),
    52  	re(`-W([^@,]+)`), // -Wall but not -Wa,-foo.
    53  	re(`-Wa,-mbig-obj`),
    54  	re(`-Wp,-D([A-Za-z_][A-Za-z0-9_]*)(=[^@,\-]*)?`),
    55  	re(`-Wp,-U([A-Za-z_][A-Za-z0-9_]*)`),
    56  	re(`-ansi`),
    57  	re(`-f(no-)?asynchronous-unwind-tables`),
    58  	re(`-f(no-)?blocks`),
    59  	re(`-f(no-)builtin-[a-zA-Z0-9_]*`),
    60  	re(`-f(no-)?common`),
    61  	re(`-f(no-)?constant-cfstrings`),
    62  	re(`-fdebug-prefix-map=([^@]+)=([^@]+)`),
    63  	re(`-fdiagnostics-show-note-include-stack`),
    64  	re(`-ffile-prefix-map=([^@]+)=([^@]+)`),
    65  	re(`-fno-canonical-system-headers`),
    66  	re(`-f(no-)?eliminate-unused-debug-types`),
    67  	re(`-f(no-)?exceptions`),
    68  	re(`-f(no-)?fast-math`),
    69  	re(`-f(no-)?inline-functions`),
    70  	re(`-finput-charset=([^@\-].*)`),
    71  	re(`-f(no-)?fat-lto-objects`),
    72  	re(`-f(no-)?keep-inline-dllexport`),
    73  	re(`-f(no-)?lto`),
    74  	re(`-fmacro-backtrace-limit=(.+)`),
    75  	re(`-fmessage-length=(.+)`),
    76  	re(`-f(no-)?modules`),
    77  	re(`-f(no-)?objc-arc`),
    78  	re(`-f(no-)?objc-nonfragile-abi`),
    79  	re(`-f(no-)?objc-legacy-dispatch`),
    80  	re(`-f(no-)?omit-frame-pointer`),
    81  	re(`-f(no-)?openmp(-simd)?`),
    82  	re(`-f(no-)?permissive`),
    83  	re(`-f(no-)?(pic|PIC|pie|PIE)`),
    84  	re(`-f(no-)?plt`),
    85  	re(`-f(no-)?rtti`),
    86  	re(`-f(no-)?split-stack`),
    87  	re(`-f(no-)?stack-(.+)`),
    88  	re(`-f(no-)?strict-aliasing`),
    89  	re(`-f(un)signed-char`),
    90  	re(`-f(no-)?use-linker-plugin`), // safe if -B is not used; we don't permit -B
    91  	re(`-f(no-)?visibility-inlines-hidden`),
    92  	re(`-fsanitize=(.+)`),
    93  	re(`-ftemplate-depth-(.+)`),
    94  	re(`-fvisibility=(.+)`),
    95  	re(`-g([^@\-].*)?`),
    96  	re(`-m32`),
    97  	re(`-m64`),
    98  	re(`-m(abi|arch|cpu|fpu|tune)=([^@\-].*)`),
    99  	re(`-m(no-)?v?aes`),
   100  	re(`-marm`),
   101  	re(`-m(no-)?avx[0-9a-z]*`),
   102  	re(`-mfloat-abi=([^@\-].*)`),
   103  	re(`-mfpmath=[0-9a-z,+]*`),
   104  	re(`-m(no-)?avx[0-9a-z.]*`),
   105  	re(`-m(no-)?ms-bitfields`),
   106  	re(`-m(no-)?stack-(.+)`),
   107  	re(`-mmacosx-(.+)`),
   108  	re(`-mios-simulator-version-min=(.+)`),
   109  	re(`-miphoneos-version-min=(.+)`),
   110  	re(`-mtvos-simulator-version-min=(.+)`),
   111  	re(`-mtvos-version-min=(.+)`),
   112  	re(`-mwatchos-simulator-version-min=(.+)`),
   113  	re(`-mwatchos-version-min=(.+)`),
   114  	re(`-mnop-fun-dllimport`),
   115  	re(`-m(no-)?sse[0-9.]*`),
   116  	re(`-m(no-)?ssse3`),
   117  	re(`-mthumb(-interwork)?`),
   118  	re(`-mthreads`),
   119  	re(`-mwindows`),
   120  	re(`-no-canonical-prefixes`),
   121  	re(`--param=ssp-buffer-size=[0-9]*`),
   122  	re(`-pedantic(-errors)?`),
   123  	re(`-pipe`),
   124  	re(`-pthread`),
   125  	re(`-?-std=([^@\-].*)`),
   126  	re(`-?-stdlib=([^@\-].*)`),
   127  	re(`--sysroot=([^@\-].*)`),
   128  	re(`-w`),
   129  	re(`-x([^@\-].*)`),
   130  	re(`-v`),
   131  }
   132  
   133  var validCompilerFlagsWithNextArg = []string{
   134  	"-arch",
   135  	"-D",
   136  	"-U",
   137  	"-I",
   138  	"-F",
   139  	"-framework",
   140  	"-include",
   141  	"-isysroot",
   142  	"-isystem",
   143  	"--sysroot",
   144  	"-target",
   145  	"-x",
   146  }
   147  
   148  var invalidLinkerFlags = []*lazyregexp.Regexp{
   149  	// On macOS this means the linker loads and executes the next argument.
   150  	// Have to exclude separately because -lfoo is allowed in general.
   151  	re(`-lto_library`),
   152  }
   153  
   154  var validLinkerFlags = []*lazyregexp.Regexp{
   155  	re(`-F([^@\-].*)`),
   156  	re(`-l([^@\-].*)`),
   157  	re(`-L([^@\-].*)`),
   158  	re(`-O`),
   159  	re(`-O([^@\-].*)`),
   160  	re(`-f(no-)?(pic|PIC|pie|PIE)`),
   161  	re(`-f(no-)?openmp(-simd)?`),
   162  	re(`-fsanitize=([^@\-].*)`),
   163  	re(`-flat_namespace`),
   164  	re(`-g([^@\-].*)?`),
   165  	re(`-headerpad_max_install_names`),
   166  	re(`-m(abi|arch|cpu|fpu|tune)=([^@\-].*)`),
   167  	re(`-mfloat-abi=([^@\-].*)`),
   168  	re(`-mmacosx-(.+)`),
   169  	re(`-mios-simulator-version-min=(.+)`),
   170  	re(`-miphoneos-version-min=(.+)`),
   171  	re(`-mthreads`),
   172  	re(`-mwindows`),
   173  	re(`-(pic|PIC|pie|PIE)`),
   174  	re(`-pthread`),
   175  	re(`-rdynamic`),
   176  	re(`-shared`),
   177  	re(`-?-static([-a-z0-9+]*)`),
   178  	re(`-?-stdlib=([^@\-].*)`),
   179  	re(`-v`),
   180  
   181  	// Note that any wildcards in -Wl need to exclude comma,
   182  	// since -Wl splits its argument at commas and passes
   183  	// them all to the linker uninterpreted. Allowing comma
   184  	// in a wildcard would allow tunneling arbitrary additional
   185  	// linker arguments through one of these.
   186  	re(`-Wl,--(no-)?allow-multiple-definition`),
   187  	re(`-Wl,--(no-)?allow-shlib-undefined`),
   188  	re(`-Wl,--(no-)?as-needed`),
   189  	re(`-Wl,-Bdynamic`),
   190  	re(`-Wl,-berok`),
   191  	re(`-Wl,-Bstatic`),
   192  	re(`-Wl,-Bsymbolic-functions`),
   193  	re(`-Wl,-O[0-9]+`),
   194  	re(`-Wl,-d[ny]`),
   195  	re(`-Wl,--disable-new-dtags`),
   196  	re(`-Wl,-e[=,][a-zA-Z0-9]+`),
   197  	re(`-Wl,--enable-new-dtags`),
   198  	re(`-Wl,--end-group`),
   199  	re(`-Wl,--(no-)?export-dynamic`),
   200  	re(`-Wl,-E`),
   201  	re(`-Wl,-framework,[^,@\-][^,]+`),
   202  	re(`-Wl,--hash-style=(sysv|gnu|both)`),
   203  	re(`-Wl,-headerpad_max_install_names`),
   204  	re(`-Wl,--no-undefined`),
   205  	re(`-Wl,-R,?([^@\-,][^,@]*$)`),
   206  	re(`-Wl,--just-symbols[=,]([^,@\-][^,@]+)`),
   207  	re(`-Wl,-rpath(-link)?[=,]([^,@\-][^,]+)`),
   208  	re(`-Wl,-s`),
   209  	re(`-Wl,-search_paths_first`),
   210  	re(`-Wl,-sectcreate,([^,@\-][^,]+),([^,@\-][^,]+),([^,@\-][^,]+)`),
   211  	re(`-Wl,--start-group`),
   212  	re(`-Wl,-?-static`),
   213  	re(`-Wl,-?-subsystem,(native|windows|console|posix|xbox)`),
   214  	re(`-Wl,-syslibroot[=,]([^,@\-][^,]+)`),
   215  	re(`-Wl,-undefined[=,]([^,@\-][^,]+)`),
   216  	re(`-Wl,-?-unresolved-symbols=[^,]+`),
   217  	re(`-Wl,--(no-)?warn-([^,]+)`),
   218  	re(`-Wl,-?-wrap[=,][^,@\-][^,]*`),
   219  	re(`-Wl(,-z,(relro|now|(no)?execstack))+`),
   220  
   221  	re(`[a-zA-Z0-9_/].*\.(a|o|obj|dll|dylib|so|tbd)`), // direct linker inputs: x.o or libfoo.so (but not -foo.o or @foo.o)
   222  	re(`\./.*\.(a|o|obj|dll|dylib|so|tbd)`),
   223  }
   224  
   225  var validLinkerFlagsWithNextArg = []string{
   226  	"-arch",
   227  	"-F",
   228  	"-l",
   229  	"-L",
   230  	"-framework",
   231  	"-isysroot",
   232  	"--sysroot",
   233  	"-target",
   234  	"-Wl,-framework",
   235  	"-Wl,-rpath",
   236  	"-Wl,-R",
   237  	"-Wl,--just-symbols",
   238  	"-Wl,-undefined",
   239  }
   240  
   241  func checkCompilerFlags(name, source string, list []string) error {
   242  	checkOverrides := true
   243  	return checkFlags(name, source, list, nil, validCompilerFlags, validCompilerFlagsWithNextArg, checkOverrides)
   244  }
   245  
   246  func checkLinkerFlags(name, source string, list []string) error {
   247  	checkOverrides := true
   248  	return checkFlags(name, source, list, invalidLinkerFlags, validLinkerFlags, validLinkerFlagsWithNextArg, checkOverrides)
   249  }
   250  
   251  // checkCompilerFlagsForInternalLink returns an error if 'list'
   252  // contains a flag or flags that may not be fully supported by
   253  // internal linking (meaning that we should punt the link to the
   254  // external linker).
   255  func checkCompilerFlagsForInternalLink(name, source string, list []string) error {
   256  	checkOverrides := false
   257  	if err := checkFlags(name, source, list, nil, validCompilerFlags, validCompilerFlagsWithNextArg, checkOverrides); err != nil {
   258  		return err
   259  	}
   260  	// Currently the only flag on the allow list that causes problems
   261  	// for the linker is "-flto"; check for it manually here.
   262  	for _, fl := range list {
   263  		if strings.HasPrefix(fl, "-flto") {
   264  			return fmt.Errorf("flag %q triggers external linking", fl)
   265  		}
   266  	}
   267  	return nil
   268  }
   269  
   270  func checkFlags(name, source string, list []string, invalid, valid []*lazyregexp.Regexp, validNext []string, checkOverrides bool) error {
   271  	// Let users override rules with $CGO_CFLAGS_ALLOW, $CGO_CFLAGS_DISALLOW, etc.
   272  	var (
   273  		allow    *regexp.Regexp
   274  		disallow *regexp.Regexp
   275  	)
   276  	if checkOverrides {
   277  		if env := cfg.Getenv("CGO_" + name + "_ALLOW"); env != "" {
   278  			r, err := regexp.Compile(env)
   279  			if err != nil {
   280  				return fmt.Errorf("parsing $CGO_%s_ALLOW: %v", name, err)
   281  			}
   282  			allow = r
   283  		}
   284  		if env := cfg.Getenv("CGO_" + name + "_DISALLOW"); env != "" {
   285  			r, err := regexp.Compile(env)
   286  			if err != nil {
   287  				return fmt.Errorf("parsing $CGO_%s_DISALLOW: %v", name, err)
   288  			}
   289  			disallow = r
   290  		}
   291  	}
   292  
   293  Args:
   294  	for i := 0; i < len(list); i++ {
   295  		arg := list[i]
   296  		if disallow != nil && disallow.FindString(arg) == arg {
   297  			goto Bad
   298  		}
   299  		if allow != nil && allow.FindString(arg) == arg {
   300  			continue Args
   301  		}
   302  		for _, re := range invalid {
   303  			if re.FindString(arg) == arg { // must be complete match
   304  				goto Bad
   305  			}
   306  		}
   307  		for _, re := range valid {
   308  			if re.FindString(arg) == arg { // must be complete match
   309  				continue Args
   310  			}
   311  		}
   312  		for _, x := range validNext {
   313  			if arg == x {
   314  				if i+1 < len(list) && load.SafeArg(list[i+1]) {
   315  					i++
   316  					continue Args
   317  				}
   318  
   319  				// Permit -Wl,-framework -Wl,name.
   320  				if i+1 < len(list) &&
   321  					strings.HasPrefix(arg, "-Wl,") &&
   322  					strings.HasPrefix(list[i+1], "-Wl,") &&
   323  					load.SafeArg(list[i+1][4:]) &&
   324  					!strings.Contains(list[i+1][4:], ",") {
   325  					i++
   326  					continue Args
   327  				}
   328  
   329  				// Permit -I= /path, -I $SYSROOT.
   330  				if i+1 < len(list) && arg == "-I" {
   331  					if (strings.HasPrefix(list[i+1], "=") || strings.HasPrefix(list[i+1], "$SYSROOT")) &&
   332  						load.SafeArg(list[i+1][1:]) {
   333  						i++
   334  						continue Args
   335  					}
   336  				}
   337  
   338  				if i+1 < len(list) {
   339  					return fmt.Errorf("invalid flag in %s: %s %s (see https://golang.org/s/invalidflag)", source, arg, list[i+1])
   340  				}
   341  				return fmt.Errorf("invalid flag in %s: %s without argument (see https://golang.org/s/invalidflag)", source, arg)
   342  			}
   343  		}
   344  	Bad:
   345  		return fmt.Errorf("invalid flag in %s: %s", source, arg)
   346  	}
   347  	return nil
   348  }
   349  

View as plain text