Код ошибки ssl error bad mac read

Firefox logo

Secure Connection Failed
SSL received a record with an incorrect Message Authentication Code. (Error code: ssl_error_bad_mac_read)

I have been receiving this error message recently when I tried to access school elearning websites and other school related websites, I have also tried on internet explorer and it shows page cannot be displayed. I have been trying the available solutions to solve it but none of them work. Is there alternative solutions available? Please advise. Thanks.

Secure Connection Failed
SSL received a record with an incorrect Message Authentication Code. (Error code: ssl_error_bad_mac_read)

I have been receiving this error message recently when I tried to access school elearning websites and other school related websites, I have also tried on internet explorer and it shows page cannot be displayed. I have been trying the available solutions to solve it but none of them work. Is there alternative solutions available? Please advise. Thanks.

Chosen solution

All Replies (6)

Can you post a link to a publicly accessible page that doesn’t require authentication (signing on)?

Can you reach this page via a normal http connection in case the server isn’t set up properly?

You may have to use «Forget About This Site» to make Firefox use a http connection.

You can try to test if there is a problem with TLS by temporarily disabling TLS.

You can set the security.tls.version.min and security.tls.version.max prefs to 0 to disable TLS (0 means SSL3).
You may need to close and restart Firefox after changing these prefs.

security.tls.version.min = 0
security.tls.version.max = 0
  • http://kb.mozillazine.org/security.tls.version.*
    0 means SSL 3.0, 1 means TLS 1.0, 2 means TLS 1.1, etc.
  • http://kb.mozillazine.org/about:config

Note that this is only meant as a quick test and you should reset the two prefs afterward.

Thank you for your advice, I’ve tried temporarily disabling TLS and restart Firefox but it didn’t work.

Sorry, but may I ask you what do you mean by:

«Can you post a link to a publicly accessible page that doesn’t require authentication (signing on)?

Can you reach this page via a normal http connection in case the server isn’t set up properly?»

That is about the address (URL) of the website that you try to visit.

Then we can see if the problem occurs for us as well or only a problem on your side.

It works after I disabled IPv6 in Firefox. Thank you for your help  :)

При открытии некоторых сайтов в Mozilla Firefox доступ к их содержимому может быть заблокирован ошибкой SSL_Error_Bad_Mac_Alert. Во многих случаях проблема возникает по причине того, что не выполняется проверка SSL.

Неправильная дата и время также могут привести к аннулированию сертификата безопасности, что в конечном итоге заставит браузер прервать соединение. Поэтому перед применением решений проверьте, правильно ли они установлены. Щелкните на часы в области уведомлений и выберите настройку даты и времени. Переместите переключатели автоматической установки времени и часового пояса в положение «Включено».

Содержание

  • 1 Добавление сайта в список незащищенных резервных хостов
  • 2 Перезагрузка роутера
  • 3 Активация параметра Security.SSL3

Добавление сайта в список незащищенных резервных хостов

Если сталкиваетесь с ошибкой SSL_Error_Bad_Mac_Alert при посещении сайта, уровень защиты на котором не вызывает у вас сомнений, то можете добавить его в список небезопасных резервных хостов. Таким образом, он будет исключен из проверки SSL, которая вызывала ошибку.

Имейте в виду, что это решение применимо только для защищенных сайтов https (c сертификатом ssl), которому полностью доверяете. Избегайте добавления сомнительных сайтов в список небезопасных хостов.

Если осознаете риски для безопасности, следуйте инструкции.

В адресной строке браузера Firefox наберите «about:config» и нажмите на Enter для входа в меню расширенных настроек.

При отображении окна «Продолжайте с осторожностью» кликните на кнопку «Принять рис и продолжить».

В навигационную строку вставьте «security.tls.insecure_fallback_hosts». При отображении искомого параметра нажмите на значок редактирования. В текстовом поле введите URL-адрес и нажмите на Enter.

