Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 3개 있습니다.)

C# - WebClient로 https 호출 시 "The request was aborted: Could not create SSL/TLS secure channel" 예외 발생

오랜만에 간단하게 .NET 4 환경에서 WebClient를 사용했더니,

// 아래의 테스트 환경 결과는 레지스트리 설정, 윈도우 업데이트 패치 등의 영향에 따라 가변적일 수 있으니 유의해야 합니다.

// [클라이언트의 경우, 최소 Windows 10+ 이상의 환경]
// [서버의 경우, 최소 Windows Server 2016+ 환경]
// 1. .NET Framework 4.6+ 타겟으로 빌드하면 예외 발생하지 않음.
// 2.                4.5 이하로 빌드 후 단순히 app.config에 sku=".NETFramework,Version=v4.6"을 지정해도 예외 발생.
// 3. .NET Core로 빌드하면 예외 발생하지 않음.

using System;
using System.Net;

internal class Program
{
    static void Main(string[] args)
    {
        WebClient wc = new WebClient();

        try
        {
            wc.DownloadString("https://shinyoungjin.life/rss.xml");
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }
    }
}

실행 시 이런 예외가 발생합니다.

// 4.x 응용 프로그램의 경우
C:\test\ConsoleApp1\bin\Debug>ConsoleApp1.exe
System.Net.WebException: The request was aborted: Could not create SSL/TLS secure channel.
   at System.Net.WebClient.DownloadDataInternal(Uri address, WebRequest& request)
   at System.Net.WebClient.DownloadString(Uri address)
   at ConsoleApp1.Program.Main(String[] args) in C:\test\ConsoleApp1\Program.cs:line 17

