curl digest auth php

Can cURL use stored auth details with DIGEST auth?

I have a few PHP scripts across servers that have DIGEST auth setup to offer a basic protection. These scripts are executed by the cron on each system like this:

In my present setup, if I happen to change the username/password combination, I’ll have to manually edit ALL the crons to update the password.

Is there a way I can store the auth details (the password’s a hash anyway) in a text file that I can pass to cURL? Something like..

1 Answer 1

Specify which config file to read curl arguments from. The config file is a text file in which command line arguments can be written which then will be used as if they were written on the actual command line.

Options and their parameters must be specified on the same config file line, separated by whitespace, colon, or the equals sign. Long option names can optionally be given in the config file without the initial double dashes and if so, the colon or equals characters can be used as separators. If the option is specified with one or two dashes, there can be no colon or equals character between the option and its parameter.

If the parameter is to contain whitespace, the parameter must be enclosed within quotes. Within double quotes, the following escape sequences are available: \, \», \t, \n, \r and \v. A backslash preceding any other letter is ignored. If the first column of a config line is a ‘#’ character, the rest of the line will be treated as a comment. Only write one option per physical line in the config file.

1) curl tries to find the «home dir»: It first checks for the CURL_HOME and then the HOME environment variables. Failing that, it uses getpwuid() on UNIX-like systems (which returns the home dir given the current user in your system). On Windows, it then checks for the APPDATA variable, or as a last resort the ‘%USERPROFILE%\Application Data’.

This option can be used multiple times to load multiple config files.

Источник

Digest аутентификация в PHP

curl digest auth php

Ограничение доступа к какой-либо области сайта обычно выглядит
однообразно: каждому пользователю выдается логин и пароль или он сам
их выбирает, и для входа в защищенную часть сайта их нужно ввести. С технической же точки зрения для проверки пароля используются
разные методы. Для ввода логина и пароля может использоваться HTML-форма.
В этом случае пароль передается на сервер открытым текстом в POST-запросе.
Это неприемлемо, если пользователь сидит в локалке, где возможно
использование снифера. Для решения этой проблемы придуман метод
аутентификации с помощью хешей, при котором пароль не передается, а
передается хеш строка, зависящая от пароля, некоего одноразового
параметра и, возможно, еще от каких-либо параметров. Этот метод еще
называют challenge/response, поскольку при его использовании клиент
получает запрос с одноразовым параметром и посылает ответ, содержащий хеш. На уровне протокола HTTP 1.1 возможна аутентификация методом
Basic, что ни чем не лучше использования HTML-формы, и Digest, который
мы и рассмотрим подробно.

AuthType Digest
AuthUserFile
AuthName
Require valid_user

Полностью описание метода можно прочитать в RFC 2069, а если
вкратце, то метод работает так. Когда сервер получает запрос, относящийся к защищенной области,
он выдает ошибку 401 Authorization Required и заголовок с запросом
аутентификации такого вида:

Как видим, A1 не зависит ни от запроса, ни от одноразового
значения, поэтому на сервере может храниться не пароль, а
H(A1). Именно так это реализовано в mod_digest в Apache.
Однако этих же данных достаточно и клиенту. Злоумышленник, получив
этот хеш, может вычислить ответ по приведенным выше формулам и
сформировать HTTP-запрос, например, с помощью программы
AccessDriver и ее инструмента HTTP
Debugger. Подробнее этот процесс будет показан ниже. Сервер должен проверить, является ли одноразовое значение
тем, которое было ранее выдано клиенту и не устарело ли оно.
Если ответ соответствует параметру nonce, но значение этого параметра
не актуально, выдается описанный выше ответ с кодом 401 с той лишь
разницей, что в заголовок WWW-Authenticate добавляется параметр
stale=true, указывающий, что в доступе отказано лишь по этой причине,
и следует повторить попытку, не запрашивая у пользователя новый пароль. Это, имхо, неудобно, поскольку если такая ситуация возникнет
при запросе POST или PUT с большим блоком данных, то клиенту придется
передать все данные дважды. Во избежание этого стандартом предусмотрен
заголовок Authentication-Info, в котором сервер может при ответе на
успешный запрос сообщить клиенту следующее одноразовое значение.
Синтаксис такой же, как у WWW-Authenticate, кроме того что nonce
заменяется на nextnonce. Однако, судя по результатам моих
экспериментов, Opera игнорирует этот заголовок. Другое решение: в соответствии с
RFC 2068 (HTTP/1.1), сервер может ответить раньше, чем завершится запрос,
чтобы клиент прервал ненужную передачу данных, но на Apache+PHP это
не реализуется, поскольку скрипт начинает выполняться только после того,
как Apache полностью получит и пропарсит запрос.

Хранение данных между запросами

В реализации метода challenge/response на PHP есть тонкий момент.
Одноразовый параметр формируется и выдается клиенту в одном ответе, а
проверяется уже в другом сеансе работы скрипта.
То есть его необходимо сохранить от одного вызова скрипта до другого, и для этого придется
использовать файлы или БД. В моем примере используются файлы с именами,
соответствующими одноразовым значениям, а в самих файлах записаны
IP-адреса клиентов, которым они выданы. В примере не реализован сбор
мусора: надо периодически удалять старые файлы.