После перезапуска Firefox попробуйте открыть страницу, доступ к которой был заблокирован ошибкой SSL_Error_Bad_Mac_Alert.

Перезагрузка роутера

Ошибка с доступом на отдельные ресурсы может произойти из-за несогласования сети. Возможно, что ее текущее состояние зависло в неопределенном состоянии, при котором блокируется возможность взаимодействия компьютера с внешними серверами через браузер.

Поэтому если сталкиваетесь с ошибкой SSL_Error_Bad_Mac_Alert, попробуйте перезапустить роутер. Отключите устройство, затем подождите 30 секунд прежде чем включить его обратно. После установки подключения проверьте, решена ли проблема.

Активация параметра Security.SSL3

Если столкнулись с сообщением SSL_Error_Bad_Mac_Alert после обновления Firefox, то, скорее всего, в расширенных настройках был отключен параметр Security.SSL3. Для его включения выполните следующие шаги:

В адресной строке наберите «about:config» и нажмите на Enter для входа в расширенные настройки. При отображении предупреждения кликните на кнопку «Принять риск и продолжить».

В строке поиска наберите Security.SSL3.

При отображении результатов прокрутите вниз и найдите параметр «Security.SSL3». Установите значение «true», и перезагрузите браузер Firefox.

Перейдите на страницу, на которой сталкивались с кодом ошибки SSL_Error_Bad_Mac_Alert и посмотрите, решена ли проблема.

Ошибка «ssl_error_bad_mac_alert» обычно возникает в Mozilla Firefox, когда затронутые пользователи пытаются посетить определенные защищенные веб-сайты. В некоторых случаях ошибка появляется, когда пользователь пытается отправить электронную почту через интерфейс IMAP в Gmail.

Mozilla Firefox ssl_error_bad_mac_alert Ошибка

Мы проанализировали несколько пользовательских отчетов, чтобы найти потенциальные причины — как оказалось, эта проблема может возникать из-за того, что не удается выполнить определенную проверку SSL, что вынуждает браузер выдавать эту ошибку и ограничивать доступ пользователя к веб-сайту. В этом случае вы можете легко решить эту проблему, открыв расширенное меню настроек Firefox и добавив веб-сайт в список незащищенных хостов FallBack.

Другая потенциальная причина, которая может привести к такому поведению браузера, — это сетевое соединение, которое блокирует связь между вашим браузером и внешними серверами. В этом случае вы можете устранить проблему, выполнив процедуру включения и выключения питания на маршрутизаторе или модеме, заставив вашу сеть начать все сначала.

Один из сценариев, который может заставить ваш браузер сделать недействительными сертификаты SSL и вызвать эту ошибку, в результате — неверное общесистемное время и дата. Несколько пользователей, столкнувшихся с той же проблемой, сообщили, что им наконец удалось решить проблему после того, как они получили доступ к настройкам даты и времени и соответственно обновили значения.

Оказывается, что для некоторых старых конфигураций компьютеров потребуется дополнительная расширенная настройка Firefox, чтобы можно было без ошибок подключаться к веб-серверам SSL3. Если этот сценарий применим, вы можете решить эту проблему, открыв вкладку «Дополнительные настройки» и установив для параметра security.ssl3 значение True.

1. Добавление сайта в список небезопасных хостов FallBack

Если вы уверены, что веб-сайт SSL, на котором вы столкнулись с проблемой, полностью безопасен, вы можете предотвратить повторное появление SSL_Error_Bad_Mac_Alert, открыв конфигурационные файлы Mozilla Firefox и добавив безопасный SSL в список незащищенных хостов FallBack.

Это будет за исключением веб-сайта, которому вы доверяете, из проверки SSL, которая ранее вызывала проблему. Многие пострадавшие пользователи подтвердили, что именно эта процедура позволила им избавиться от проблемы на неопределенный срок.