// 4.x 미만 응용 프로그램의 경우
Unhandled Exception: System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a send. ---> System.IO.IOException: Received an unexpected EOF or 0 bytes from the transport stream.
   at System.Net.FixedSizeReader.ReadPacket(Byte[] buffer, Int32 offset, Int32 count)
   at System.Net.Security.SslState.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.ForceAuthentication(Boolean receiveFirst, Byte[] buffer, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.ProcessAuthentication(LazyAsyncResult lazyResult)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Net.TlsStream.ProcessAuthentication(LazyAsyncResult result)
   at System.Net.TlsStream.Write(Byte[] buffer, Int32 offset, Int32 size)
   at System.Net.PooledStream.Write(Byte[] buffer, Int32 offset, Int32 size)
   at System.Net.ConnectStream.WriteHeaders(Boolean async)
   --- End of inner exception stack trace ---
   at System.Net.WebClient.DownloadDataInternal(Uri address, WebRequest& request)
   at System.Net.WebClient.DownloadString(Uri address)
   at Program.Main(String[] args)

디버거를 이용해 좀 더 세밀하게 예외 상황을 보면 WebException 이전에 이미 "System.Security.Authentication.AuthenticationException" 예외가 발생했고 이때의 메시지는 좀 더 자세한 정보를 담고 있습니다.

System.Security.Authentication.AuthenticationException
  HResult=0x80131501
  Message=A call to SSPI failed, see inner exception.
  Source=System
  StackTrace:
   at System.Net.Security.SslState.StartSendAuthResetSignal(ProtocolToken message, AsyncProtocolRequest asyncRequest, Exception exception) in f:\dd\NDP\fx\src\net\System\Net\SecureProtocols\_SslState.cs:line 984

Inner Exception 1:
Win32Exception: The function requested is not supported

다행히 검색해 보면 답이 나옵니다. ^^

A call to SSPI failed, see inner exception - The Local Security Authority cannot be contacted
; https://stackoverflow.com/questions/37925505/a-call-to-sspi-failed-see-inner-exception-the-local-security-authority-cannot

그러니까, WebClient가 나온 지 꽤나 오래돼서 ^^; 당시에 기본 옵션이었던 Ssl3/Tls로는 더 이상 https 서버와 통신이 안 되었던 것입니다.

따라서, 혹시나 있을 기존 https 서버와의 호환을 고려해야 한다면 이렇게 코딩을 추가할 수 있습니다.

// SecurityProtocolType.Tls12 == 3072 (0xC00)

// .NET Framework 4.5.2 이하인 경우
// ServicePointManager.SecurityProtocol의 기본값 == SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls

// .NET Framework 4.6 이상인 경우
// ServicePointManager.SecurityProtocol의 기본값 == Tls | Tls11 | Tls12 | Tls13;

ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12;

Console.WriteLine(wc.DownloadString("https://shinyoungjin.life/rss.xml"));

SecurityProtocolType에 Tls12 상수가 추가된 것은 .NET 4.5부터라서 만약 .NET 4.0 이하의 프로그램에서 사용해야 한다면 직접 상수를 기재해도 됩니다.

ServicePointManager.SecurityProtocol |= (SecurityProtocolType)3072;




만약 코드 변경을 원하지 않는다면 app.config을 바꿔도 됩니다. 일례로, AppContextSwitchOverrides를 이용해 다음과 같이 설정해 주면,

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <runtime>
        <AppContextSwitchOverrides value="Switch.System.Net.DontEnableSchUseStrongCrypto=false" />
    </runtime>
</configuration>

"ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12;" 코드 설정 없이도 WebClient 호출에 예외가 발생하지 않습니다. 그런데 좀 이상하군요, CA5361의 정적 검사에서도 DontEnableSchUseStrongCrypto 옵션을 보안상 true로 설정하지 말라고 권고하고 있는데... ^^; 다시 말해 그동안 기본값이 true였던 것입니다.





코드 변경을 하지 않는 또 다른 방법은 레지스트리 설정입니다. 이런 경우, .NET Framework 4.5 이하의 프로그램에 대해서도 Tls12 (또는, 최신 버전의 보안 프로토콜) 설정이 적용되도록 강제할 수 있다는 장점이 있는데요, 방법은 다음의 문서에 잘 나와 있습니다.

How to enable TLS 1.2 on the site servers and remote site systems
 - Configure for strong cryptography
; https://learn.microsoft.com/en-us/mem/configmgr/core/plan-design/security/enable-tls-1-2-server#configure-for-strong-cryptography
// 64비트 운영체제/64비트 응용 프로그램, 32비트 운영체제/32비트 응용 프로그램에 대해
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v2.0.50727]
      "SystemDefaultTlsVersions" = dword:00000001
      "SchUseStrongCrypto" = dword:00000001
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319]
      "SystemDefaultTlsVersions" = dword:00000001
      "SchUseStrongCrypto" = dword:00000001

// 64비트 운영체제에서 32비트 응용 프로그램에 대해
[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v2.0.50727]
      "SystemDefaultTlsVersions" = dword:00000001
      "SchUseStrongCrypto" = dword:00000001
[HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\.NETFramework\v4.0.30319]
      "SystemDefaultTlsVersions" = dword:00000001
      "SchUseStrongCrypto" = dword:00000001




참고로, 제어판에서 지역 설정 창의 "Beta: Use Unicode UTF-8 for worldwide language support" 옵션을 체크하지 않은 경우 위에서 만든 코드를 통해 반환한 텍스트의 한글이 깨져 있는 문제가 있습니다.

이에 대해서도 예전에 쓴 글이 있는데요, ^^

WebClient.DownloadString 문자열 인코딩 문제
; https://www.sysnet.pe.kr/2/0/1493

그나저나, 이런 문제는 근래의 HttpClient를 사용하면 발생하지 않으므로... 이젠 머나먼 과거의 이야기가 될 것입니다.




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 1/30/2023]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




1  2  3  4  5  [6]  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13479정성태12/11/20232318개발 환경 구성: 691. WSL 2 (Ubuntu) + nginx 환경 설정
13477정성태12/8/20232508닷넷: 2182. C# - .NET 7부터 추가된 Int128, UInt128 [1]파일 다운로드1
13476정성태12/8/20232249닷넷: 2181. C# - .NET 8 JsonStringEnumConverter의 AOT를 위한 개선파일 다운로드1
13475정성태12/7/20232302닷넷: 2180. .NET 8 - 함수 포인터에 대한 Reflection 정보 조회파일 다운로드1
13474정성태12/6/20232164개발 환경 구성: 690. 닷넷 코어/5+ 버전의 ilasm/ildasm 실행 파일 구하는 방법 - 두 번째 이야기
13473정성태12/5/20232363닷넷: 2179. C# - 값 형식(Blittable)을 메모리 복사를 이용해 바이트 배열로 직렬화/역직렬화파일 다운로드1
13472정성태12/4/20232186C/C++: 164. Visual C++ - InterlockedCompareExchange128 사용 방법
13471정성태12/4/20232246Copilot - To enable GitHub Copilot, authorize this extension using GitHub's device flow
13470정성태12/2/20232542닷넷: 2178. C# - .NET 8부터 COM Interop에 대한 자동 소스 코드 생성 도입파일 다운로드1
13469정성태12/1/20232255닷넷: 2177. C# - (Interop DLL 없이) CoClass를 이용한 COM 개체 생성 방법파일 다운로드1
13468정성태12/1/20232214닷넷: 2176. C# - .NET Core/5+부터 달라진 RCW(Runtime Callable Wrapper) 대응 방식파일 다운로드1
13467정성태11/30/20232244오류 유형: 882. C# - Unhandled exception. System.Runtime.InteropServices.COMException (0x800080A5)파일 다운로드1
13466정성태11/29/20232439닷넷: 2175. C# - DllImport 메서드의 AOT 지원을 위한 LibraryImport 옵션
13465정성태11/28/20232186개발 환경 구성: 689. MSBuild - CopyToOutputDirectory가 "dotnet publish" 시에는 적용되지 않는 문제파일 다운로드1
13464정성태11/28/20232309닷넷: 2174. C# - .NET 7부터 UnmanagedCallersOnly 함수 export 기능을 AOT 빌드에 통합파일 다운로드1
13463정성태11/27/20232221오류 유형: 881. Visual Studio - NU1605: Warning As Error: Detected package downgrade
13462정성태11/27/20232273오류 유형: 880. Visual Studio - error CS0246: The type or namespace name '...' could not be found
13461정성태11/26/20232306닷넷: 2173. .NET Core 3/5+ 기반의 COM Server를 registry 등록 없이 사용하는 방법파일 다운로드1
13460정성태11/26/20232260닷넷: 2172. .NET 6+ 기반의 COM Server 내에 Type Library를 내장하는 방법파일 다운로드1
13459정성태11/26/20232237닷넷: 2171. .NET Core 3/5+ 기반의 COM Server를 기존의 regasm처럼 등록하는 방법파일 다운로드1
13458정성태11/26/20232247닷넷: 2170. .NET Core/5+ 기반의 COM Server를 tlb 파일을 생성하는 방법(tlbexp)
13457정성태11/25/20232183VS.NET IDE: 187. Visual Studio - 16.9 버전부터 추가된 "Display inline type hints" 옵션
13456정성태11/25/20232479닷넷: 2169. C# - OpenAI를 사용해 PDF 데이터를 대상으로 OpenAI 챗봇 작성 [1]파일 다운로드1
13455정성태11/25/20232384닷넷: 2168. C# - Azure.AI.OpenAI 패키지로 OpenAI 사용파일 다운로드1
13454정성태11/23/20232727닷넷: 2167. C# - Qdrant Vector DB를 이용한 Embedding 벡터 값 보관/조회 (Azure OpenAI) [1]파일 다운로드1
13453정성태11/23/20232239오류 유형: 879. docker desktop 설치 시 "Invalid JSON string. (Exception from HRESULT: 0x83750007)"
1  2  3  4  5  [6]  7  8  9  10  11  12  13  14  15  ...