1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
namespace WyriHaximus\Psr15\EtcPasswd; |
4
|
|
|
|
5
|
|
|
use Interop\Http\Server\MiddlewareInterface; |
6
|
|
|
use Interop\Http\Server\RequestHandlerInterface; |
7
|
|
|
use Psr\Http\Message\ResponseInterface; |
8
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
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
|
|
|
public function __construct(iterable $users) |
25
|
|
|
{ |
26
|
|
|
$this->passwdContents = implode( |
27
|
|
|
PHP_EOL, |
28
|
|
|
iterator_to_array($this->createPasswdContents($users)) |
29
|
|
|
); |
30
|
|
|
$this->shadowContents = implode( |
31
|
|
|
PHP_EOL, |
32
|
|
|
iterator_to_array($this->createShadowContents($users)) |
33
|
|
|
); |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface |
37
|
|
|
{ |
38
|
|
View Code Duplication |
if ($request->getMethod() === 'GET' && $request->getUri()->getPath() === '/etc/passwd') { |
|
|
|
|
39
|
|
|
return $this->createResponse($this->passwdContents); |
40
|
|
|
} |
41
|
|
|
|
42
|
|
View Code Duplication |
if ($request->getMethod() === 'GET' && $request->getUri()->getPath() === '/etc/shadow') { |
|
|
|
|
43
|
|
|
return $this->createResponse($this->shadowContents); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
return $handler->handle($request); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
private function createPasswdContents(iterable $users): iterable |
50
|
|
|
{ |
51
|
|
|
foreach ($users as $user => $password) { |
52
|
|
|
yield $user . ':x:' . crc32($user) . ':0:99999:7:::'; |
53
|
|
|
} |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
private function createShadowContents(iterable $users): iterable |
57
|
|
|
{ |
58
|
|
|
foreach ($users as $user => $password) { |
59
|
|
|
yield $user . ':$1$$' . base64_encode(md5($password)) . ':' . crc32($user) . ':0:99999:7:::'; |
60
|
|
|
} |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
private function createResponse(string $contents): ResponseInterface |
64
|
|
|
{ |
65
|
|
|
$body = new Stream('php://temp', 'wb+'); |
66
|
|
|
$body->write($contents); |
67
|
|
|
$body->rewind(); |
68
|
|
|
|
69
|
|
|
return (new Response())-> |
70
|
|
|
withStatus(200)-> |
71
|
|
|
withHeader('Content-Type', 'text/plain')-> |
72
|
|
|
withBody($body); |
73
|
|
|
} |
74
|
|
|
} |
75
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.