ВАЖНО: Это следует делать только на защищенном SSL-сайте, которому вы полностью доверяете. Не добавляйте сомнительные веб-сайты в список небезопасных хостов FallBack.

Если вы понимаете риски безопасности и готовы добавить веб-сайт в список небезопасных хостов FallBack Firefox, следуйте приведенным ниже инструкциям:

  1. Откройте браузер Mozilla Firefox, введите «about: config» на панели навигации и нажмите «Enter», чтобы открыть меню «Дополнительные настройки».
  2. Когда вы увидите подсказку «Продолжить с осторожностью», нажмите «Принять риск» и «Продолжить».
  3. Как только вы окажетесь в меню расширенных настроек, вставьте security.tls.insecure_fallback_hosts в панель навигации и нажмите Enter, чтобы найти настройку.
  4. Когда результаты появятся, нажмите на значок «Редактировать», связанный с записью security.tls.insecure_fallback_hosts (правая часть).
  5. В появившемся текстовом поле просто введите URL-адрес веб-сайта, с которым вы столкнулись с проблемой, и нажмите Enter.
  6. Перезапустите браузер Mozilla Firefox и посмотрите, будет ли проблема решена при следующем запуске программы.

Добавление защищенного SSL сайта в качестве хоста Fallback

Если вы все еще сталкиваетесь с той же ошибкой security.tls.insecure_fallback_hosts или ищете подход, который не подвергает вашу систему каким-либо угрозам безопасности, перейдите к следующему потенциальному исправлению ниже.

2. Включение питания маршрутизатора / модема

Как выясняется, эта конкретная проблема также может возникнуть из-за несогласованности сети. Возможно, ваше текущее состояние сети застряло в подвешенном состоянии. Это может заблокировать возможность вашего ПК общаться с внешними веб-серверами через ваш браузер.

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

Чтобы запустить процедуру включения / выключения питания, нажмите кнопку ON / OFF и оставьте сетевое устройство выключенным не менее 30 секунд или более. Если вы хотите убедиться, что операция прошла успешно, также отсоедините кабель питания от электрической розетки. Это заставит вашу сеть начать заново при следующем запуске маршрутизатора / модема.

Перезапуск роутера / модема

Примечание: не путайте кнопку питания с кнопкой сброса. Кнопка сброса сбрасывает все ранее установленные сетевые настройки и пользовательские учетные данные.

Если вы уже сделали это и по-прежнему сталкиваетесь с той же проблемой, перейдите к следующему потенциальному исправлению ниже.

3. Установка правильного времени и даты

Как выясняется, еще одна причина, по которой ваш Mozilla Firefox может вызвать ошибку security.tls.insecure_fallback_hosts, заключается в несовместимости даты и времени. Это может сделать недействительным сертификат безопасности, заставив ваш браузер прервать соединение.

Если этот сценарий применим, вы можете решить проблему, открыв настройки даты и времени и изменив значения до текущих. Несколько затронутых пользователей, столкнувшихся с той же проблемой, подтвердили, что эта операция, наконец, остановила появление сообщения об ошибке.

  1. Откройте диалоговое окно «Выполнить», нажав клавишу Windows + R. Затем введите «timedate.cpl» и нажмите Enter, чтобы открыть окна «Дата и время».Открытие окна даты и времени
  2. Как только вам удастся попасть внутрь окна «Дата и время», перейдите на вкладку «Дата и время» и нажмите «Изменить дату и время».Установка правильной даты и времени
  3. В окне «Дата и время» используйте предоставленный календарь, чтобы установить соответствующие значения даты и времени.Изменение времени и даты
  4. После того, как изменения были завершены, перезагрузите компьютер и посетите тот же веб-сайт и следующую последовательность запуска, чтобы увидеть, решена ли проблема.

Если вы все еще сталкиваетесь с той же ошибкой ssl_error_bad_mac_alert, перейдите к следующему потенциальному исправлению ниже.

4. Установка Security.SSL3 на TRUE

Если вы столкнулись с проблемой со старой машиной, которая не является общедоступной, вы можете получить ошибку «ssl_error_bad_mac_alert» с большим количеством действительных веб-серверов SSL, пока не найдете время для доступа к Расширенным настройкам Firefox и включения Security.SSL3.

Если вы заметили, что ошибка внезапно начала появляться после обновления самого Firefox, скорее всего, вы столкнулись с проблемой из-за того, что Security.SSL3 по умолчанию отключен.

Вот краткое руководство по включению Security.SSL3 в вашем браузере Firefox:

  1. Откройте браузер Firefox, введите «about: config» и нажмите «Enter», чтобы открыть меню «Дополнительные настройки».
  2. Когда вы увидите приглашение «Продолжить с осторожностью», нажмите кнопку «Принять риск и продолжить».
  3. В меню «Дополнительные настройки» используйте меню поиска вверху для поиска security.ssl3 и нажмите клавишу «Ввод», чтобы просмотреть результаты.
  4. Как только результаты будут получены, прокрутите вниз до нижней части экрана и найдите security.ssl3.
    Примечание. Если у вас есть возможность выбрать строку, логическое значение и число с плавающей запятой, выберите логическое значение.
  5. Затем убедитесь, что значение security.ssl3 установлено в true, затем сохраните изменения и перезапустите браузер Mozilla Firefox.
  6. Посетите тот же веб-сайт, на котором ранее отображалась ошибка «ssl_error_bad_mac_alert», и посмотрите, решена ли проблема в настоящее время.

Включение Security.SSL3 через Расширенные настройки

The ‘ssl_error_bad_mac_alert‘ error typically occurs in Mozilla Firefox when affected users attempt to visit certain secured websites. In some cases, the error appears when the user attempts to send emails via the IMAP interface to Gmail.

Mozilla Firefox ssl_error_bad_mac_alert Error

We have analysed several user reports to find potential causes – as it turns out, this issue can occur due to the fact that a certain SSL check is failing, forcing the browser to throw this error and restrict the user from accessing the website. In this case, you can resolve the issue easily by accessing the advanced Firefox Preference menu and adding the website to the list of Insecure FallBack Hosts.

Another potential cause that might lead to this browser behavior is a network connection that ends up blocking communications between your browser and external servers. In this case, you can fix the issue by performing a power-cycling procedure on your router or modem, forcing your network to start fresh.

One scenario that might force your browser to invalidate SSL certificates and throw this error, as a result, is an incorrect system-wide time & date. Several users encountering the same problem have reported that they finally managed to resolve the issue after they accessed the Date and Time settings and updated the values accordingly.

It turns out that certain older machine configurations will need a certain Firefox advanced setting advanced in order to be able to connect to SSL3 web-servers without errors. If this scenario is applicable, you can fix the issue by accessing the Advanced Preferences tab and setting the value of security.ssl3 to True.

1. Adding Website to the list of Insecure FallBack Hosts

If you’re certain that the SSL website where you’re encountering the issue is completely secure, you can prevent the SSL_Error_Bad_Mac_Alert from ever appearing again by accessing the Mozilla Firefox config files and adding the secure SSL to the list of Insecure FallBack Hosts.

This will except the website you trust from the SSL check that was previously causing the issue. A lot of affected users have confirmed that this procedure is what allowed them to get rid of the issue indefinitely.

IMPORTANT: This should only be attempted with an SSL secured website that you completely trust. Do not add questionable websites to the list of Insecure FallBack Hosts.

If you understand the security risks and you’re prepared to add the website to the Firefox list of Insecure FallBack Hosts, follow the instructions here:

  1. Open up your Mozilla Firefox browser, type ‘about:config‘ in the navigation bar and press Enter to open up the Advanced Preferences menu.
  2. When you see the Proceed with Caution prompt, click on Accept the Risk and Continue.
  3. Once you’re inside the Advanced Preferences menu, paste security.tls.insecure_fallback_hosts into the navigation bar and press Enter to find the setting preference.
  4. When the results show up, click on the Edit icon associated with security.tls.insecure_fallback_hosts entry (right-hand section).
  5. In the newly appeared text box, simply enter the website URL that you’re encountering the issue with and hit Enter.
  6. Restart your Mozilla Firefox browser and see if the issue is resolved at the next program startup.

Adding the SSL secured website as Fallback host

In case you’re still encountering the same security.tls.insecure_fallback_hosts error or you’re looking for an approach that will not expose your system to any security risks, move down to the next potential fix below.

2. Power-Cycling the Router / Modem

As it turns out, this particular issue can also occur due to a network inconsistency. It’s possible that your current network state is stuck in a limbo state. This might block your PC ability to communicate with external web servers through your browser.

If this scenario is applicable, you can most likely fix the issue by performing a power-cycling procedure on your router. This operation should not be confused with a router reset. Opposite from a reset, this will not affect your credentials and any previously established.

To initiate a power-cycling procedure, press the ON / OFF button and leave the network device turned off at least 30 seconds or more. If you want to make sure that the operation is a success, also disconnect the power cable from your power outlet. This will force your network to start fresh at the next router/modem startup.

Restarting your router/modem

Note: Do not confuse the power button with the reset button. The reset button will reset every previously established network settings and custom credentials.

If you already did this and you’re still encountering the same issue, move down to the next potential fix below.

3. Setting the Correct time & Date

As it turns out, another reason that might make your Mozilla Firefox throw the security.tls.insecure_fallback_hosts error is an inconsistent date & time. This might invalidate the security certificate, forcing your browser to interrupt the connection.

If this scenario is applicable, you can fix the issue by accessing your Date & time settings and modifying the values to the current values. Several affected users encountering the same issue have confirmed that this operation finally stopped the error message from appearing.

  1. Open up a Run dialog box by pressing Windows key + R. Next, type ‘timedate.cpl’ and press Enter to open the Date and time windows.
    Opening the Date and time window
  2. Once you manage to get inside the Date & Time window, navigate to the Date and Time tab and click on Change date and time.
    Setting the correct date & time
  3. Inside the Date and Time window, use the provided calendar to set the appropriate Date and Time values.
    Modifying Time & date
  4. Once the modifications have been completed, restart your computer and visit the same website ad the next startup sequence to see if the issue is resolved.

In case you’re still encountering the same ‘ssl_error_bad_mac_alert‘ error, move down to the next potential fix below.

4. Setting Security.SSL3 to TRUE

If you’re encountering the issue with an old machine that is not publicly exposed, you might get the ‘ssl_error_bad_mac_alert‘ error with a lot of valid SSL web servers until you find the time to access Firefox’s Advanced Preferences and enable Security.SSL3.

In case you noticed that the error suddenly started occurring after Firefox updated itself, chances are you’re encountering the problem due to the fact that Security.SSL3 is disabled by default.

Here’s a quick guide on ensuring that Security.SSL3 is enabled on your Firefox browser:

  1. Open your Firefox browser, type ‘about:config‘ and press Enter to access the Advanced Preferences menu.
  2. When you see the ‘Proceed with Caution‘ prompt, click on the Accept the Risk and Continue button.
  3. Inside the Advanced Preferences menu, use the search menu at the top to search for security.ssl3 and press Enter to see the results.
  4. Once the results are in, scroll down to the bottom fo the screen and locate security.ssl3.
    Note: If you have the option to choose from a string, boolean and float, choose boolean.
  5. Next, ensure that the value of security.ssl3 is set to true, then save the modifications and restart your Mozilla Firefox browser.
  6. Visit the same website that was previously displaying the ‘ssl_error_bad_mac_alert‘ error and see if the issue is now resolved.

Enabling Security.SSL3 via Advanced Preferences

Photo of Kevin Arrows

Kevin Arrows

Kevin is a dynamic and self-motivated information technology professional, with a Thorough knowledge of all facets pertaining to network infrastructure design, implementation and administration. Superior record of delivering simultaneous large-scale mission critical projects on time and under budget.

Facing ERR_SSL_BAD_RECORD_MAC_ALERT error when you try to access a web address, Right? Here ClickSSL guide can help you.

An SSL Certificate makes use of cryptography to transmit information between the server and the client securely. However, there are times when specific network interferences or interruptions can cause SSL errors like the ERR_SSL_BAD_RECORD_MAC_ALERT pop-up. This is one of the most annoying errors that keep you from accessing even the most reputed and trusted websites. Nevertheless, you must fix it as early as possible so that you can access your favorite websites without any further inconvenience.

What is ERR_SSL_BAD_RECORD_MAC_ALERT?

The ERR_SSL_BAD_RECORD_MAC_ALERT error is exclusive to the Chrome browser and may arise due to several reasons, which are either directly or indirectly connected to data transmission. Although pinpointing the exact cause for this issue might not be an easy thing to do, fixing it is, and that is precisely what you should focus on. If this is the first time you have encountered this type of error, you are probably worried about your safety, but you don’t have to.

This technical glitch is often caused due to some underlying problem on the client computer and can be easily verified. You can confirm that by trying to access legitimate websites like paypal.com that already have an SSL certificate installed and are running on the HTTPS protocol. If you continue to encounter the same error, it only confirms the above stated — it is a client-side issue that you need to resolve. As we have already mentioned, detecting the cause for this issue may not always be possible — not until you find a suitable solution, so you will have to try them out one by one. Let us now discuss some of the most effective ways to solve the ERR_SSL_BAD_RECORD_MAC_ALERT error.

1. Update your OS

Do you have a licensed operating system and update it from time to time? Probably not! But doing that could help resolve this SSL error and many other pre-existing vulnerabilities in your system. Your OS maker releases security patches from time to time in the form of updates. Downloading and installing those updates can not only prevent security concerns but can also fix technical glitches this SSL error.

Follow the below-mentioned steps to update your Windows OS right away.

  • Click on the windows button and type ‘Settings’ in the search bar
  • Click on Settings
  • Click on the ‘Updates and Security’ Option
  • Click on the ‘Download and Install’ Option

windows update

Once you are done updating your system, you might be prompted to restart your computer.

2. Update Google Chrome

Sometimes, updating the Google Chrome browser can resolve the ERR_SSL_BAD_RECORD_MAC_ALERT issue. You can do that by clicking on the three vertical dots on the top-right corner of the Chrome Browser and clicking on ‘more’. If you find the ‘update’ option, you need to click on that to update your browser.

On the other hand, if you do not see that option, it only indicates that your Chrome Browser is up to date. You can always confirm that by clicking on the three vertical dots on the top-right corner and then on ‘help’ and ‘About Google Chrome’. If your system is up to date, you will find a message like the one shown in the image below.

update google chrome

3. Antivirus

If you recently installed an Antivirus and have been experiencing this error ever since you already know what the problem is. It is never a good idea to meddle with your antivirus’ settings, but sometimes it becomes inevitable. Particularly, when you are using one that inspects the HTTPS and blocks out potentially dangerous traffic. In that case, you need to deactivate the HTTPS Inspection from your antivirus’ settings. However, please do this at your own risk and continue to avoid websites without SSL certificates installed on them.

4. Stop using Advanced Streaming Technologies

If you fancy high-speed internet, you most likely have a speed optimizing application or more advanced technology like a Killer Network card installed on your system. That could very well be the root cause of the ERR_SSL_BAD_RECORD_MAC_ALERT issue. The application or the Killer Network assigns a high priority to the data packets to boost the internet speed, which can sometimes cause this SSL error.

