Skip to content

Instantly share code, notes, and snippets.

@reymons
Last active January 24, 2021 19:04
Show Gist options
  • Save reymons/221e81c432d45e3efd15d48fb536bd6b to your computer and use it in GitHub Desktop.
Save reymons/221e81c432d45e3efd15d48fb536bd6b to your computer and use it in GitHub Desktop.
Работа с протоколом HTTPS через openssl
Цель: получить практические навыки по работе с HTTPS протоколом посредством openssl. Научиться создавать сертификаты.
Ход работы:
Задание 1.
Подключиться по openssl к https://wikipedia.org и отправить запрос:
openssl s_client -connect wikipedia.org:443
GET /wiki/страница HTTP/1.1
Host: ru.wikipedia.org
User-Agent: Mozilla/5.0 (X11; U; Linux i686; ru; rv:1.9b5) Gecko/2008050509 Firefox/3.0b5
Accept: text/html
Connection: close
(пустая строка)
После выполнения данного запроса к серверу, был получен следующий ответ:
<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8">
<title>Wikimedia Error</title>
<style>
* { margin: 0; padding: 0; }
body { background: #fff; font: 15px/1.6 sans-serif; color: #333; }
.content { margin: 7% auto 0; padding: 2em 1em 1em; max-width: 640px; }
.footer { clear: both; margin-top: 14%; border-top: 1px solid #e5e5e5; background: #f9f9f9; padding: 2em 0; font-size: 0.8em; text-align: center; }
img { float: left; margin: 0 2em 2em 0; }
a img { border: 0; }
h1 { margin-top: 1em; font-size: 1.2em; }
.content-text { overflow: hidden; overflow-wrap: break-word; word-wrap: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; -ms-hyphens: auto; hyphens: auto; }
p { margin: 0.7em 0 1em 0; }
a { color: #0645ad; text-decoration: none; }
a:hover { text-decoration: underline; }
code { font-family: sans-serif; }
.text-muted { color: #777; }
</style>
<div class="content" role="main">
<a href="https://www.wikimedia.org"><img src="https://www.wikimedia.org/static/images/wmf-logo.png" srcset="https://www.wikimedia.org/static/images/wmf-logo-2x.png 2x" alt="Wikimedia" width="135" height="101">
</a>
<h1>Error</h1>
<div class="content-text">
<p>Our servers are currently under maintenance or experiencing a technical problem.
Please <a href="" title="Reload this page" onclick="window.location.reload(false); return false">try again</a> in a few&nbsp;minutes.</p>
<p>See the error message at the bottom of this page for more&nbsp;information.</p>
</div>
</div>
<div class="footer"><p>If you report this error to the Wikimedia System Administrators, please include the details below.</p><p class="text-muted"><code>Request from 37.79.42.190 via cp3056 cp3056, Varnish XID 118135765<br>Upstream caches: cp3056 int<br>Error: 400, at Sat, 19 Dec 2020 11:52:30 GMT</code></p>
</div>
</html>
closed
Была получена верстка страница , а также сообщение "closed", что говорит о закрытии подключения.
Задание 2.
1) Создать ключ шифрования для работы по зашифрованному каналу связи.
Вводим следующую запись: openssl req -new -x509 -keyout key.pem -out server.pem -days 365 -nodes
Далее просит ввести данные для ключа:
Country Name (2 letter code) [AU]:RU
State or Province Name (full name) [Some-State]:Moscow
Locality Name (eg, city) []:Moscow
Organization Name (eg, company) [Internet Widgits Pty Ltd]:Some-Company
Organizational Unit Name (eg, section) []:Some-Section
Common Name (e.g. server FQDN or YOUR name) []:Waffen
Email Address []:[email protected]
2) Поднять веб сервер работающий по протоколу HTTPS
Вводим:
import ssl
from http.server import HTTPServer, SimpleHTTPRequestHandler
httpd = HTTPServer(("0.0.0.0", 4443), SimpleHTTPRequestHandler)
httpd.socket = ssl.wrap_socket(
httpd.socket,
certfile="server.pem",
keyfile="key.pem",
server_side=True,
ssl_version=ssl.PROTOCOL_TLS,
)
httpd.serve_forever()
Далее в терминале вводим
$ openssl s_client -connect 127.0.0.1:4443
В другом терминале выполним: openssl s_client -connect 127.0.0.1:4443
Благодаря сведениям из ключа при создании сертификата известны сведения о сервере:
Затем создаётся сертификат и открывается TLS-соединение.
Сделаем в нем GET-запрос. Сервер возвращает:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Directory listing for /</title>
</head>
<body>
<h1>Directory listing for /</h1>
<hr>
<ul>
<li><a href="__pycache__/">__pycache__/</a></li>
<li><a href="key.pem">key.pem</a></li>
<li><a href="server.pem">server.pem</a></li>
<li><a href="server.py">server.py</a></li>
</ul>
<hr>
</body>
</html>
Задание 3.
Отправить запросы на http://httpbin.org, проанализировать ответ и код состояния. Описать работу HTTP протокола в каждом запросе.
1) Запросить данные GET запросом с ресурса ip
GET /ip HTTP/1.1
Host: httpbin.org
Accept: */*
Ответ:
HTTP/1.1 200 OK
Date: Sat, 19 Dec 2020 16:50:03 GMT
Content-Type: application/json
Content-Length: 31
Connection: keep-alive
Server: gunicorn/19.9.0
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
{
"origin": "37.79.42.190"
}
Произошло успешное подключение (код 200)
2) Выполнить запрос методом GET
GET /get?foo=bar&1=2&2/0&error=True HTTP/1.1
Host: httpbin.org
Accept: */*
Ответ:
HTTP/1.1 200 OK
Date: Sat, 19 Dec 2020 16:54:47 GMT
Content-Type: application/json
Content-Length: 322
Connection: keep-alive
Server: gunicorn/19.9.0
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
{
"args": {
"1": "2",
"2/0": "",
"error": "True",
"foo": "bar"
},
"headers": {
"Accept": "*/*",
"Host": "httpbin.org",
"X-Amzn-Trace-Id": "Root=1-5fde3057-037af1643c611dc05fd189db"
},
"origin": "37.79.42.190",
"url": "https://httpbin.org/get?foo=bar&1=2&2%2F0&error=True"
}
Произошло подключение (код 200), при этом загрузив страницу с определенными аргументами.
3)Выполнить запрос методом POST
POST /post HTTP/1.1
Host: httpbin.org
Accept: */*
Content-Length: вычислить длину контента и втавить сюда число!!!
Content-Type: application/x-www-form-urlencoded
foo=bar&1=2&2%2F0=&error=True
Ответ:
HTTP/1.1 200 OK
Date: Sat, 19 Dec 2020 17:12:23 GMT
Content-Type: application/json
Content-Length: 446
Connection: keep-alive
Server: gunicorn/19.9.0
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
{
"args": {},
"data": "",
"files": {},
"form": {
"1": "2",
"2/0": "",
"error": "True",
"foo": "bar"
},
"headers": {
"Accept": "*/*",
"Content-Length": "29",
"Content-Type": "application/x-www-form-urlencoded",
"Host": "httpbin.org",
"X-Amzn-Trace-Id": "Root=1-5f9da855-610c5e7358d1caac17b1f4aa"
},
"json": null,
"origin": "82.193.155.224",
"url": "https://httpbin.org/post"
}
Запрос прошел (200 код). Были так же, как и в 2) пункте заданы параметры.
4) Отправить запрос на установку Cookie
Вводим:
GET /cookies/set?country=Ru HTTP/1.1
Host: httpbin.org
Accept: */*
Ответ:
HTTP/1.1 302 FOUND
Date: Sat, 19 Dec 2020 17:16:18 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 223
Connection: keep-alive
Server: gunicorn/19.9.0
Location: /cookies
Set-Cookie: country=Ru; Path=/
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>Redirecting...</title>
<h1>Redirecting...</h1>
<p>You should be redirected automatically to target URL: <a href="/cookies">/coo
kies</a>. If not click the link.
Происходит перенаправление как и с telnet.
5) Просмотреть список установленных Cookie
Вводим:
GET /cookies HTTP/1.1
Host: httpbin.org
Accept: */*
Ответ:
HTTP/1.1 200 OK
Date: Sat, 31 Dec 2020 17:21:06 GMT
Content-Type: application/json
Content-Length: 20
Connection: keep-alive
Server: gunicorn/19.9.0
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
{
"cookies": {}
}
Поле пустое, т. к. на прошлом шаге произошло перенаправление, а не установка.
6. Отправить запрос на страницу с перенаправлением
Вводим:
GET /redirect/4 HTTP/1.1
Host: httpbin.org
Accept: */*
Ответ:
HTTP/1.1 404 Not Found
Server: awselb/2.0
Date: Sat, 19 Dec 2020 17:26:01 GMT
Content-Type: text/plain; charset=utf-8
Content-Length: 0
Connection: keep-alive
Обратиться к сайту не получилось, но пример перенаправления можно увидеть в 5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment