179 points · by zdw · 4y ago · 157 comments
Is it, though?
I mean, C is around for around half a century, and C is perhaps the primary language in the FLOSS universe.
Still, why is there no widely adopted idempotent directory tree creation library?
In C++ that functionality is indeed part of the standard library.
It is the intermediary subshell in system() that is the root of all evil, not composing unix programs together; that is what our OS forefathers intended.
The error: you should never pass unescaped/untrusted input into a subshell.
In Python, it’s the difference between the safe:
def make_dir(path):
subprocess.run([“mkdir”, “-p”, path])
Instead of: def make_dir_unsafe(path):
subprocess.run(“mkdir -p “ + path, shell=True)
The latter is easier to type because you don’t need to use the annoying list syntax, but it’s unsafe. If you are writing a library function a subshell is not a sound approach. os.makedirs(path) subprocess.run([“mkdir”, “-p”, path])
This does not work for all values of path. And I'm not just referring to blorgle's complaint. I'm being deliberately vague to make you pause for a second and think. def make_dir(path):
subprocess.run('mkdir -p'.split() + [path])- performance. Obviously that depends on the circumstances but if you are working on a function that is used in many places you don't know the circumstances.
- error handling and reporting. Are you going to capture stderr from mkdir? If this fails can you provide a clear indication of the problem to the caller?
- paths. If you run mkdir without specifying an absolute path your program may fail if $path is not what you expect. That can also be a vulnerability.
- dependencies. Now you won't run in a distroless container or other cut down environment
- you lose type safety
Not saying "never shell out" but I've been burned by most of these so I am cautious about it.
Certainly the worst of it, but even if you pass the untrusted data as a discrete arguments you're still vulnerable to parameter injection.
Let's say, for example, that you're running ["find", USER_SUPPLIED_PATH, "-type", "f"]. If the user supplies "-delete" as the path, the resulting behaviour would not be as intended.
Would it be noticeably slower to the point it's measurably relevant, though? Or are we talking about something well within the domain of premature optimization?
I mean,if you're doing IO, how often does creating a dir end up being the performance bottleneck?
Especially because the early examples in the article (making subdirs for something like different packages/release - "project/staging", "project/production") are almost certainly safe to use a subshell for - so much so that I was genuinely wondering why the author wouldn't just call out to "mkdir -p" for that use case.
The error came when someone decided to pass untrusted/user-supplied data to this function (the later example - usernames).
But I think doing the later is a huge mistake either way. Don't pass untrusted & unsanitized user data ANYWHERE that isn't explicitly designed for it.
Who gives a hoot whether that's to a subshell, or a pipe/stream, or to a sql query, or your DOM, or any other of hundred of places that user supplied data isn't safe.
If you ever see an unsafe string usage being passed into a function that expects a safe string, without an accompanying call to sanitise(), that's very wrong (and won't work if the language is strongly typed) and should be recognised/corrected as such immediately.
Having the code inline makes it easy to audit, and prevents problems when a dependency changes 5 years later.
It also trains people to write proper C code. Writing loops and checking errno should be second nature for a C programmer, and doing it often helps you learn.
It's really a ham-fisted band-aid to an poorly designed threading system. The whole thing is in incredibly bad taste.
If I'm writing traditional, clean, single-threaded Unix, I don't want anything to do with any at() stuff.
Since the at() functions exist, these environments can just not have a global filesystem namespace – there is no open(), only openat() under the descriptors you have. No escaping up from the sandbox!
Generally, just act on the file system. Expect errors to happen and handle them. Even if it's potentially slower. Unless, and in fact I'll say only if, your company is a hot startup revolutionizing file system semantics.
More generally, do not be clever about solving problems outside your bailiwick. Unless you want to blog about it and misattribute blame to something like fixing unit tests. (Aside: sounds like the unit tests also had unchecked assumptions.)
All shared code should have a maintainer, and the maintainer should be responsible for updates. If that person leaves then someone else should have to take over that responsibility.
In the case of the problem in the article it should be a very simple matter of raising a high priority bug ticket to fix the issue, and the maintainer then informing users of the library that they need to update their dependencies. It never works like that though.
I think the real answer is to decide on a strategy and then put healthy process in place to mitigate the downsides. In the case of sharing code across the company, make sure there are 2+ maintainers. This sort of succession planning is common. It is not foolproof, but it does mitigate the issue you raised.
Isn't this really a tooling problem? I can't imagine any environment in which I can't instantly find all callers/users of a shared package. The problem I always have is that there are too many [known] callers! Impact is still unknown because you can't always depend on unit and other test to uncover complex issues unforeseen and unknown until they actually crop up. But that's why you have a staging environment.
It's better than the alternative of not sharing code.
Some complex things need to be shared, but something like a library to make directory structures doesn't. It's fine if teams just write their own, or use one from outside the company. At least that way any issues are limited to only impacting that team, and in the long term you end up with much more maintainable apps.
Shared code that isn't treated like an external library(with proper, defined maintainers) is, in my experience, some of the worst technical debt.
As others comments point out, doing this well is subtle and tricky. This is absolutely the kind of thing that individual teams ought not have to maintain their own copies of.
Agree the best solution would be for this to be baked into the language, or failing that a well-known OSS library.
But if you don't have either, a shared company library is better than the duplication IMO. It does require a company culture that's able to invest in infrastructure, but I think you need that, especially if you're working with languages like C that don't come with as many "batteries included".
All the people who spent that last week or two hunting down places where log4j got imported by dependencies like Springboot or Grails are crying into their Xmas whisky at this…
Avoiding the problems one can run into with a shared codebase by not sharing at all is the worst solution.
Instead you end up in a situation where everyone is responsible for everything, which also means everyone is responsible for nothing.
All code should have a maintainer.
Low-level libraries that are used all over the company should probably have a strict code review process that's overseen by a group of experienced maintainers who have a good knowledge of security, performance, etc.
What? We are 7 people, and have a shared library for filesystem work.
(Since Java 8 about half of it is no longer needed, as it's included, and we replace usage with the standard library as we update projects.)
Google's https://abseil.io and Facebook's https://github.com/facebook/folly come to mind.
Aren't standard I/O functions also vulnerable if you don't sanitize your inputs? You can overwrite data and do all sorts of stuff. Sure forking a subprocess is more dangerous, but I think the real issue here is lack of input sanitization when calling OS functions, not the system() call per se.
Leverage a lookup that says user input “../../../root” == code generated directory path.
You might need some additional checks, like for ../ and symlinks, but you need these regardless whether you execve or write your own mkdirp().
Don't cripple your standard library. If C had a function for this super common need then this problem would never happen.
> That's how it happens: a tiny little change flings the door wide open. Someone solves their own local problem and misses the bigger picture.
feels like an opening to say "...which is why we mandate code review to try and prevent situations where a single person's lack of perspective gets shipped." Of course, that's banking on the reviewer(s) having a broader perspective, so it's only a probabilistic mitigation, but it beats nothing.
Code review only works well to prevent this sort of thing if you have designated owners for each library/feature, who are on the hook for the robustness/security/privacy thereof, and whose signoff is mandatory.
>LangSec regards the Internet insecurity epidemic as a consequence of ad hoc input handling. LangSec posits that the only path to trustworthy computer software that takes untrusted inputs is treating all valid or expected inputs as a formal language, and the respective input-handling routine as a parser for that language. Only then can any correctness guarantees be assured for the input-handling code. Ambiguity of message/protocol specification is insecurity; ad hoc parsing is an engine of exploitation; overly complex syntax can make judging security properties of input impractical or even undecidable.
>LangSec explains why ad hoc "input sanitization", "sanity checking", and other advice to be more careful with inputs is not enough, and why numerous secure programming initiatives have not ended input-driven exploitation. LangSec is also a code and protocol auditing methodology.
This is so basic; why do people keep getting it wrong?
From my point of view, any API which accepts special strings from users is a massive burden and should be extremely suspect when used in an automatic fashion.
Sure, the shell is nice when you're interacting with it, but calling the shell from your own program is crazy. Similarly, the fact that databases don't offer any structured query fomat and insist on plain text SQL (even with the kludge of prepared statements) is a horrible idea, that has bit everyone time and time again.
Not doing it is just plain incompetence.
You could replace the call to `mkdir` with a `psql` call and have the same security hole. The primary issue is with using a shell/subprocess.
Maybe you could make the case that "there tend to be better in-language libs for dealing with databases than filesystems". Not sure that's true, even if it is it's sort of a secondary lesson.
- shell=True: https://semgrep.dev/r?q=python.lang.security.audit.subproces...
- system-like calls with a non-static argument: https://semgrep.dev/r?q=python.lang.security.audit.dangerous...
Custom rules can be written for additional patterns of concern (or specific/uncommon/private APIs) too.
https://github.com/elanning/checkr
It's a nice inbetween solution for quick stuff not worth writing a full static analysis plugin for.
You are accepting unsafe input, and trying to work around that without making the input safe.
What you should be doing: taking the raw path string and parsing it. Defining via the parser what the form of a permitted path is. Either the input data matches this pattern, in which case it almost doesn't matter how you turn it into directories, or it does not, in which case you can reject it as garbage.
This seems like the kind of thing that if done well, could eliminate entire classes of bugs without being too burdensome.
You'd define a class "SanitizedStr" (or in this particular case "Path") and have all path operations work on that.
Python's pathlib sort of does this, although there's still attacks possible with stuff like joining with an absolute path.
https://ballerina.io/1.0/learn/by-example/taint-checking.htm...
p3rl.org/File::Spec#no_upwards - after calling splitpath and splitdir from the same module - is very much my friend.
(or for advanced mode, Path::Tiny, possibly with the help of App::FatPacker to condense back down to a single script if you're writing something you need to be able to copy around without thinking about dependencies)
Specialized algorithms; time/date calculations; complex custom business logic shared across the company; code generation libraries that generate code following best practices. These aren't always easy to get right.
But left padding strings or creating directories? These are less than 20 lines of code. The cost of using a library does not outweigh the risks when the benefit is that low.
There's tons and tons of different possible <20 line implementations for creating a directory + parents, many of which likely have subtle (or not-so-subtle) bugs.
Unit tests shouldn’t be creating directories in the first place - any outside interaction ought to be mocked out anyway.
Just in case anyone missed it: that's pretty much exactly the same thing that happened with the recent Log4Shell disaster.
Someone wanted to have a config value from JNDI in their logs and thought it would be cool to have log4j's string interpolation support that directly, found that it was easy to implement, and submitted a patch, which was accepted without any discussion.