You can conveniently fix that by simply turning down the ‘Stream Detect’ function in your Killer Control Center or by uninstalling the speed-boosting application. Sometimes, your Killer Network card might need a more advanced solution. In that case, uninstall it by following the steps listed below.

  • You need to first download the uninstaller tool from here
  • Next, choose the Remove Killer Software option to uninstall
  • Finally, restart the computer when prompted to do that, and you are done

Remember that fixing this issue could lower your internet speed, so you must be prepared for that.

5. Fix your Router

If none of the above fixes worked, your router could very well be the culprit. You can fix that by adjusting the Maximum Transmission Unit (MTU) of your router. This might sound a tad bit technical, but all it means is the maximum packet size that can be transmitted over the network. It is an advanced configuration that can be readjusted easily by typing 192.168.0.1. or 192.168.1.1. in the URL bar.

You can then look for the MTU settings under WAN and change it to 1400. In most cases, this should solve the problem, but we must mention that different routers may have different IPs and the ones mentioned above are the default ones.

Conclusion

We have discussed some of the most common ways to fix the ERR_SSL_BAD_RECORD_MAC_ALERT error, and one of those should work for you. None of these methods requires you to have any technical expertise, so try them out one at a time. Once you have resolved the error, do let us know which one worked out for you.

Recommended Reading:

  • NET::ERR_CERT_AUTHORITY_INVALID Error on Google Chrome
  • ERR_BAD_SSL_CLIENT_AUTH_CERT for Google Chrome
  • NET::ERR_Certificate_Transparency_Required
  • ERR_SSL_PROTOCOL_ERROR on Google Chrome
  • ERR_CONNECTION_REFUSED in Chrome

Many Thanks to @steffen-ullrich, This is final solution for who comes later. works for http/https:

package main

import (
    "fmt"
    "net"
    "strings"
)

func main() {
    fmt.Println("Start server...")

    ln, _ := net.Listen("tcp", ":8000")

    for {
        conn, _ := ln.Accept()
        handleSocket(conn)
    }
}

func handleSocket(client_to_proxy net.Conn) {
    buffer := make([]byte, 32*1024)
    _, e := client_to_proxy.Read(buffer)
    if e != nil {
        fmt.Println("ERROR1 ", e)
        return
    }
    message := string(buffer)
    a := strings.Count(message, "rn")
    fmt.Println(message)
    fmt.Println(a)
    if e != nil {
        fmt.Println("ERROR1 ", e)
        return
    }

    splited := strings.Split(message, " ")
    //host := strings.Split(splited[1], ":")
    if splited[0] == "CONNECT" {
        //message = strings.Replace(message, "CONNECT", "GET", 1)
        proxy_to_server, e := net.Dial("tcp", splited[1])
        if e != nil {
            fmt.Println("ERROR2 ", e)
            return
        }
        //_, e = proxy_to_server.Write([]byte(message))
        //if e != nil {
        //  fmt.Println("ERROR2 ", e)
        //  return
        //}
        lenn, e := client_to_proxy.Write([]byte("HTTP/1.1 200 OKrnrn"))
        if e != nil {
            fmt.Println("ERROR8 ", e)
            return
        }
        fmt.Println(lenn)

        read443(client_to_proxy, proxy_to_server)
    } else if splited[0] == "GET" {
        host1 := strings.Replace(splited[1], "http://", "", 1)
        host2 := host1[:len(host1)-1]
        var final_host string
        if strings.LastIndexAny(host2, "/") > 0 {
            final_host = host2[:strings.LastIndexAny(host2, "/")]
        } else {
            final_host = host2
        }
        proxy_to_server, e := net.Dial("tcp", final_host+":80")
        if e != nil {
            fmt.Println("ERROR7 ", e)
            return
        }
        _, e = proxy_to_server.Write([]byte(message))
        if e != nil {
            fmt.Println("ERROR6 ", e)
            return
        }

        write80(client_to_proxy, proxy_to_server)
    }
}