Этот скрипт проверяет только пароль, и работает независимо от
логина. В зависимости от успешности проверки выдаются простые ответы.

Название защищаемой области
$pass = ‘pass’; // Пароль
$fileprefix = ‘./’; // Путь для файлов-меток, обозначающих валидность nonce

// Получаем заголовки
$headers = apache_request_headers();

// Флаг, который мы установим в TRUE при успешной проверке
$auth_success = FALSE;
$stale = «»;

if ($auth_success)
<
print(» Digest auth test

Источник

Questions on Cookies cURL and Digest Auth PHP

I have 2 pages: login.php and index.php

When writting localhost/mysite/login.php and writting a username and password in a form, a cURL request using CURLOPT_HTTPAUTH = CURLAUTH_DIGEST and CURLOPT_USERPWD = ‘user:pass’ will be passed to another file that will authenticate the user with those credentials using HTTP DIGEST AUTH, and will return 200 for success or 401 for wrong credentials.

If it gets a 200 code, login.php will redirect to index.php, which will make a cURL request too to that same digest file, but without CURLOPT_HTTPAUTH or CURLOPT_USERPWD. The idea is that, since I already did this on login.php, those digest credentials should be stored on the user browser, but it isn’t. So index.php will end up asking for credentials AGAIN, this is the problem.

Some people has recommended me to use CURLOPT_COOKIEFILE and CURLOPT_COOKIEJAR, but no one has explained me how does that work? I understand that CURLOPT_COOKIEFILE is for retrieving cookies info, and CURLOPT_COOKIEJAR is for saving them.

So the questions are this:

1) The route for that cookie file (ex. ‘/tmp/cookies.txt’), where is that? what exactly is /tmp/cookies.txt? in the same level as login.php? or in C:/? also, should I create this file beforehand? or is it created automatically?

2) Is that file on the server, or on the client? if on the server, how am I to know which cookie is from which user, so that Y user doesn’t end up using X user credentials to log in.

3) Also, when using those cookies options, what am I saving exactly? In the authentication page should I manually create a cookie to be stored on that file? if so, what cookie? I need to keep the Digest Auth Credentials, which I think is a header with nonce, cnonce, nc, username, response, etc. Not sure if this is actually the way around it.

Источник

php curl with digest returns two responses

I have spotted a «weird» php CURL behavior that is sending me nuts. Basically what I am doing is making a digest authenticated call with curl. Here’s an extract of my code:

It works fine and the server actually comes back with a «YES, YOU PROVIDED THE RIGHT CREDENTIALS» kind of message. Only trouble is, the raw http response is a bit odd as it includes, as a matter of fact, 2 responses instead of one. Here’s what curl_exec($this->c) spits out:

I don’t get why it includes the first response from the server (the one in which it states it requires authentication).

Can anyone throw some light on the issue? How do I avoid the responses’ cumulation?

2 Answers 2

To only get the second header you could try this (not very optimal solution):

curl digest auth php

I hit the same problem, and I think it was caused by PHP being compiled against an ancient version of libcurl (7.11.0 in my case, which is now nearly 10 years old). On a different machine with a more recent version of libcurl (7.29.0) the same code was fine, and my problems ended after getting my host to recompile their PHP to use the latest they had available (7.30.0).

This fix was suggested by a thread on the curl-library mailing list from 2008, where a user discovered the problem affected version 7.10.6 but not 7.12.1. I’ve searched the libcurl changelog around 7.12.0 and failed to find any clear entry about fixing this problem, though it might be covered by «general HTTP authentication improvements». Still, I’m now pretty confident that an old libcurl is the problem.

You can check which version of libcurl is used by your PHP from the ‘cURL Information’ entry in the output of phpinfo();

Not the answer you’re looking for? Browse other questions tagged php curl or ask your own question.

Linked

Related

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.16.40224

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

How do I send a digest auth request using curl?

While searching for a guide I found this example on Wikipedia

(it would be great if there is a tool/site that converts requests from this form raw requests to curl command)

this the realm and nonce when I try to send a normal get request to the site.

After searching online again for a little bit I got that the command should be like this

but I didn’t get where to put the nonce or the realm or the qop or algorithm=»MD5″

2 Answers 2

You don’t have to specify all those values anywhere. The only thing you do have to is username/password pair. CURL takes care of computing the client response for you. This is exactly what «supporting of digest authentication» means for any client.

answer by user Alexey R. from stack over flow

in addition by a user on another site the command should look like this

When using Digest authentication, you need to send an HTTP «Authorization» header, and this header is where the nonce etc should go.

However, Digest uses a challenge/response mechanism that requires the Authorization header to be sent in a second HTTP request, rather than in the original HTTP request.

The second HTTP request can only be sent once the original HTTP request has received a 401 response.

You should be able to get the idea from this closed GitHub issue where it’s explained further about the way curl works with this.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *