Completed
Pull Request — master (#3233)
by Christoph
95:52 queued 83:56
created
lib/private/Security/CSRF/CsrfTokenGenerator.php 1 patch
Indentation   +17 added lines, -17 removed lines patch added patch discarded remove patch
@@ -31,23 +31,23 @@
 block discarded – undo
31 31
  * @package OC\Security\CSRF
32 32
  */
33 33
 class CsrfTokenGenerator {
34
-	/** @var ISecureRandom  */
35
-	private $random;
34
+    /** @var ISecureRandom  */
35
+    private $random;
36 36
 
37
-	/**
38
-	 * @param ISecureRandom $random
39
-	 */
40
-	public function __construct(ISecureRandom $random) {
41
-		$this->random = $random;
42
-	}
37
+    /**
38
+     * @param ISecureRandom $random
39
+     */
40
+    public function __construct(ISecureRandom $random) {
41
+        $this->random = $random;
42
+    }
43 43
 
44
-	/**
45
-	 * Generate a new CSRF token.
46
-	 *
47
-	 * @param int $length Length of the token in characters.
48
-	 * @return string
49
-	 */
50
-	public function generateToken($length = 32) {
51
-		return $this->random->generate($length);
52
-	}
44
+    /**
45
+     * Generate a new CSRF token.
46
+     *
47
+     * @param int $length Length of the token in characters.
48
+     * @return string
49
+     */
50
+    public function generateToken($length = 32) {
51
+        return $this->random->generate($length);
52
+    }
53 53
 }
Please login to merge, or discard this patch.
lib/private/Security/Crypto.php 1 patch
Indentation   +88 added lines, -88 removed lines patch added patch discarded remove patch
@@ -43,93 +43,93 @@
 block discarded – undo
43 43
  * @package OC\Security
44 44
  */
45 45
 class Crypto implements ICrypto {
46
-	/** @var AES $cipher */
47
-	private $cipher;
48
-	/** @var int */
49
-	private $ivLength = 16;
50
-	/** @var IConfig */
51
-	private $config;
52
-	/** @var ISecureRandom */
53
-	private $random;
54
-
55
-	/**
56
-	 * @param IConfig $config
57
-	 * @param ISecureRandom $random
58
-	 */
59
-	function __construct(IConfig $config, ISecureRandom $random) {
60
-		$this->cipher = new AES();
61
-		$this->config = $config;
62
-		$this->random = $random;
63
-	}
64
-
65
-	/**
66
-	 * @param string $message The message to authenticate
67
-	 * @param string $password Password to use (defaults to `secret` in config.php)
68
-	 * @return string Calculated HMAC
69
-	 */
70
-	public function calculateHMAC($message, $password = '') {
71
-		if($password === '') {
72
-			$password = $this->config->getSystemValue('secret');
73
-		}
74
-
75
-		// Append an "a" behind the password and hash it to prevent reusing the same password as for encryption
76
-		$password = hash('sha512', $password . 'a');
77
-
78
-		$hash = new Hash('sha512');
79
-		$hash->setKey($password);
80
-		return $hash->hash($message);
81
-	}
82
-
83
-	/**
84
-	 * Encrypts a value and adds an HMAC (Encrypt-Then-MAC)
85
-	 * @param string $plaintext
86
-	 * @param string $password Password to encrypt, if not specified the secret from config.php will be taken
87
-	 * @return string Authenticated ciphertext
88
-	 */
89
-	public function encrypt($plaintext, $password = '') {
90
-		if($password === '') {
91
-			$password = $this->config->getSystemValue('secret');
92
-		}
93
-		$this->cipher->setPassword($password);
94
-
95
-		$iv = $this->random->generate($this->ivLength);
96
-		$this->cipher->setIV($iv);
97
-
98
-		$ciphertext = bin2hex($this->cipher->encrypt($plaintext));
99
-		$hmac = bin2hex($this->calculateHMAC($ciphertext.$iv, $password));
100
-
101
-		return $ciphertext.'|'.$iv.'|'.$hmac;
102
-	}
103
-
104
-	/**
105
-	 * Decrypts a value and verifies the HMAC (Encrypt-Then-Mac)
106
-	 * @param string $authenticatedCiphertext
107
-	 * @param string $password Password to encrypt, if not specified the secret from config.php will be taken
108
-	 * @return string plaintext
109
-	 * @throws \Exception If the HMAC does not match
110
-	 */
111
-	public function decrypt($authenticatedCiphertext, $password = '') {
112
-		if($password === '') {
113
-			$password = $this->config->getSystemValue('secret');
114
-		}
115
-		$this->cipher->setPassword($password);
116
-
117
-		$parts = explode('|', $authenticatedCiphertext);
118
-		if(sizeof($parts) !== 3) {
119
-			throw new \Exception('Authenticated ciphertext could not be decoded.');
120
-		}
121
-
122
-		$ciphertext = hex2bin($parts[0]);
123
-		$iv = $parts[1];
124
-		$hmac = hex2bin($parts[2]);
125
-
126
-		$this->cipher->setIV($iv);
127
-
128
-		if(!hash_equals($this->calculateHMAC($parts[0].$parts[1], $password), $hmac)) {
129
-			throw new \Exception('HMAC does not match.');
130
-		}
131
-
132
-		return $this->cipher->decrypt($ciphertext);
133
-	}
46
+    /** @var AES $cipher */
47
+    private $cipher;
48
+    /** @var int */
49
+    private $ivLength = 16;
50
+    /** @var IConfig */
51
+    private $config;
52
+    /** @var ISecureRandom */
53
+    private $random;
54
+
55
+    /**
56
+     * @param IConfig $config
57
+     * @param ISecureRandom $random
58
+     */
59
+    function __construct(IConfig $config, ISecureRandom $random) {
60
+        $this->cipher = new AES();
61
+        $this->config = $config;
62
+        $this->random = $random;
63
+    }
64
+
65
+    /**
66
+     * @param string $message The message to authenticate
67
+     * @param string $password Password to use (defaults to `secret` in config.php)
68
+     * @return string Calculated HMAC
69
+     */
70
+    public function calculateHMAC($message, $password = '') {
71
+        if($password === '') {
72
+            $password = $this->config->getSystemValue('secret');
73
+        }
74
+
75
+        // Append an "a" behind the password and hash it to prevent reusing the same password as for encryption
76
+        $password = hash('sha512', $password . 'a');
77
+
78
+        $hash = new Hash('sha512');
79
+        $hash->setKey($password);
80
+        return $hash->hash($message);
81
+    }
82
+
83
+    /**
84
+     * Encrypts a value and adds an HMAC (Encrypt-Then-MAC)
85
+     * @param string $plaintext
86
+     * @param string $password Password to encrypt, if not specified the secret from config.php will be taken
87
+     * @return string Authenticated ciphertext
88
+     */
89
+    public function encrypt($plaintext, $password = '') {
90
+        if($password === '') {
91
+            $password = $this->config->getSystemValue('secret');
92
+        }
93
+        $this->cipher->setPassword($password);
94
+
95
+        $iv = $this->random->generate($this->ivLength);
96
+        $this->cipher->setIV($iv);
97
+
98
+        $ciphertext = bin2hex($this->cipher->encrypt($plaintext));
99
+        $hmac = bin2hex($this->calculateHMAC($ciphertext.$iv, $password));
100
+
101
+        return $ciphertext.'|'.$iv.'|'.$hmac;
102
+    }
103
+
104
+    /**
105
+     * Decrypts a value and verifies the HMAC (Encrypt-Then-Mac)
106
+     * @param string $authenticatedCiphertext
107
+     * @param string $password Password to encrypt, if not specified the secret from config.php will be taken
108
+     * @return string plaintext
109
+     * @throws \Exception If the HMAC does not match
110
+     */
111
+    public function decrypt($authenticatedCiphertext, $password = '') {
112
+        if($password === '') {
113
+            $password = $this->config->getSystemValue('secret');
114
+        }
115
+        $this->cipher->setPassword($password);
116
+
117
+        $parts = explode('|', $authenticatedCiphertext);
118
+        if(sizeof($parts) !== 3) {
119
+            throw new \Exception('Authenticated ciphertext could not be decoded.');
120
+        }
121
+
122
+        $ciphertext = hex2bin($parts[0]);
123
+        $iv = $parts[1];
124
+        $hmac = hex2bin($parts[2]);
125
+
126
+        $this->cipher->setIV($iv);
127
+
128
+        if(!hash_equals($this->calculateHMAC($parts[0].$parts[1], $password), $hmac)) {
129
+            throw new \Exception('HMAC does not match.');
130
+        }
131
+
132
+        return $this->cipher->decrypt($ciphertext);
133
+    }
134 134
 
135 135
 }
Please login to merge, or discard this patch.
lib/private/Security/SecureRandom.php 1 patch
Indentation   +44 added lines, -44 removed lines patch added patch discarded remove patch
@@ -37,51 +37,51 @@
 block discarded – undo
37 37
  * @package OC\Security
38 38
  */
39 39
 class SecureRandom implements ISecureRandom {
40
-	/**
41
-	 * Convenience method to get a low strength random number generator.
42
-	 *
43
-	 * Low Strength should be used anywhere that random strings are needed
44
-	 * in a non-cryptographical setting. They are not strong enough to be
45
-	 * used as keys or salts. They are however useful for one-time use tokens.
46
-	 *
47
-	 * @deprecated 9.0.0 Use \OC\Security\SecureRandom::generate directly or random_bytes() / random_int()
48
-	 * @return $this
49
-	 */
50
-	public function getLowStrengthGenerator() {
51
-		return $this;
52
-	}
40
+    /**
41
+     * Convenience method to get a low strength random number generator.
42
+     *
43
+     * Low Strength should be used anywhere that random strings are needed
44
+     * in a non-cryptographical setting. They are not strong enough to be
45
+     * used as keys or salts. They are however useful for one-time use tokens.
46
+     *
47
+     * @deprecated 9.0.0 Use \OC\Security\SecureRandom::generate directly or random_bytes() / random_int()
48
+     * @return $this
49
+     */
50
+    public function getLowStrengthGenerator() {
51
+        return $this;
52
+    }
53 53
 
54
-	/**
55
-	 * Convenience method to get a medium strength random number generator.
56
-	 *
57
-	 * Medium Strength should be used for most needs of a cryptographic nature.
58
-	 * They are strong enough to be used as keys and salts. However, they do
59
-	 * take some time and resources to generate, so they should not be over-used
60
-	 *
61
-	 * @deprecated 9.0.0 Use \OC\Security\SecureRandom::generate directly or random_bytes() / random_int()
62
-	 * @return $this
63
-	 */
64
-	public function getMediumStrengthGenerator() {
65
-		return $this;
66
-	}
54
+    /**
55
+     * Convenience method to get a medium strength random number generator.
56
+     *
57
+     * Medium Strength should be used for most needs of a cryptographic nature.
58
+     * They are strong enough to be used as keys and salts. However, they do
59
+     * take some time and resources to generate, so they should not be over-used
60
+     *
61
+     * @deprecated 9.0.0 Use \OC\Security\SecureRandom::generate directly or random_bytes() / random_int()
62
+     * @return $this
63
+     */
64
+    public function getMediumStrengthGenerator() {
65
+        return $this;
66
+    }
67 67
 
68
-	/**
69
-	 * Generate a random string of specified length.
70
-	 * @param int $length The length of the generated string
71
-	 * @param string $characters An optional list of characters to use if no character list is
72
-	 * 							specified all valid base64 characters are used.
73
-	 * @return string
74
-	 */
75
-	public function generate($length,
76
-							 $characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/') {
77
-		$maxCharIndex = strlen($characters) - 1;
78
-		$randomString = '';
68
+    /**
69
+     * Generate a random string of specified length.
70
+     * @param int $length The length of the generated string
71
+     * @param string $characters An optional list of characters to use if no character list is
72
+     * 							specified all valid base64 characters are used.
73
+     * @return string
74
+     */
75
+    public function generate($length,
76
+                                $characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/') {
77
+        $maxCharIndex = strlen($characters) - 1;
78
+        $randomString = '';
79 79
 
80
-		while($length > 0) {
81
-			$randomNumber = \random_int(0, $maxCharIndex);
82
-			$randomString .= $characters[$randomNumber];
83
-			$length--;
84
-		}
85
-		return $randomString;
86
-	}
80
+        while($length > 0) {
81
+            $randomNumber = \random_int(0, $maxCharIndex);
82
+            $randomString .= $characters[$randomNumber];
83
+            $length--;
84
+        }
85
+        return $randomString;
86
+    }
87 87
 }
Please login to merge, or discard this patch.
lib/private/Security/Certificate.php 1 patch
Indentation   +100 added lines, -100 removed lines patch added patch discarded remove patch
@@ -27,104 +27,104 @@
 block discarded – undo
27 27
 use OCP\ICertificate;
28 28
 
29 29
 class Certificate implements ICertificate {
30
-	protected $name;
31
-
32
-	protected $commonName;
33
-
34
-	protected $organization;
35
-
36
-	protected $serial;
37
-
38
-	protected $issueDate;
39
-
40
-	protected $expireDate;
41
-
42
-	protected $issuerName;
43
-
44
-	protected $issuerOrganization;
45
-
46
-	/**
47
-	 * @param string $data base64 encoded certificate
48
-	 * @param string $name
49
-	 * @throws \Exception If the certificate could not get parsed
50
-	 */
51
-	public function __construct($data, $name) {
52
-		$this->name = $name;
53
-		$gmt = new \DateTimeZone('GMT');
54
-
55
-		// If string starts with "file://" ignore the certificate
56
-		$query = 'file://';
57
-		if(strtolower(substr($data, 0, strlen($query))) === $query) {
58
-			throw new \Exception('Certificate could not get parsed.');
59
-		}
60
-
61
-		$info = openssl_x509_parse($data);
62
-		if(!is_array($info)) {
63
-			throw new \Exception('Certificate could not get parsed.');
64
-		}
65
-
66
-		$this->commonName = isset($info['subject']['CN']) ? $info['subject']['CN'] : null;
67
-		$this->organization = isset($info['subject']['O']) ? $info['subject']['O'] : null;
68
-		$this->issueDate = new \DateTime('@' . $info['validFrom_time_t'], $gmt);
69
-		$this->expireDate = new \DateTime('@' . $info['validTo_time_t'], $gmt);
70
-		$this->issuerName = isset($info['issuer']['CN']) ? $info['issuer']['CN'] : null;
71
-		$this->issuerOrganization = isset($info['issuer']['O']) ? $info['issuer']['O'] : null;
72
-	}
73
-
74
-	/**
75
-	 * @return string
76
-	 */
77
-	public function getName() {
78
-		return $this->name;
79
-	}
80
-
81
-	/**
82
-	 * @return string|null
83
-	 */
84
-	public function getCommonName() {
85
-		return $this->commonName;
86
-	}
87
-
88
-	/**
89
-	 * @return string
90
-	 */
91
-	public function getOrganization() {
92
-		return $this->organization;
93
-	}
94
-
95
-	/**
96
-	 * @return \DateTime
97
-	 */
98
-	public function getIssueDate() {
99
-		return $this->issueDate;
100
-	}
101
-
102
-	/**
103
-	 * @return \DateTime
104
-	 */
105
-	public function getExpireDate() {
106
-		return $this->expireDate;
107
-	}
108
-
109
-	/**
110
-	 * @return bool
111
-	 */
112
-	public function isExpired() {
113
-		$now = new \DateTime();
114
-		return $this->issueDate > $now or $now > $this->expireDate;
115
-	}
116
-
117
-	/**
118
-	 * @return string|null
119
-	 */
120
-	public function getIssuerName() {
121
-		return $this->issuerName;
122
-	}
123
-
124
-	/**
125
-	 * @return string|null
126
-	 */
127
-	public function getIssuerOrganization() {
128
-		return $this->issuerOrganization;
129
-	}
30
+    protected $name;
31
+
32
+    protected $commonName;
33
+
34
+    protected $organization;
35
+
36
+    protected $serial;
37
+
38
+    protected $issueDate;
39
+
40
+    protected $expireDate;
41
+
42
+    protected $issuerName;
43
+
44
+    protected $issuerOrganization;
45
+
46
+    /**
47
+     * @param string $data base64 encoded certificate
48
+     * @param string $name
49
+     * @throws \Exception If the certificate could not get parsed
50
+     */
51
+    public function __construct($data, $name) {
52
+        $this->name = $name;
53
+        $gmt = new \DateTimeZone('GMT');
54
+
55
+        // If string starts with "file://" ignore the certificate
56
+        $query = 'file://';
57
+        if(strtolower(substr($data, 0, strlen($query))) === $query) {
58
+            throw new \Exception('Certificate could not get parsed.');
59
+        }
60
+
61
+        $info = openssl_x509_parse($data);
62
+        if(!is_array($info)) {
63
+            throw new \Exception('Certificate could not get parsed.');
64
+        }
65
+
66
+        $this->commonName = isset($info['subject']['CN']) ? $info['subject']['CN'] : null;
67
+        $this->organization = isset($info['subject']['O']) ? $info['subject']['O'] : null;
68
+        $this->issueDate = new \DateTime('@' . $info['validFrom_time_t'], $gmt);
69
+        $this->expireDate = new \DateTime('@' . $info['validTo_time_t'], $gmt);
70
+        $this->issuerName = isset($info['issuer']['CN']) ? $info['issuer']['CN'] : null;
71
+        $this->issuerOrganization = isset($info['issuer']['O']) ? $info['issuer']['O'] : null;
72
+    }
73
+
74
+    /**
75
+     * @return string
76
+     */
77
+    public function getName() {
78
+        return $this->name;
79
+    }
80
+
81
+    /**
82
+     * @return string|null
83
+     */
84
+    public function getCommonName() {
85
+        return $this->commonName;
86
+    }
87
+
88
+    /**
89
+     * @return string
90
+     */
91
+    public function getOrganization() {
92
+        return $this->organization;
93
+    }
94
+
95
+    /**
96
+     * @return \DateTime
97
+     */
98
+    public function getIssueDate() {
99
+        return $this->issueDate;
100
+    }
101
+
102
+    /**
103
+     * @return \DateTime
104
+     */
105
+    public function getExpireDate() {
106
+        return $this->expireDate;
107
+    }
108
+
109
+    /**
110
+     * @return bool
111
+     */
112
+    public function isExpired() {
113
+        $now = new \DateTime();
114
+        return $this->issueDate > $now or $now > $this->expireDate;
115
+    }
116
+
117
+    /**
118
+     * @return string|null
119
+     */
120
+    public function getIssuerName() {
121
+        return $this->issuerName;
122
+    }
123
+
124
+    /**
125
+     * @return string|null
126
+     */
127
+    public function getIssuerOrganization() {
128
+        return $this->issuerOrganization;
129
+    }
130 130
 }
Please login to merge, or discard this patch.
lib/private/Security/IdentityProof/Signer.php 1 patch
Indentation   +66 added lines, -66 removed lines patch added patch discarded remove patch
@@ -26,76 +26,76 @@
 block discarded – undo
26 26
 use OCP\IUserManager;
27 27
 
28 28
 class Signer {
29
-	/** @var Manager */
30
-	private $keyManager;
31
-	/** @var ITimeFactory */
32
-	private $timeFactory;
33
-	/** @var IUserManager */
34
-	private $userManager;
29
+    /** @var Manager */
30
+    private $keyManager;
31
+    /** @var ITimeFactory */
32
+    private $timeFactory;
33
+    /** @var IUserManager */
34
+    private $userManager;
35 35
 
36
-	/**
37
-	 * @param Manager $keyManager
38
-	 * @param ITimeFactory $timeFactory
39
-	 * @param IUserManager $userManager
40
-	 */
41
-	public function __construct(Manager $keyManager,
42
-								ITimeFactory $timeFactory,
43
-								IUserManager $userManager) {
44
-		$this->keyManager = $keyManager;
45
-		$this->timeFactory = $timeFactory;
46
-		$this->userManager = $userManager;
47
-	}
36
+    /**
37
+     * @param Manager $keyManager
38
+     * @param ITimeFactory $timeFactory
39
+     * @param IUserManager $userManager
40
+     */
41
+    public function __construct(Manager $keyManager,
42
+                                ITimeFactory $timeFactory,
43
+                                IUserManager $userManager) {
44
+        $this->keyManager = $keyManager;
45
+        $this->timeFactory = $timeFactory;
46
+        $this->userManager = $userManager;
47
+    }
48 48
 
49
-	/**
50
-	 * Returns a signed blob for $data
51
-	 *
52
-	 * @param string $type
53
-	 * @param array $data
54
-	 * @param IUser $user
55
-	 * @return array ['message', 'signature']
56
-	 */
57
-	public function sign($type, array $data, IUser $user) {
58
-		$privateKey = $this->keyManager->getKey($user)->getPrivate();
59
-		$data = [
60
-			'data' => $data,
61
-			'type' => $type,
62
-			'signer' => $user->getCloudId(),
63
-			'timestamp' => $this->timeFactory->getTime(),
64
-		];
65
-		openssl_sign(json_encode($data), $signature, $privateKey, OPENSSL_ALGO_SHA512);
49
+    /**
50
+     * Returns a signed blob for $data
51
+     *
52
+     * @param string $type
53
+     * @param array $data
54
+     * @param IUser $user
55
+     * @return array ['message', 'signature']
56
+     */
57
+    public function sign($type, array $data, IUser $user) {
58
+        $privateKey = $this->keyManager->getKey($user)->getPrivate();
59
+        $data = [
60
+            'data' => $data,
61
+            'type' => $type,
62
+            'signer' => $user->getCloudId(),
63
+            'timestamp' => $this->timeFactory->getTime(),
64
+        ];
65
+        openssl_sign(json_encode($data), $signature, $privateKey, OPENSSL_ALGO_SHA512);
66 66
 
67
-		return [
68
-			'message' => $data,
69
-			'signature' => base64_encode($signature),
70
-		];
71
-	}
67
+        return [
68
+            'message' => $data,
69
+            'signature' => base64_encode($signature),
70
+        ];
71
+    }
72 72
 
73
-	/**
74
-	 * Whether the data is signed properly
75
-	 *
76
-	 * @param array $data
77
-	 * @return bool
78
-	 */
79
-	public function verify(array $data) {
80
-		if(isset($data['message'])
81
-			&& isset($data['signature'])
82
-			&& isset($data['message']['signer'])
83
-		) {
84
-			$location = strrpos($data['message']['signer'], '@');
85
-			$userId = substr($data['message']['signer'], 0, $location);
73
+    /**
74
+     * Whether the data is signed properly
75
+     *
76
+     * @param array $data
77
+     * @return bool
78
+     */
79
+    public function verify(array $data) {
80
+        if(isset($data['message'])
81
+            && isset($data['signature'])
82
+            && isset($data['message']['signer'])
83
+        ) {
84
+            $location = strrpos($data['message']['signer'], '@');
85
+            $userId = substr($data['message']['signer'], 0, $location);
86 86
 
87
-			$user = $this->userManager->get($userId);
88
-			if($user !== null) {
89
-				$key = $this->keyManager->getKey($user);
90
-				return (bool)openssl_verify(
91
-					json_encode($data['message']),
92
-					base64_decode($data['signature']),
93
-					$key->getPublic(),
94
-					OPENSSL_ALGO_SHA512
95
-				);
96
-			}
97
-		}
87
+            $user = $this->userManager->get($userId);
88
+            if($user !== null) {
89
+                $key = $this->keyManager->getKey($user);
90
+                return (bool)openssl_verify(
91
+                    json_encode($data['message']),
92
+                    base64_decode($data['signature']),
93
+                    $key->getPublic(),
94
+                    OPENSSL_ALGO_SHA512
95
+                );
96
+            }
97
+        }
98 98
 
99
-		return false;
100
-	}
99
+        return false;
100
+    }
101 101
 }
Please login to merge, or discard this patch.
lib/private/Security/IdentityProof/Key.php 1 patch
Indentation   +18 added lines, -18 removed lines patch added patch discarded remove patch
@@ -22,25 +22,25 @@
 block discarded – undo
22 22
 namespace OC\Security\IdentityProof;
23 23
 
24 24
 class Key {
25
-	/** @var string */
26
-	private $publicKey;
27
-	/** @var string */
28
-	private $privateKey;
25
+    /** @var string */
26
+    private $publicKey;
27
+    /** @var string */
28
+    private $privateKey;
29 29
 
30
-	/**
31
-	 * @param string $publicKey
32
-	 * @param string $privateKey
33
-	 */
34
-	public function __construct($publicKey, $privateKey) {
35
-		$this->publicKey = $publicKey;
36
-		$this->privateKey = $privateKey;
37
-	}
30
+    /**
31
+     * @param string $publicKey
32
+     * @param string $privateKey
33
+     */
34
+    public function __construct($publicKey, $privateKey) {
35
+        $this->publicKey = $publicKey;
36
+        $this->privateKey = $privateKey;
37
+    }
38 38
 
39
-	public function getPrivate() {
40
-		return $this->privateKey;
41
-	}
39
+    public function getPrivate() {
40
+        return $this->privateKey;
41
+    }
42 42
 
43
-	public function getPublic() {
44
-		return $this->publicKey;
45
-	}
43
+    public function getPublic() {
44
+        return $this->publicKey;
45
+    }
46 46
 }
Please login to merge, or discard this patch.
lib/private/Security/IdentityProof/Manager.php 1 patch
Indentation   +70 added lines, -70 removed lines patch added patch discarded remove patch
@@ -26,83 +26,83 @@
 block discarded – undo
26 26
 use OCP\Security\ICrypto;
27 27
 
28 28
 class Manager {
29
-	/** @var IAppData */
30
-	private $appData;
31
-	/** @var ICrypto */
32
-	private $crypto;
29
+    /** @var IAppData */
30
+    private $appData;
31
+    /** @var ICrypto */
32
+    private $crypto;
33 33
 
34
-	/**
35
-	 * @param IAppData $appData
36
-	 * @param ICrypto $crypto
37
-	 */
38
-	public function __construct(IAppData $appData,
39
-								ICrypto $crypto) {
40
-		$this->appData = $appData;
41
-		$this->crypto = $crypto;
42
-	}
34
+    /**
35
+     * @param IAppData $appData
36
+     * @param ICrypto $crypto
37
+     */
38
+    public function __construct(IAppData $appData,
39
+                                ICrypto $crypto) {
40
+        $this->appData = $appData;
41
+        $this->crypto = $crypto;
42
+    }
43 43
 
44
-	/**
45
-	 * Calls the openssl functions to generate a public and private key.
46
-	 * In a separate function for unit testing purposes.
47
-	 *
48
-	 * @return array [$publicKey, $privateKey]
49
-	 */
50
-	protected function generateKeyPair() {
51
-		$config = [
52
-			'digest_alg' => 'sha512',
53
-			'private_key_bits' => 2048,
54
-		];
44
+    /**
45
+     * Calls the openssl functions to generate a public and private key.
46
+     * In a separate function for unit testing purposes.
47
+     *
48
+     * @return array [$publicKey, $privateKey]
49
+     */
50
+    protected function generateKeyPair() {
51
+        $config = [
52
+            'digest_alg' => 'sha512',
53
+            'private_key_bits' => 2048,
54
+        ];
55 55
 
56
-		// Generate new key
57
-		$res = openssl_pkey_new($config);
58
-		openssl_pkey_export($res, $privateKey);
56
+        // Generate new key
57
+        $res = openssl_pkey_new($config);
58
+        openssl_pkey_export($res, $privateKey);
59 59
 
60
-		// Extract the public key from $res to $pubKey
61
-		$publicKey = openssl_pkey_get_details($res);
62
-		$publicKey = $publicKey['key'];
60
+        // Extract the public key from $res to $pubKey
61
+        $publicKey = openssl_pkey_get_details($res);
62
+        $publicKey = $publicKey['key'];
63 63
 
64
-		return [$publicKey, $privateKey];
65
-	}
64
+        return [$publicKey, $privateKey];
65
+    }
66 66
 
67
-	/**
68
-	 * Generate a key for $user
69
-	 * Note: If a key already exists it will be overwritten
70
-	 *
71
-	 * @param IUser $user
72
-	 * @return Key
73
-	 */
74
-	protected function generateKey(IUser $user) {
75
-		list($publicKey, $privateKey) = $this->generateKeyPair();
67
+    /**
68
+     * Generate a key for $user
69
+     * Note: If a key already exists it will be overwritten
70
+     *
71
+     * @param IUser $user
72
+     * @return Key
73
+     */
74
+    protected function generateKey(IUser $user) {
75
+        list($publicKey, $privateKey) = $this->generateKeyPair();
76 76
 
77
-		// Write the private and public key to the disk
78
-		try {
79
-			$this->appData->newFolder($user->getUID());
80
-		} catch (\Exception $e) {}
81
-		$folder = $this->appData->getFolder($user->getUID());
82
-		$folder->newFile('private')
83
-			->putContent($this->crypto->encrypt($privateKey));
84
-		$folder->newFile('public')
85
-			->putContent($publicKey);
77
+        // Write the private and public key to the disk
78
+        try {
79
+            $this->appData->newFolder($user->getUID());
80
+        } catch (\Exception $e) {}
81
+        $folder = $this->appData->getFolder($user->getUID());
82
+        $folder->newFile('private')
83
+            ->putContent($this->crypto->encrypt($privateKey));
84
+        $folder->newFile('public')
85
+            ->putContent($publicKey);
86 86
 
87
-		return new Key($publicKey, $privateKey);
88
-	}
87
+        return new Key($publicKey, $privateKey);
88
+    }
89 89
 
90
-	/**
91
-	 * Get public and private key for $user
92
-	 *
93
-	 * @param IUser $user
94
-	 * @return Key
95
-	 */
96
-	public function getKey(IUser $user) {
97
-		try {
98
-			$folder = $this->appData->getFolder($user->getUID());
99
-			$privateKey = $this->crypto->decrypt(
100
-				$folder->getFile('private')->getContent()
101
-			);
102
-			$publicKey = $folder->getFile('public')->getContent();
103
-			return new Key($publicKey, $privateKey);
104
-		} catch (\Exception $e) {
105
-			return $this->generateKey($user);
106
-		}
107
-	}
90
+    /**
91
+     * Get public and private key for $user
92
+     *
93
+     * @param IUser $user
94
+     * @return Key
95
+     */
96
+    public function getKey(IUser $user) {
97
+        try {
98
+            $folder = $this->appData->getFolder($user->getUID());
99
+            $privateKey = $this->crypto->decrypt(
100
+                $folder->getFile('private')->getContent()
101
+            );
102
+            $publicKey = $folder->getFile('public')->getContent();
103
+            return new Key($publicKey, $privateKey);
104
+        } catch (\Exception $e) {
105
+            return $this->generateKey($user);
106
+        }
107
+    }
108 108
 }
Please login to merge, or discard this patch.
lib/private/Security/CertificateManager.php 1 patch
Indentation   +237 added lines, -237 removed lines patch added patch discarded remove patch
@@ -36,242 +36,242 @@
 block discarded – undo
36 36
  * Manage trusted certificates for users
37 37
  */
38 38
 class CertificateManager implements ICertificateManager {
39
-	/**
40
-	 * @var string
41
-	 */
42
-	protected $uid;
43
-
44
-	/**
45
-	 * @var \OC\Files\View
46
-	 */
47
-	protected $view;
48
-
49
-	/**
50
-	 * @var IConfig
51
-	 */
52
-	protected $config;
53
-
54
-	/**
55
-	 * @var ILogger
56
-	 */
57
-	protected $logger;
58
-
59
-	/**
60
-	 * @param string $uid
61
-	 * @param \OC\Files\View $view relative to data/
62
-	 * @param IConfig $config
63
-	 * @param ILogger $logger
64
-	 */
65
-	public function __construct($uid, \OC\Files\View $view, IConfig $config, ILogger $logger) {
66
-		$this->uid = $uid;
67
-		$this->view = $view;
68
-		$this->config = $config;
69
-		$this->logger = $logger;
70
-	}
71
-
72
-	/**
73
-	 * Returns all certificates trusted by the user
74
-	 *
75
-	 * @return \OCP\ICertificate[]
76
-	 */
77
-	public function listCertificates() {
78
-
79
-		if (!$this->config->getSystemValue('installed', false)) {
80
-			return array();
81
-		}
82
-
83
-		$path = $this->getPathToCertificates() . 'uploads/';
84
-		if (!$this->view->is_dir($path)) {
85
-			return array();
86
-		}
87
-		$result = array();
88
-		$handle = $this->view->opendir($path);
89
-		if (!is_resource($handle)) {
90
-			return array();
91
-		}
92
-		while (false !== ($file = readdir($handle))) {
93
-			if ($file != '.' && $file != '..') {
94
-				try {
95
-					$result[] = new Certificate($this->view->file_get_contents($path . $file), $file);
96
-				} catch (\Exception $e) {
97
-				}
98
-			}
99
-		}
100
-		closedir($handle);
101
-		return $result;
102
-	}
103
-
104
-	/**
105
-	 * create the certificate bundle of all trusted certificated
106
-	 */
107
-	public function createCertificateBundle() {
108
-		$path = $this->getPathToCertificates();
109
-		$certs = $this->listCertificates();
110
-
111
-		if (!$this->view->file_exists($path)) {
112
-			$this->view->mkdir($path);
113
-		}
114
-
115
-		$defaultCertificates = file_get_contents(\OC::$SERVERROOT . '/resources/config/ca-bundle.crt');
116
-		if (strlen($defaultCertificates) < 1024) { // sanity check to verify that we have some content for our bundle
117
-			// log as exception so we have a stacktrace
118
-			$this->logger->logException(new \Exception('Shipped ca-bundle is empty, refusing to create certificate bundle'));
119
-			return;
120
-		}
121
-
122
-		$fhCerts = $this->view->fopen($path . '/rootcerts.crt', 'w');
123
-
124
-		// Write user certificates
125
-		foreach ($certs as $cert) {
126
-			$file = $path . '/uploads/' . $cert->getName();
127
-			$data = $this->view->file_get_contents($file);
128
-			if (strpos($data, 'BEGIN CERTIFICATE')) {
129
-				fwrite($fhCerts, $data);
130
-				fwrite($fhCerts, "\r\n");
131
-			}
132
-		}
133
-
134
-		// Append the default certificates
135
-		fwrite($fhCerts, $defaultCertificates);
136
-
137
-		// Append the system certificate bundle
138
-		$systemBundle = $this->getCertificateBundle(null);
139
-		if ($this->view->file_exists($systemBundle)) {
140
-			$systemCertificates = $this->view->file_get_contents($systemBundle);
141
-			fwrite($fhCerts, $systemCertificates);
142
-		}
143
-
144
-		fclose($fhCerts);
145
-	}
146
-
147
-	/**
148
-	 * Save the certificate and re-generate the certificate bundle
149
-	 *
150
-	 * @param string $certificate the certificate data
151
-	 * @param string $name the filename for the certificate
152
-	 * @return \OCP\ICertificate
153
-	 * @throws \Exception If the certificate could not get added
154
-	 */
155
-	public function addCertificate($certificate, $name) {
156
-		if (!Filesystem::isValidPath($name) or Filesystem::isFileBlacklisted($name)) {
157
-			throw new \Exception('Filename is not valid');
158
-		}
159
-
160
-		$dir = $this->getPathToCertificates() . 'uploads/';
161
-		if (!$this->view->file_exists($dir)) {
162
-			$this->view->mkdir($dir);
163
-		}
164
-
165
-		try {
166
-			$file = $dir . $name;
167
-			$certificateObject = new Certificate($certificate, $name);
168
-			$this->view->file_put_contents($file, $certificate);
169
-			$this->createCertificateBundle();
170
-			return $certificateObject;
171
-		} catch (\Exception $e) {
172
-			throw $e;
173
-		}
174
-
175
-	}
176
-
177
-	/**
178
-	 * Remove the certificate and re-generate the certificate bundle
179
-	 *
180
-	 * @param string $name
181
-	 * @return bool
182
-	 */
183
-	public function removeCertificate($name) {
184
-		if (!Filesystem::isValidPath($name)) {
185
-			return false;
186
-		}
187
-		$path = $this->getPathToCertificates() . 'uploads/';
188
-		if ($this->view->file_exists($path . $name)) {
189
-			$this->view->unlink($path . $name);
190
-			$this->createCertificateBundle();
191
-		}
192
-		return true;
193
-	}
194
-
195
-	/**
196
-	 * Get the path to the certificate bundle for this user
197
-	 *
198
-	 * @param string $uid (optional) user to get the certificate bundle for, use `null` to get the system bundle
199
-	 * @return string
200
-	 */
201
-	public function getCertificateBundle($uid = '') {
202
-		if ($uid === '') {
203
-			$uid = $this->uid;
204
-		}
205
-		return $this->getPathToCertificates($uid) . 'rootcerts.crt';
206
-	}
207
-
208
-	/**
209
-	 * Get the full local path to the certificate bundle for this user
210
-	 *
211
-	 * @param string $uid (optional) user to get the certificate bundle for, use `null` to get the system bundle
212
-	 * @return string
213
-	 */
214
-	public function getAbsoluteBundlePath($uid = '') {
215
-		if ($uid === '') {
216
-			$uid = $this->uid;
217
-		}
218
-		if ($this->needsRebundling($uid)) {
219
-			if (is_null($uid)) {
220
-				$manager = new CertificateManager(null, $this->view, $this->config, $this->logger);
221
-				$manager->createCertificateBundle();
222
-			} else {
223
-				$this->createCertificateBundle();
224
-			}
225
-		}
226
-		return $this->view->getLocalFile($this->getCertificateBundle($uid));
227
-	}
228
-
229
-	/**
230
-	 * @param string $uid (optional) user to get the certificate path for, use `null` to get the system path
231
-	 * @return string
232
-	 */
233
-	private function getPathToCertificates($uid = '') {
234
-		if ($uid === '') {
235
-			$uid = $this->uid;
236
-		}
237
-		$path = is_null($uid) ? '/files_external/' : '/' . $uid . '/files_external/';
238
-
239
-		return $path;
240
-	}
241
-
242
-	/**
243
-	 * Check if we need to re-bundle the certificates because one of the sources has updated
244
-	 *
245
-	 * @param string $uid (optional) user to get the certificate path for, use `null` to get the system path
246
-	 * @return bool
247
-	 */
248
-	private function needsRebundling($uid = '') {
249
-		if ($uid === '') {
250
-			$uid = $this->uid;
251
-		}
252
-		$sourceMTimes = [$this->getFilemtimeOfCaBundle()];
253
-		$targetBundle = $this->getCertificateBundle($uid);
254
-		if (!$this->view->file_exists($targetBundle)) {
255
-			return true;
256
-		}
257
-
258
-		if (!is_null($uid)) { // also depend on the system bundle
259
-			$sourceMTimes[] = $this->view->filemtime($this->getCertificateBundle(null));
260
-		}
261
-
262
-		$sourceMTime = array_reduce($sourceMTimes, function ($max, $mtime) {
263
-			return max($max, $mtime);
264
-		}, 0);
265
-		return $sourceMTime > $this->view->filemtime($targetBundle);
266
-	}
267
-
268
-	/**
269
-	 * get mtime of ca-bundle shipped by Nextcloud
270
-	 *
271
-	 * @return int
272
-	 */
273
-	protected function getFilemtimeOfCaBundle() {
274
-		return filemtime(\OC::$SERVERROOT . '/resources/config/ca-bundle.crt');
275
-	}
39
+    /**
40
+     * @var string
41
+     */
42
+    protected $uid;
43
+
44
+    /**
45
+     * @var \OC\Files\View
46
+     */
47
+    protected $view;
48
+
49
+    /**
50
+     * @var IConfig
51
+     */
52
+    protected $config;
53
+
54
+    /**
55
+     * @var ILogger
56
+     */
57
+    protected $logger;
58
+
59
+    /**
60
+     * @param string $uid
61
+     * @param \OC\Files\View $view relative to data/
62
+     * @param IConfig $config
63
+     * @param ILogger $logger
64
+     */
65
+    public function __construct($uid, \OC\Files\View $view, IConfig $config, ILogger $logger) {
66
+        $this->uid = $uid;
67
+        $this->view = $view;
68
+        $this->config = $config;
69
+        $this->logger = $logger;
70
+    }
71
+
72
+    /**
73
+     * Returns all certificates trusted by the user
74
+     *
75
+     * @return \OCP\ICertificate[]
76
+     */
77
+    public function listCertificates() {
78
+
79
+        if (!$this->config->getSystemValue('installed', false)) {
80
+            return array();
81
+        }
82
+
83
+        $path = $this->getPathToCertificates() . 'uploads/';
84
+        if (!$this->view->is_dir($path)) {
85
+            return array();
86
+        }
87
+        $result = array();
88
+        $handle = $this->view->opendir($path);
89
+        if (!is_resource($handle)) {
90
+            return array();
91
+        }
92
+        while (false !== ($file = readdir($handle))) {
93
+            if ($file != '.' && $file != '..') {
94
+                try {
95
+                    $result[] = new Certificate($this->view->file_get_contents($path . $file), $file);
96
+                } catch (\Exception $e) {
97
+                }
98
+            }
99
+        }
100
+        closedir($handle);
101
+        return $result;
102
+    }
103
+
104
+    /**
105
+     * create the certificate bundle of all trusted certificated
106
+     */
107
+    public function createCertificateBundle() {
108
+        $path = $this->getPathToCertificates();
109
+        $certs = $this->listCertificates();
110
+
111
+        if (!$this->view->file_exists($path)) {
112
+            $this->view->mkdir($path);
113
+        }
114
+
115
+        $defaultCertificates = file_get_contents(\OC::$SERVERROOT . '/resources/config/ca-bundle.crt');
116
+        if (strlen($defaultCertificates) < 1024) { // sanity check to verify that we have some content for our bundle
117
+            // log as exception so we have a stacktrace
118
+            $this->logger->logException(new \Exception('Shipped ca-bundle is empty, refusing to create certificate bundle'));
119
+            return;
120
+        }
121
+
122
+        $fhCerts = $this->view->fopen($path . '/rootcerts.crt', 'w');
123
+
124
+        // Write user certificates
125
+        foreach ($certs as $cert) {
126
+            $file = $path . '/uploads/' . $cert->getName();
127
+            $data = $this->view->file_get_contents($file);
128
+            if (strpos($data, 'BEGIN CERTIFICATE')) {
129
+                fwrite($fhCerts, $data);
130
+                fwrite($fhCerts, "\r\n");
131
+            }
132
+        }
133
+
134
+        // Append the default certificates
135
+        fwrite($fhCerts, $defaultCertificates);
136
+
137
+        // Append the system certificate bundle
138
+        $systemBundle = $this->getCertificateBundle(null);
139
+        if ($this->view->file_exists($systemBundle)) {
140
+            $systemCertificates = $this->view->file_get_contents($systemBundle);
141
+            fwrite($fhCerts, $systemCertificates);
142
+        }
143
+
144
+        fclose($fhCerts);
145
+    }
146
+
147
+    /**
148
+     * Save the certificate and re-generate the certificate bundle
149
+     *
150
+     * @param string $certificate the certificate data
151
+     * @param string $name the filename for the certificate
152
+     * @return \OCP\ICertificate
153
+     * @throws \Exception If the certificate could not get added
154
+     */
155
+    public function addCertificate($certificate, $name) {
156
+        if (!Filesystem::isValidPath($name) or Filesystem::isFileBlacklisted($name)) {
157
+            throw new \Exception('Filename is not valid');
158
+        }
159
+
160
+        $dir = $this->getPathToCertificates() . 'uploads/';
161
+        if (!$this->view->file_exists($dir)) {
162
+            $this->view->mkdir($dir);
163
+        }
164
+
165
+        try {
166
+            $file = $dir . $name;
167
+            $certificateObject = new Certificate($certificate, $name);
168
+            $this->view->file_put_contents($file, $certificate);
169
+            $this->createCertificateBundle();
170
+            return $certificateObject;
171
+        } catch (\Exception $e) {
172
+            throw $e;
173
+        }
174
+
175
+    }
176
+
177
+    /**
178
+     * Remove the certificate and re-generate the certificate bundle
179
+     *
180
+     * @param string $name
181
+     * @return bool
182
+     */
183
+    public function removeCertificate($name) {
184
+        if (!Filesystem::isValidPath($name)) {
185
+            return false;
186
+        }
187
+        $path = $this->getPathToCertificates() . 'uploads/';
188
+        if ($this->view->file_exists($path . $name)) {
189
+            $this->view->unlink($path . $name);
190
+            $this->createCertificateBundle();
191
+        }
192
+        return true;
193
+    }
194
+
195
+    /**
196
+     * Get the path to the certificate bundle for this user
197
+     *
198
+     * @param string $uid (optional) user to get the certificate bundle for, use `null` to get the system bundle
199
+     * @return string
200
+     */
201
+    public function getCertificateBundle($uid = '') {
202
+        if ($uid === '') {
203
+            $uid = $this->uid;
204
+        }
205
+        return $this->getPathToCertificates($uid) . 'rootcerts.crt';
206
+    }
207
+
208
+    /**
209
+     * Get the full local path to the certificate bundle for this user
210
+     *
211
+     * @param string $uid (optional) user to get the certificate bundle for, use `null` to get the system bundle
212
+     * @return string
213
+     */
214
+    public function getAbsoluteBundlePath($uid = '') {
215
+        if ($uid === '') {
216
+            $uid = $this->uid;
217
+        }
218
+        if ($this->needsRebundling($uid)) {
219
+            if (is_null($uid)) {
220
+                $manager = new CertificateManager(null, $this->view, $this->config, $this->logger);
221
+                $manager->createCertificateBundle();
222
+            } else {
223
+                $this->createCertificateBundle();
224
+            }
225
+        }
226
+        return $this->view->getLocalFile($this->getCertificateBundle($uid));
227
+    }
228
+
229
+    /**
230
+     * @param string $uid (optional) user to get the certificate path for, use `null` to get the system path
231
+     * @return string
232
+     */
233
+    private function getPathToCertificates($uid = '') {
234
+        if ($uid === '') {
235
+            $uid = $this->uid;
236
+        }
237
+        $path = is_null($uid) ? '/files_external/' : '/' . $uid . '/files_external/';
238
+
239
+        return $path;
240
+    }
241
+
242
+    /**
243
+     * Check if we need to re-bundle the certificates because one of the sources has updated
244
+     *
245
+     * @param string $uid (optional) user to get the certificate path for, use `null` to get the system path
246
+     * @return bool
247
+     */
248
+    private function needsRebundling($uid = '') {
249
+        if ($uid === '') {
250
+            $uid = $this->uid;
251
+        }
252
+        $sourceMTimes = [$this->getFilemtimeOfCaBundle()];
253
+        $targetBundle = $this->getCertificateBundle($uid);
254
+        if (!$this->view->file_exists($targetBundle)) {
255
+            return true;
256
+        }
257
+
258
+        if (!is_null($uid)) { // also depend on the system bundle
259
+            $sourceMTimes[] = $this->view->filemtime($this->getCertificateBundle(null));
260
+        }
261
+
262
+        $sourceMTime = array_reduce($sourceMTimes, function ($max, $mtime) {
263
+            return max($max, $mtime);
264
+        }, 0);
265
+        return $sourceMTime > $this->view->filemtime($targetBundle);
266
+    }
267
+
268
+    /**
269
+     * get mtime of ca-bundle shipped by Nextcloud
270
+     *
271
+     * @return int
272
+     */
273
+    protected function getFilemtimeOfCaBundle() {
274
+        return filemtime(\OC::$SERVERROOT . '/resources/config/ca-bundle.crt');
275
+    }
276 276
 
277 277
 }
Please login to merge, or discard this patch.
lib/private/TempManager.php 1 patch
Indentation   +221 added lines, -221 removed lines patch added patch discarded remove patch
@@ -34,246 +34,246 @@
 block discarded – undo
34 34
 use OCP\ITempManager;
35 35
 
36 36
 class TempManager implements ITempManager {
37
-	/** @var string[] Current temporary files and folders, used for cleanup */
38
-	protected $current = [];
39
-	/** @var string i.e. /tmp on linux systems */
40
-	protected $tmpBaseDir;
41
-	/** @var ILogger */
42
-	protected $log;
43
-	/** @var IConfig */
44
-	protected $config;
37
+    /** @var string[] Current temporary files and folders, used for cleanup */
38
+    protected $current = [];
39
+    /** @var string i.e. /tmp on linux systems */
40
+    protected $tmpBaseDir;
41
+    /** @var ILogger */
42
+    protected $log;
43
+    /** @var IConfig */
44
+    protected $config;
45 45
 
46
-	/** Prefix */
47
-	const TMP_PREFIX = 'oc_tmp_';
46
+    /** Prefix */
47
+    const TMP_PREFIX = 'oc_tmp_';
48 48
 
49
-	/**
50
-	 * @param \OCP\ILogger $logger
51
-	 * @param \OCP\IConfig $config
52
-	 */
53
-	public function __construct(ILogger $logger, IConfig $config) {
54
-		$this->log = $logger;
55
-		$this->config = $config;
56
-		$this->tmpBaseDir = $this->getTempBaseDir();
57
-	}
49
+    /**
50
+     * @param \OCP\ILogger $logger
51
+     * @param \OCP\IConfig $config
52
+     */
53
+    public function __construct(ILogger $logger, IConfig $config) {
54
+        $this->log = $logger;
55
+        $this->config = $config;
56
+        $this->tmpBaseDir = $this->getTempBaseDir();
57
+    }
58 58
 
59
-	/**
60
-	 * Builds the filename with suffix and removes potential dangerous characters
61
-	 * such as directory separators.
62
-	 *
63
-	 * @param string $absolutePath Absolute path to the file / folder
64
-	 * @param string $postFix Postfix appended to the temporary file name, may be user controlled
65
-	 * @return string
66
-	 */
67
-	private function buildFileNameWithSuffix($absolutePath, $postFix = '') {
68
-		if($postFix !== '') {
69
-			$postFix = '.' . ltrim($postFix, '.');
70
-			$postFix = str_replace(['\\', '/'], '', $postFix);
71
-			$absolutePath .= '-';
72
-		}
59
+    /**
60
+     * Builds the filename with suffix and removes potential dangerous characters
61
+     * such as directory separators.
62
+     *
63
+     * @param string $absolutePath Absolute path to the file / folder
64
+     * @param string $postFix Postfix appended to the temporary file name, may be user controlled
65
+     * @return string
66
+     */
67
+    private function buildFileNameWithSuffix($absolutePath, $postFix = '') {
68
+        if($postFix !== '') {
69
+            $postFix = '.' . ltrim($postFix, '.');
70
+            $postFix = str_replace(['\\', '/'], '', $postFix);
71
+            $absolutePath .= '-';
72
+        }
73 73
 
74
-		return $absolutePath . $postFix;
75
-	}
74
+        return $absolutePath . $postFix;
75
+    }
76 76
 
77
-	/**
78
-	 * Create a temporary file and return the path
79
-	 *
80
-	 * @param string $postFix Postfix appended to the temporary file name
81
-	 * @return string
82
-	 */
83
-	public function getTemporaryFile($postFix = '') {
84
-		if (is_writable($this->tmpBaseDir)) {
85
-			// To create an unique file and prevent the risk of race conditions
86
-			// or duplicated temporary files by other means such as collisions
87
-			// we need to create the file using `tempnam` and append a possible
88
-			// postfix to it later
89
-			$file = tempnam($this->tmpBaseDir, self::TMP_PREFIX);
90
-			$this->current[] = $file;
77
+    /**
78
+     * Create a temporary file and return the path
79
+     *
80
+     * @param string $postFix Postfix appended to the temporary file name
81
+     * @return string
82
+     */
83
+    public function getTemporaryFile($postFix = '') {
84
+        if (is_writable($this->tmpBaseDir)) {
85
+            // To create an unique file and prevent the risk of race conditions
86
+            // or duplicated temporary files by other means such as collisions
87
+            // we need to create the file using `tempnam` and append a possible
88
+            // postfix to it later
89
+            $file = tempnam($this->tmpBaseDir, self::TMP_PREFIX);
90
+            $this->current[] = $file;
91 91
 
92
-			// If a postfix got specified sanitize it and create a postfixed
93
-			// temporary file
94
-			if($postFix !== '') {
95
-				$fileNameWithPostfix = $this->buildFileNameWithSuffix($file, $postFix);
96
-				touch($fileNameWithPostfix);
97
-				chmod($fileNameWithPostfix, 0600);
98
-				$this->current[] = $fileNameWithPostfix;
99
-				return $fileNameWithPostfix;
100
-			}
92
+            // If a postfix got specified sanitize it and create a postfixed
93
+            // temporary file
94
+            if($postFix !== '') {
95
+                $fileNameWithPostfix = $this->buildFileNameWithSuffix($file, $postFix);
96
+                touch($fileNameWithPostfix);
97
+                chmod($fileNameWithPostfix, 0600);
98
+                $this->current[] = $fileNameWithPostfix;
99
+                return $fileNameWithPostfix;
100
+            }
101 101
 
102
-			return $file;
103
-		} else {
104
-			$this->log->warning(
105
-				'Can not create a temporary file in directory {dir}. Check it exists and has correct permissions',
106
-				[
107
-					'dir' => $this->tmpBaseDir,
108
-				]
109
-			);
110
-			return false;
111
-		}
112
-	}
102
+            return $file;
103
+        } else {
104
+            $this->log->warning(
105
+                'Can not create a temporary file in directory {dir}. Check it exists and has correct permissions',
106
+                [
107
+                    'dir' => $this->tmpBaseDir,
108
+                ]
109
+            );
110
+            return false;
111
+        }
112
+    }
113 113
 
114
-	/**
115
-	 * Create a temporary folder and return the path
116
-	 *
117
-	 * @param string $postFix Postfix appended to the temporary folder name
118
-	 * @return string
119
-	 */
120
-	public function getTemporaryFolder($postFix = '') {
121
-		if (is_writable($this->tmpBaseDir)) {
122
-			// To create an unique directory and prevent the risk of race conditions
123
-			// or duplicated temporary files by other means such as collisions
124
-			// we need to create the file using `tempnam` and append a possible
125
-			// postfix to it later
126
-			$uniqueFileName = tempnam($this->tmpBaseDir, self::TMP_PREFIX);
127
-			$this->current[] = $uniqueFileName;
114
+    /**
115
+     * Create a temporary folder and return the path
116
+     *
117
+     * @param string $postFix Postfix appended to the temporary folder name
118
+     * @return string
119
+     */
120
+    public function getTemporaryFolder($postFix = '') {
121
+        if (is_writable($this->tmpBaseDir)) {
122
+            // To create an unique directory and prevent the risk of race conditions
123
+            // or duplicated temporary files by other means such as collisions
124
+            // we need to create the file using `tempnam` and append a possible
125
+            // postfix to it later
126
+            $uniqueFileName = tempnam($this->tmpBaseDir, self::TMP_PREFIX);
127
+            $this->current[] = $uniqueFileName;
128 128
 
129
-			// Build a name without postfix
130
-			$path = $this->buildFileNameWithSuffix($uniqueFileName . '-folder', $postFix);
131
-			mkdir($path, 0700);
132
-			$this->current[] = $path;
129
+            // Build a name without postfix
130
+            $path = $this->buildFileNameWithSuffix($uniqueFileName . '-folder', $postFix);
131
+            mkdir($path, 0700);
132
+            $this->current[] = $path;
133 133
 
134
-			return $path . '/';
135
-		} else {
136
-			$this->log->warning(
137
-				'Can not create a temporary folder in directory {dir}. Check it exists and has correct permissions',
138
-				[
139
-					'dir' => $this->tmpBaseDir,
140
-				]
141
-			);
142
-			return false;
143
-		}
144
-	}
134
+            return $path . '/';
135
+        } else {
136
+            $this->log->warning(
137
+                'Can not create a temporary folder in directory {dir}. Check it exists and has correct permissions',
138
+                [
139
+                    'dir' => $this->tmpBaseDir,
140
+                ]
141
+            );
142
+            return false;
143
+        }
144
+    }
145 145
 
146
-	/**
147
-	 * Remove the temporary files and folders generated during this request
148
-	 */
149
-	public function clean() {
150
-		$this->cleanFiles($this->current);
151
-	}
146
+    /**
147
+     * Remove the temporary files and folders generated during this request
148
+     */
149
+    public function clean() {
150
+        $this->cleanFiles($this->current);
151
+    }
152 152
 
153
-	/**
154
-	 * @param string[] $files
155
-	 */
156
-	protected function cleanFiles($files) {
157
-		foreach ($files as $file) {
158
-			if (file_exists($file)) {
159
-				try {
160
-					\OC_Helper::rmdirr($file);
161
-				} catch (\UnexpectedValueException $ex) {
162
-					$this->log->warning(
163
-						"Error deleting temporary file/folder: {file} - Reason: {error}",
164
-						[
165
-							'file' => $file,
166
-							'error' => $ex->getMessage(),
167
-						]
168
-					);
169
-				}
170
-			}
171
-		}
172
-	}
153
+    /**
154
+     * @param string[] $files
155
+     */
156
+    protected function cleanFiles($files) {
157
+        foreach ($files as $file) {
158
+            if (file_exists($file)) {
159
+                try {
160
+                    \OC_Helper::rmdirr($file);
161
+                } catch (\UnexpectedValueException $ex) {
162
+                    $this->log->warning(
163
+                        "Error deleting temporary file/folder: {file} - Reason: {error}",
164
+                        [
165
+                            'file' => $file,
166
+                            'error' => $ex->getMessage(),
167
+                        ]
168
+                    );
169
+                }
170
+            }
171
+        }
172
+    }
173 173
 
174
-	/**
175
-	 * Remove old temporary files and folders that were failed to be cleaned
176
-	 */
177
-	public function cleanOld() {
178
-		$this->cleanFiles($this->getOldFiles());
179
-	}
174
+    /**
175
+     * Remove old temporary files and folders that were failed to be cleaned
176
+     */
177
+    public function cleanOld() {
178
+        $this->cleanFiles($this->getOldFiles());
179
+    }
180 180
 
181
-	/**
182
-	 * Get all temporary files and folders generated by oc older than an hour
183
-	 *
184
-	 * @return string[]
185
-	 */
186
-	protected function getOldFiles() {
187
-		$cutOfTime = time() - 3600;
188
-		$files = [];
189
-		$dh = opendir($this->tmpBaseDir);
190
-		if ($dh) {
191
-			while (($file = readdir($dh)) !== false) {
192
-				if (substr($file, 0, 7) === self::TMP_PREFIX) {
193
-					$path = $this->tmpBaseDir . '/' . $file;
194
-					$mtime = filemtime($path);
195
-					if ($mtime < $cutOfTime) {
196
-						$files[] = $path;
197
-					}
198
-				}
199
-			}
200
-		}
201
-		return $files;
202
-	}
181
+    /**
182
+     * Get all temporary files and folders generated by oc older than an hour
183
+     *
184
+     * @return string[]
185
+     */
186
+    protected function getOldFiles() {
187
+        $cutOfTime = time() - 3600;
188
+        $files = [];
189
+        $dh = opendir($this->tmpBaseDir);
190
+        if ($dh) {
191
+            while (($file = readdir($dh)) !== false) {
192
+                if (substr($file, 0, 7) === self::TMP_PREFIX) {
193
+                    $path = $this->tmpBaseDir . '/' . $file;
194
+                    $mtime = filemtime($path);
195
+                    if ($mtime < $cutOfTime) {
196
+                        $files[] = $path;
197
+                    }
198
+                }
199
+            }
200
+        }
201
+        return $files;
202
+    }
203 203
 
204
-	/**
205
-	 * Get the temporary base directory configured on the server
206
-	 *
207
-	 * @return string Path to the temporary directory or null
208
-	 * @throws \UnexpectedValueException
209
-	 */
210
-	public function getTempBaseDir() {
211
-		if ($this->tmpBaseDir) {
212
-			return $this->tmpBaseDir;
213
-		}
204
+    /**
205
+     * Get the temporary base directory configured on the server
206
+     *
207
+     * @return string Path to the temporary directory or null
208
+     * @throws \UnexpectedValueException
209
+     */
210
+    public function getTempBaseDir() {
211
+        if ($this->tmpBaseDir) {
212
+            return $this->tmpBaseDir;
213
+        }
214 214
 
215
-		$directories = [];
216
-		if ($temp = $this->config->getSystemValue('tempdirectory', null)) {
217
-			$directories[] = $temp;
218
-		}
219
-		if ($temp = \OC::$server->getIniWrapper()->get('upload_tmp_dir')) {
220
-			$directories[] = $temp;
221
-		}
222
-		if ($temp = getenv('TMP')) {
223
-			$directories[] = $temp;
224
-		}
225
-		if ($temp = getenv('TEMP')) {
226
-			$directories[] = $temp;
227
-		}
228
-		if ($temp = getenv('TMPDIR')) {
229
-			$directories[] = $temp;
230
-		}
231
-		if ($temp = sys_get_temp_dir()) {
232
-			$directories[] = $temp;
233
-		}
215
+        $directories = [];
216
+        if ($temp = $this->config->getSystemValue('tempdirectory', null)) {
217
+            $directories[] = $temp;
218
+        }
219
+        if ($temp = \OC::$server->getIniWrapper()->get('upload_tmp_dir')) {
220
+            $directories[] = $temp;
221
+        }
222
+        if ($temp = getenv('TMP')) {
223
+            $directories[] = $temp;
224
+        }
225
+        if ($temp = getenv('TEMP')) {
226
+            $directories[] = $temp;
227
+        }
228
+        if ($temp = getenv('TMPDIR')) {
229
+            $directories[] = $temp;
230
+        }
231
+        if ($temp = sys_get_temp_dir()) {
232
+            $directories[] = $temp;
233
+        }
234 234
 
235
-		foreach ($directories as $dir) {
236
-			if ($this->checkTemporaryDirectory($dir)) {
237
-				return $dir;
238
-			}
239
-		}
235
+        foreach ($directories as $dir) {
236
+            if ($this->checkTemporaryDirectory($dir)) {
237
+                return $dir;
238
+            }
239
+        }
240 240
 
241
-		$temp = tempnam(dirname(__FILE__), '');
242
-		if (file_exists($temp)) {
243
-			unlink($temp);
244
-			return dirname($temp);
245
-		}
246
-		throw new \UnexpectedValueException('Unable to detect system temporary directory');
247
-	}
241
+        $temp = tempnam(dirname(__FILE__), '');
242
+        if (file_exists($temp)) {
243
+            unlink($temp);
244
+            return dirname($temp);
245
+        }
246
+        throw new \UnexpectedValueException('Unable to detect system temporary directory');
247
+    }
248 248
 
249
-	/**
250
-	 * Check if a temporary directory is ready for use
251
-	 *
252
-	 * @param mixed $directory
253
-	 * @return bool
254
-	 */
255
-	private function checkTemporaryDirectory($directory) {
256
-		// suppress any possible errors caused by is_writable
257
-		// checks missing or invalid path or characters, wrong permissions etc
258
-		try {
259
-			if (is_writeable($directory)) {
260
-				return true;
261
-			}
262
-		} catch (\Exception $e) {
263
-		}
264
-		$this->log->warning('Temporary directory {dir} is not present or writable',
265
-			['dir' => $directory]
266
-		);
267
-		return false;
268
-	}
249
+    /**
250
+     * Check if a temporary directory is ready for use
251
+     *
252
+     * @param mixed $directory
253
+     * @return bool
254
+     */
255
+    private function checkTemporaryDirectory($directory) {
256
+        // suppress any possible errors caused by is_writable
257
+        // checks missing or invalid path or characters, wrong permissions etc
258
+        try {
259
+            if (is_writeable($directory)) {
260
+                return true;
261
+            }
262
+        } catch (\Exception $e) {
263
+        }
264
+        $this->log->warning('Temporary directory {dir} is not present or writable',
265
+            ['dir' => $directory]
266
+        );
267
+        return false;
268
+    }
269 269
 
270
-	/**
271
-	 * Override the temporary base directory
272
-	 *
273
-	 * @param string $directory
274
-	 */
275
-	public function overrideTempBaseDir($directory) {
276
-		$this->tmpBaseDir = $directory;
277
-	}
270
+    /**
271
+     * Override the temporary base directory
272
+     *
273
+     * @param string $directory
274
+     */
275
+    public function overrideTempBaseDir($directory) {
276
+        $this->tmpBaseDir = $directory;
277
+    }
278 278
 
279 279
 }
Please login to merge, or discard this patch.