func write80(client_to_proxy net.Conn, proxy_to_server net.Conn) {
    buffer := make([]byte, 64*1024)

    readLeng, err := proxy_to_server.Read(buffer)
    if err != nil {
        fmt.Println("ERROR9 ", err)
        return
    }
    fmt.Println("WRIIIIIIIIIIIIIIIIIIIIIIT from server:")
    fmt.Println(string(buffer[:readLeng]))
    if readLeng > 0 {
        _, err := client_to_proxy.Write(buffer[:readLeng])
        if err != nil {
            fmt.Println("ERR4 ", err)
            return
        }
    }

    go read80(client_to_proxy, proxy_to_server)
    for {
        readLeng, err := proxy_to_server.Read(buffer)
        if err != nil {
            fmt.Println("ERROR10 ", err)
            return
        }
        fmt.Println("WRIIIIIIIIIIIIIIIIIIIIIIT from server:")
        fmt.Println(string(buffer[:readLeng]))
        if readLeng > 0 {
            _, err := client_to_proxy.Write(buffer[:readLeng])
            if err != nil {
                fmt.Println("ERR4 ", err)
                return
            }
        }
    }
}

func read80(client_to_proxy net.Conn, proxy_to_server net.Conn) {
    buffer := make([]byte, 32*1024)

    for {
        readLeng, err := client_to_proxy.Read(buffer)
        if err != nil {
            return
        }
        fmt.Println("REEEEEEEEEEEEEEEEEEEEEEED from client:")
        fmt.Println(string(buffer[:readLeng]))
        if readLeng > 0 {
            _, err := proxy_to_server.Write(buffer[:readLeng])
            if err != nil {
                fmt.Println("ERR5 ", err)
                return
            }
        }
    }
}

func write443(client_to_proxy net.Conn, proxy_to_server net.Conn) {
    buffer := make([]byte, 32*1024)
    for {
        readLeng, err := proxy_to_server.Read(buffer)
        if err != nil {
            fmt.Println("ERROR10 ", err)
            return
        }
        fmt.Println("WRIIIIIIIIIIIIIIIIIIIIIIT from server:")
        fmt.Println(string(buffer[:readLeng]))
        if readLeng > 0 {
            _, err := client_to_proxy.Write(buffer[:readLeng])
            if err != nil {
                fmt.Println("ERR4 ", err)
                return
            }
        }
    }
}

func read443(client_to_proxy net.Conn, proxy_to_server net.Conn) {
    buffer := make([]byte, 32*1024)

    readLeng, err := client_to_proxy.Read(buffer)
    if err != nil {
        return
    }
    fmt.Println("REEEEEEEEEEEEEEEEEEEEEEED from client:")
    fmt.Println(string(buffer[:readLeng]))
    if readLeng > 0 {
        _, err := proxy_to_server.Write(buffer[:readLeng])
        if err != nil {
            fmt.Println("ERR5 ", err)
            return
        }
    }

    go write443(client_to_proxy, proxy_to_server)

    for {
        readLeng, err := client_to_proxy.Read(buffer)
        if err != nil {
            return
        }
        fmt.Println("REEEEEEEEEEEEEEEEEEEEEEED from client:")
        fmt.Println(string(buffer[:readLeng]))
        if readLeng > 0 {
            _, err := proxy_to_server.Write(buffer[:readLeng])
            if err != nil {
                fmt.Println("ERR5 ", err)
                return
            }
        }
    }
}

Понравилась статья? Поделить с друзьями:
  • Код ошибки system service exception win32k system
  • Код ошибки win 1601 eset
  • Код ошибки system service exception win32k sys
  • Код ошибки whea uncorrectable error windows 10 как исправить
  • Код ошибки ssl error bad mac alert