Little-beak.com's gitlab server

nextcloud_version2.tex 26.9 KB
Newer Older
drexl's avatar
drexl committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
\documentclass[12pt,a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage{graphicx}

%% Added to display code.
\usepackage{listings}

%handles umlauts
\lstset{literate=%
{Ö}{{\"O}}1
{Ä}{{\"A}}1
{Ü}{{\"U}}1
{ß}{{\ss}}2
{ü}{{\"u}}1
{ä}{{\"a}}1
{ö}{{\"o}}1
}


%handles floating objects
\usepackage[section]{placeins}

%handles code insertion
\usepackage{color}

\definecolor{mygreen}{rgb}{0,0.6,0}
\definecolor{mygray}{rgb}{0.5,0.5,0.5}
\definecolor{mymauve}{rgb}{0.58,0,0.82}

\lstset{ %
  backgroundcolor=\color{white},   % choose the background color; you must add \usepackage{color} or \usepackage{xcolor}; should come as last argument
  basicstyle=\footnotesize,        % the size of the fonts that are used for the code
  breakatwhitespace=false,         % sets if automatic breaks should only happen at whitespace
  breaklines=true,                 % sets automatic line breaking
  captionpos=b,                    % sets the caption-position to bottom
  commentstyle=\color{mygreen},    % comment style
  columns=fullflexible,				%IMPORTANT, added to insure that the columns align properly
  deletekeywords={...},            % if you want to delete keywords from the given language
  escapeinside={\%*}{*)},          % if you want to add LaTeX within your code
  extendedchars=true,              % lets you use non-ASCII characters; for 8-bits encodings only, does not work with UTF-8
  frame=single,	                   % adds a frame around the code
  keepspaces=true,                 % keeps spaces in text, useful for keeping indentation of code (possibly needs columns=flexible)
  keywordstyle=\color{blue},       % keyword style
  language=php,                 % the language of the code
  morekeywords={*,...},            % if you want to add more keywords to the set
  numbers=left,                    % where to put the line-numbers; possible values are (none, left, right)
  numbersep=5pt,                   % how far the line-numbers are from the code
  numberstyle=\tiny\color{mygray}, % the style that is used for the line-numbers
  rulecolor=\color{black},         % if not set, the frame-color may be changed on line-breaks within not-black text (e.g. comments (green here))
  showspaces=false,                % show spaces everywhere adding particular underscores; it overrides 'showstringspaces'
  showstringspaces=false,          % underline spaces within strings only
  showtabs=false,                  % show tabs within strings adding particular underscores
  stepnumber=1,                    % the step between two line-numbers. If it's 1, each line will be numbered
  stringstyle=\color{mymauve},     % string literal style
  tabsize=2,	                   % sets default tabsize to 2 spaces
  title=\lstname                   % show the filename of files included with \lstinputlisting; also try caption instead of title
}









70
\author{R********, Rusland and Licea, Esteban}
drexl's avatar
drexl committed
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117


\begin{document}

% First we'll do the basic pseudocode for the whole project.
% Title page

\begin{titlepage}


\newcommand{\HRule}{\rule{\linewidth}{0.5mm}} % Defines a new command for the horizontal lines, change thickness here

\center % Center everything on the page
 
 %----------------------------------------------------------------------------------------
%	LOGO SECTION
%----------------------------------------------------------------------------------------

\begin{center}
\includegraphics[scale=.13]{Logo_HTW_Berlin.png}\\[1cm] % Include a department/university logo - this will require the graphicx package
\end{center}
 
%----------------------------------------------------------------------------------------

%----------------------------------------------------------------------------------------
%	HEADING SECTIONS
%----------------------------------------------------------------------------------------

%\textsc{\LARGE Hochschule für Technik und Wirtschaft Berlin}\\[1.5cm] % Name of your university/college
\textsc{\Large Internet Security}\\[0.5cm] % Major heading such as course name
\textsc{\large Internationaler Medieninformatik}\\[0.5cm] % Minor heading such as course title

%----------------------------------------------------------------------------------------
%	TITLE SECTION
%----------------------------------------------------------------------------------------

\HRule \\[0.4cm]
{ \huge \bfseries NextCloud Security and Threat Report}\\[0.4cm] % Title of your document
\HRule \\[1.5cm]
 
%----------------------------------------------------------------------------------------
%	AUTHOR SECTION
%----------------------------------------------------------------------------------------

\begin{minipage}{0.4\textwidth}
\begin{flushleft} \large
\emph{Author:}\\
118 119
Ruslan \textsc{R*******}\\ (Matr. Nr)\\ % Your name
Esteban \textsc{L****}\\ (Matr. Nr)\\ % Your name
drexl's avatar
drexl committed
120 121 122 123 124 125
\end{flushleft}
\end{minipage}
~
\begin{minipage}{0.4\textwidth}
\begin{flushright} \large
\emph{Supervisor:} \\
126
M. Sc. B**** \textsc{Kirschner} % Supervisor's Name
drexl's avatar
drexl committed
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566
\end{flushright}
\end{minipage}\\[4cm]

% If you don't want a supervisor, uncomment the two lines below and remove the section above
%\Large \emph{Author:}\\
%John \textsc{Smith}\\[3cm] % Your name

%----------------------------------------------------------------------------------------
%	DATE SECTION
%----------------------------------------------------------------------------------------

{\large \today}\\[0.5cm] % Date, change the \today to a set date if you want to be precise


\vfill % Fill the rest of the page with whitespace

\end{titlepage}


% Table of Content
\tableofcontents

%Executive summary
%Basically, the TL;DR
\section{Executive Summary}

% Introduction
\subsection{Background}
\paragraph{We have selected the open source project Nextcloud for our report. Originally, we had thought about exploring ownCloud, but apparently within a few months of this writing, co-founder and CEO Frank Karlitschek decided to leave ownCloud and fork into Nextcloud--followed, thereafter, by a majority of the core development team. At the start of this project, we had to decided which one of the two to choose, before settling on Nextcloud.}
\cite{site1} %creates the first notation for our bibliography.

\subsection{What is Nextcloud}

\paragraph{Nextcloud, the next generation open source Enterprise File Sync and Share was started by ownCloud inventor Frank Karlitschek and a dozen experienced open source entrepreneurs and engineers to empower users to take back control over their data and communication. The company was launched in 2016 as a spin-off from Struktur AG, a leading web conferencing and financial planning software company since 1995, servicing customers like Deutsche Bank, Vodafone, BNP Paribas and many others, and turned profitable by the end of 2016. Nextcloud gives organizations fine-grained control over data access, facilitates file synchronization and sharing across devices, enables collaboration within and across organizational boundaries and lets users communicate through secure audio and video conferencing.}
\cite{site2}

%mostly follow another template
\subsection{Summary of Tests, Findings \& Recommendations}

\paragraph{Before we begin our tests, we will acknowledge currently known vulnerabilities. This serves two purposes:}

\paragraph{First, we can limit our exploration for an already known vulnerability. Secondly, it will give us an idea of where adjacent vulnerabilities may lie.}
\footnote{https://nextcloud.com/security/advisory/?id=nc-sa-2017-007}

%\begin{enumerate}
%\item DOM XSS vulnerability in search dialogue
%\item Reflected XSS in error pages
%\item Limitation of app specific password scope can be bypassed
%\item Stored XSS in Gallery application
%\item Share tokens for public calendars disclosed
%\end{enumerate}




%\begin{enumerate}
%\item We will not waste time reporting a known issue.
%\item We can begin probing near a known vulnerability.
%\end{enumerate}

\paragraph{As of the 8th, May 2017, Nextcloud server version 11.0.3, the known vulnerabilities according to the Nextcloud advistory, are shown in table ~\ref{tab: currentVulnerabilities}.}
\footnote{The errors has been fixed and regression tests been added.}


% Note the !htb, to keep the table 'here'

\begin{table}[!htb]
\begin{center}
\resizebox {15cm}{!}{
	\begin{tabular}{|p{6cm}|p{2cm}|p{6cm}|}
	\hline
	\multicolumn{3}{|c|}{\textbf{Nextcloud known vulnerabilities}}\\ 
	\hline
Name & CWE classification & Description\\
	\hline
	\hline
DOM XSS vulnerability in search dialogue (NC-SA-2017-007) & CWE-79 & Inadequate escaping lead to XSS vulnerability in the search module. To be exploitable an user has to write or paste malicious content into the search dialogue.\\
	\hline
Reflected XSS in error pages (NC-SA-2017-008)  & CWE-79 & Inadequate escaping of error messages leads to XSS vulnerabilities in multiple components.

Note that Nextcloud employs a strict Content-Security-Policy preventing exploitation of this XSS issue on modern web browsers. \\
	\hline
Limitation of app specific password scope can be bypassed (NC-SA-2017-009) & CWE-285 & Improper session handling allowed an application specific password without permission to the files access to the users file. \\
	\hline
Stored XSS in Gallery application (NC-SA-2017-010) & CWE-79 & A JavaScript library used by Nextcloud for sanitizing untrusted user-input suffered from a XSS vulnerability caused by a behaviour change in Safari 10.1 and 10.2.

Note that Nextcloud employs a strict Content-Security-Policy preventing exploitation of this XSS issue on modern web browsers. \\
	\hline
Share tokens for public calendars disclosed (NC-SA-2017-011) & CWE-548 & A logical error caused disclosure of valid share tokens for public calendars. Thus granting an attacker potentially access to publicly shared calendars without knowing the share token. \\
	\hline
\end{tabular}}
\caption{\label{tab: currentVulnerabilities} Vulnerabilities as of {\today}}
\end{center}
\end{table}




\paragraph{Following is a list of common attacks, against a LAMP stack.}
\footnote{LAMP = Linux, Apache, MySQL, and Php technologies used together to implement an application.}

\paragraph{We will go through, and carefully consider each attack vector.}
\cite{man1}

\begin{enumerate}
\item CSRF - Cross-site request forgery
\item SQL Injection
\item Cross-site scripting (XSS)
\item JavaScript vulnerabilities
\item Clickjacking
\item Code execution/File inclusions
\item Directory Traversal/Auth bypass/Privilege escalations
\item Shell Injection
\item Sensitive Data exposure
\end{enumerate}

\subsubsection{Cross-site Request Forgery}
\paragraph{An attack type that can be mitigated by the implementation of Same-site cookies. Nextcloud implements Same-site cookie, for example, in the /var/www/nextcloud/lib/base.php file, as well as the /var/www/nextcloud/core/ajax/update.php file.}

\paragraph{The code from the base.php file demonstrates how Nextcloud creates Same-site cookies.}

\paragraph{The update.php file exemplifies how Nextcloud implements error handling, verification, and updates the site, accordingly.}

\paragraph{Browsers that support same-site cookies can be instructed in a way to only send a cookie if the request is originating from the original domain. This makes exploiting CSRF vulnerabilities from other domains a non-issue. Also timing attacks, such as enumerating whether a specific file or folder exists, are not feasible anymore. Nextcloud enforces the same-site cookies to be present on every request by enforcing this within the middleware.}
\cite{site4}

\paragraph{At the moment, it doesn't appear that Nextcloud can do more to mitigate the security risks associated with CSRF type attacks, and the current safeguards are otherwise satisfactory.}

\subsubsection{SQL Injection}

\paragraph{The best protection against this type of attack vector is the usage of SQL prepared statements. As best we could, we found that Nextcloud's application only uses prepared statements within php's framework, and encourages application developers to do so as well. Here is an example that demonstrates how to create prepared statements, so there is less direct access to the database, via SQL.}

\begin{center}
\begin{lstlisting} [title=sqlGoodPractices snippet]
<?php
$sql = 'SELECT * FROM `users` WHERE `id` = ?';
$query = \OCP\DB::prepare($sql);
$params = array(1);
$result = $query->execute($params);
\end{lstlisting}
\end{center}

\subsubsection{Cross-site scripting (XSS)}

\paragraph{Cross site scripting happens when user input is passed directly to templates. A potential attacker might be able to inject HTML/JavaScript into the page to steal the users session, log keyboard entries, even perform DDOS attacks on other websites or other malicious actions.}
\cite{man1}

\paragraph{Nextcloud utilizes a Content-Security-Policy to enhance security, and prevent the usage of inline Javascript execution. Additionally, Nextcloud sanitizes it's templates (and JavaScript) which manipulate any DOM elements, to limit the potential for breaches.}

\paragraph{According to the Nextcloud Developer's Manual, the best way to sanitize templates is to never use echo, print, and $<\%=$ commands, but instead use p(). Here is an example of vulnerable code:}

\begin{center}
\begin{lstlisting}[title=badExample.php]
<?php
echo $_GET['username'];
\end{lstlisting}
\end{center}

\paragraph{We searched through the code for vulnerabilities of this type, in addition to, href attributes -- which can also open the door for XSS attacks, but found no weaknesses.}

\subsubsection{JavaScript vulnerabilities}
\paragraph{We combed the code elements that allow manipulate HTML directly via JavaScript, which can lead to un-sanitized variables. Good and bad guidelines were offered in the developer manual to assist us in our search (See below):}

\begin{center}
\begin{lstlisting} [title=DON'T]
var html = '<li>' + username + '</li>"';
\end{lstlisting}
\end{center}

\begin{center}
\begin{lstlisting} [title=DO]
var html = '<li>' + escapeHTML(username) + '</li>';
\end{lstlisting}
\end{center}

\subsubsection{Clickjacking}
\paragraph{When determining how to search for Clickjacking, we had to understand how Nextcloud handles the threat of offering the user invisible x-frame to click. No one can prevent users from randomly click on whatever their hearts desire. However, Nextcloud sends the X-Frame-Options header to all template responses, which should eliminate the threat of tricking the user into exploiting x-frame vulnerabilities.}

\subsubsection{Code Execution/File inclusions}
\paragraph{Code Execution means that an attacker can include a malicious PHP file that executes with unwanted consequences. We were unable to find a vulnerability with our manual intrusion attempts. Nextcloud further cautions to never allow users to upload files into a folder which is reachable from the URL.}

\paragraph{We scanned through the application files, to try to find any examples where user-input was allowed through any of the following php functions:}

\begin{itemize}
\item include()
\item require()
\item require\_once()
\item eval()
\item fopen()
\end{itemize}

\paragraph{We were unsuccessful.}

\subsubsection{Directory Traversal/Auth Bypass/Privilege Escalations}
\paragraph{Ad-hoc attempts to attack Nextcloud through Directory Traversal, AuthBypass, and privilege escalation were unsuccessful. Altering various URL inputs like "\textbackslash" and "/" did not expose any elements of the system.}

\paragraph{We used the following code examples, as the basis for our scans of the Nextcloud code.}
\cite{man1}


\begin{center}
\begin{lstlisting} [title=DON'T]
<?php
$username = OC_User::getUser();
fopen("/data/" . $username . "/" . $_GET['file'] . ".txt");
\end{lstlisting}
\end{center}

\begin{center}
\begin{lstlisting} [title=DO]
<?php
$username = OC_User::getUser();
$file = str_replace(array('/', '\\'), '', $_GET['file']);
fopen("/data/" . $username . "/" . $file . ".txt");
\end{lstlisting}
\end{center}

\paragraph{The better code replaces "/" "\textbackslash\textbackslash", with the "/". This particular vulnerability was scanned with eyeballs, as it was not something that could be easily parsed with a text editor like vi.}

\subsubsection{Shell Injection}
\paragraph{Since Nextcloud doesn't offer any type of core abilities that would allow PHP to execute shell commands, we consider this area a low risk. We did search through some elements that could conceivably use shell commands, but they did not. Unless someone codes a particular application that does so, there does not appear to be a threat from this vector.}

\subsubsection{Sensitive Data Exposure}
\paragraph{Nextcloud does not store it's application location in a webroot directly, thus it cannot be accessed simply by using a web browser.}



\subsection{Detailed Findings}
%list all vulnerabilities
\paragraph{In the end, we were unable to find any security vulnerabilities at this time. For an open source project, Nextcloud is mature, and well developed. With continued development, however, penetration testing will be required periodically. However, at the moment, it appears that Nextcloud has a robust security system in place, that should inspire confidence in it's users.}


% Methodology
\section{Methodology}
\paragraph{The primary focus of our task was defining the methodology. We asked ourselves the followed questions:}

\begin{enumerate}
\item What technologies are involved?
\item What are the customer's (Nextcloud in this case) needs?
\item How will we probe/examine the involved technologies, in particular, the known attack vectors against them?
\end{enumerate}

% 		1. Determine protocol stacks to be analyzed.
\subsection{Protocols \& adjacent technologies to be examined}
\paragraph{In defining our scope, we consider all threats, from all attack vectors--across all relevant technologies, which would for this project, include the following areas:}

\begin{enumerate}
\item HTML
\item CSS
\item JavaScript
\item Apache
\item MySQL
\item PHP
\end{enumerate}

\paragraph{Predominantly, however, the application under review will dive us deep into PHP.}

% 2. Determine associated vulnerabilities known against those protocols
\subsection{Nextcloud Threat-model}

\paragraph{We will, however, mostly focus our attention mostly on Nextcloud's threat model. Following is the model:}
\cite{site3}

\subsubsection{Administrator privileges}
\paragraph{Nextcloud considers administrators ultimately trusted. It is for example expected behavior that a Nextcloud administrator can execute arbitrary code.}

\subsubsection{Encryption}
\paragraph{Nextcloud can be configured to encrypt data at rest. In this scenario we do prevent against storage administrators mainly, we are aware that a Nextcloud administrator could still intercept the user password to manually decrypt the encryption key. We do thus only consider attack scenarios bounty-worthy if they include external parties.}

\subsubsection{Features intentionally marked as insecure}
\paragraph{Some features in Nextcloud are intentionally marked as insecure and disabled by default (plus have a big warning above them). One example includes the preview providers such as the LibreOffice preview provider. At the moment we consider vulnerabilities in those disabled features as not bounty-worthy.}

\subsubsection{Attacks involving other Android apps on the device}
\paragraph{We do consider attacks involving other Android apps on the device as minimal risk, also especially considering that the Nextcloud Android apps stores synced files locally accessible on the device. (since no Content Provider is yet implemented).}

\subsubsection{Denial of Service}
\paragraph{Due to the usage of the PHP scripting language Nextcloud does consider Denial of Service not something that can at the moment be completely prevented. For this reason while we do fix and acknowledge specific Denial of Service attacks we do generally not consider DoS a bounty-worthy vulnerability.}

\subsubsection{Audit logging}
\paragraph{The audit logging feature in Nextcloud is at the moment missing some logs for things like "Accessing previews of files", these will be added in a future release and known issues are tracked in our issue tracker.}

\subsubsection{Version disclosure}
\paragraph{At the moment we consider version disclosure an accepted risk as an attacker can enumerate service versions using other means as well. (e.g. comparing behavior)}

\subsubsection{Content spoofing}
\paragraph{Generally speaking we consider content spoofing not a bounty-worthy vulnerability.}

\subsubsection{User enumeration}
\paragraph{We do not consider user enumeration a security risk as for convenience and for features such as Server-to-Server sharing this is an expected behavior.}

\subsubsection{Brute force of credentials}
\paragraph{At the moment we do not consider brute-forcing of credentials or a missing password threshold eligible vulnerabilities. In the case of Nextcloud we currently expect people to protect their instance using measures such as fail2ban. We do have a native anti-bruteforce protection.}

\subsubsection{Server-side request forgery}
\paragraph{Nextcloud ships with multiple features that perform sending requests to other hosts, we do consider this accepted behavior and advocate people to deploy Nextcloud into its own segregated network segment.}


\subsection{How we examined the client software}
\paragraph{We used a two-pronged approach. First, we used manual penetration testing to try and "break" the system. Using the web as a source, we were able to find previously successful attack methods (against other systems), and try them against Nextcloud. This gave us examples of malicious javascript and php files that we could try. Additionally, it gave us an idea of how we could attempt to 'hack' Nextcloud. Lastly, we used methods learned throughout the course of how we could compromise Nextcloud.}

\paragraph{The second phase involved digging into the source code, and searching for sloppy code that could lead to system breaches. We relied heavily on the Nextcloud Developer's manual--and to a lesser extent Nextcloud's Administrator Manual--for highlighting of best practices, as well as things to be avoided. The amount of code to read was copious. It's understandable why often times security analysis relies on automated software. However, nothing is as good as a few good eyeballs. Additionally, we found it rewarding to work with vi and bash, to allow us to quickly parse through code, that otherwise would have been more laborious without.}

\paragraph{Lastly, we tried to balance our tests, against the Nextcloud threat model. It doesn't make sense to bother with things that they, themselves, deem outside of their scope, e.g. DoS attacks, for example.}
% Bibliography
\begin{thebibliography}{9}

\bibitem{site1}
  "Goodbye OwnCloud, Hello Nextcloud! The Aftermath of Disrupting Open Source Cloud Storage." Serenity-Networks. N.p., 07 Oct. 2016. Web. 03 July 2017. 
  
\bibitem{site2}
  "About – Nextcloud." About – Nextcloud – Nextcloud. N.p., n.d. Web. 18 July 2017. 
  
\bibitem{site3}
  "Threat-model." Nextcloud. N.p., n.d. Web. 20 July 2017. 
  
\bibitem{man1}
   Nextcloud Developers. Nextcloud Developer Manual. N.p.: Nextcloud, 18 July 2017. PDF. 
  
\bibitem{site4}
   "Nextcloud 11 Delivers Verified Security Improvements." Nextcloud. N.p., 13 Dec. 2016. Web. 23 July 2017. 


\end{thebibliography}

% Appendix
%		1. Risk Assessment (table)
% 		2. definitions

%\section{Appendix}

%important code that was analyzed.
%\subsection{CSRF Code}
%
%\begin{center}
%\begin{lstlisting}[title=base.php]
%    /**
%	 * Send the same site cookies
%	 */
%	private static function sendSameSiteCookies() {
%		$cookieParams = session_get_cookie_params();
%		$secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : '';
%		$policies = [
%			'lax',
%			'strict',
%		];
%
%		// Append __Host to the cookie if it meets the requirements
%		$cookiePrefix = '';
%		if($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
%			$cookiePrefix = '__Host-';
%		}
%
%		foreach($policies as $policy) {
%			header(
%				sprintf(
%					'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
%					$cookiePrefix,
%					$policy,
%					$cookieParams['path'],
%					$policy
%				),
%				false
%			);
%		}
%	}
%
%	/**
%	 * Same Site cookie to further mitigate CSRF attacks. This cookie has to
%	 * be set in every request if cookies are sent to add a second level of
%	 * defense against CSRF.
%	 *
%	 * If the cookie is not sent this will set the cookie and reload the page.
%	 * We use an additional cookie since we want to protect logout CSRF and
%	 * also we can't directly interfere with PHP's session mechanism.
%	 */
%	private static function performSameSiteCookieProtection() {
%		$request = \OC::$server->getRequest();
%
%		// Some user agents are notorious and don't really properly follow HTTP
%		// specifications. For those, have an automated opt-out. Since the protection
%		// for remote.php is applied in base.php as starting point we need to opt out
%		// here.
%		$incompatibleUserAgents = [
%			// OS X Finder
%			'/^WebDAVFS/',
%		];
%		if($request->isUserAgent($incompatibleUserAgents)) {
%			return;
%		}
%
%		if(count($_COOKIE) > 0) {
%			$requestUri = $request->getScriptName();
%			$processingScript = explode('/', $requestUri);
%			$processingScript = $processingScript[count($processingScript)-1];
%			// FIXME: In a SAML scenario we don't get any strict or lax cookie
%			// send for the ACS endpoint. Since we have some legacy code in Nextcloud
%			// (direct PHP files) the enforcement of lax cookies is performed here
%			// instead of the middleware.
%			//
%			// This means we cannot exclude some routes from the cookie validation,
%			// which normally is not a problem but is a little bit cumbersome for
%			// this use-case.
%			// Once the old legacy PHP endpoints have been removed we can move
%			// the verification into a middleware and also adds some exemptions.
%			//
%			// Questions about this code? Ask Lukas ;-)
%			$currentUrl = substr(explode('?',$request->getRequestUri(), 2)[0], strlen(\OC::$WEBROOT));
%			if($currentUrl === '/index.php/apps/user_saml/saml/acs' || $currentUrl === '/apps/user_saml/saml/acs') {
%				return;
%			}
%			// For the "index.php" endpoint only a lax cookie is required.
%			if($processingScript === 'index.php') {
%				if(!$request->passesLaxCookieCheck()) {
%					self::sendSameSiteCookies();
%					header('Location: '.$_SERVER['REQUEST_URI']);
%					exit();
%				}
%			} else {
%				// All other endpoints require the lax and the strict cookie
%				if(!$request->passesStrictCookieCheck()) {
%					self::sendSameSiteCookies();
%					// Debug mode gets access to the resources without strict cookie
%					// due to the fact that the SabreDAV browser also lives there.
%					if(!\OC::$server->getConfig()->getSystemValue('debug', false)) {
%						http_response_code(\OCP\AppFramework\Http::STATUS_SERVICE_UNAVAILABLE);
%						exit();
%					}
%				}
%			}
%		} elseif(!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
%			self::sendSameSiteCookies();
%		}
%	}
%\end{lstlisting}
%\end{center}


%\lstinputlisting[language=php]{update.php}

\end{document}