1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
namespace WyriHaximus\Psr15\EtcPasswd; |
4
|
|
|
|
5
|
|
|
use Psr\Http\Message\ResponseInterface; |
6
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
7
|
|
|
use Psr\Http\Server\MiddlewareInterface; |
8
|
|
|
use Psr\Http\Server\RequestHandlerInterface; |
9
|
|
|
use Zend\Diactoros\Response; |
10
|
|
|
use Zend\Diactoros\Stream; |
11
|
|
|
|
12
|
|
|
final class EtcPasswdMiddleware implements MiddlewareInterface |
13
|
|
|
{ |
14
|
|
|
/** |
15
|
|
|
* @var string |
16
|
|
|
*/ |
17
|
|
|
private $passwdContents = ''; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* @var string |
21
|
|
|
*/ |
22
|
|
|
private $shadowContents = ''; |
23
|
|
|
|
24
|
14 |
|
public function __construct(iterable $users) |
25
|
|
|
{ |
26
|
14 |
|
$this->passwdContents = \implode( |
27
|
14 |
|
\PHP_EOL, |
28
|
14 |
|
\iterator_to_array($this->createPasswdContents($users)) |
29
|
|
|
); |
30
|
14 |
|
$this->shadowContents = \implode( |
31
|
14 |
|
\PHP_EOL, |
32
|
14 |
|
\iterator_to_array($this->createShadowContents($users)) |
33
|
|
|
); |
34
|
14 |
|
} |
35
|
|
|
|
36
|
14 |
|
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface |
37
|
|
|
{ |
38
|
14 |
|
if ($request->getMethod() === 'GET' && $request->getUri()->getPath() === '/etc/passwd') { |
39
|
2 |
|
return $this->createResponse($this->passwdContents); |
40
|
|
|
} |
41
|
|
|
|
42
|
12 |
|
if ($request->getMethod() === 'GET' && $request->getUri()->getPath() === '/etc/shadow') { |
43
|
2 |
|
return $this->createResponse($this->shadowContents); |
44
|
|
|
} |
45
|
|
|
|
46
|
10 |
|
return $handler->handle($request); |
47
|
|
|
} |
48
|
|
|
|
49
|
14 |
|
private function createPasswdContents(iterable $users): iterable |
50
|
|
|
{ |
51
|
14 |
|
foreach ($users as $user => $password) { |
52
|
4 |
|
yield $user . ':x:' . \crc32($user) . ':0:99999:7:::'; |
53
|
|
|
} |
54
|
14 |
|
} |
55
|
|
|
|
56
|
14 |
|
private function createShadowContents(iterable $users): iterable |
57
|
|
|
{ |
58
|
14 |
|
foreach ($users as $user => $password) { |
59
|
4 |
|
yield $user . ':$1$$' . \base64_encode(\md5($password)) . ':' . \crc32($user) . ':0:99999:7:::'; |
60
|
|
|
} |
61
|
14 |
|
} |
62
|
|
|
|
63
|
4 |
|
private function createResponse(string $contents): ResponseInterface |
64
|
|
|
{ |
65
|
4 |
|
$body = new Stream('php://temp', 'wb+'); |
66
|
4 |
|
$body->write($contents); |
67
|
4 |
|
$body->rewind(); |
68
|
|
|
|
69
|
4 |
|
return (new Response())-> |
70
|
4 |
|
withStatus(200)-> |
71
|
4 |
|
withHeader('Content-Type', 'text/plain')-> |
72
|
4 |
|
withBody($body); |
73
|
|
|
} |
74
|
|
|
} |
75
|
|
|
|