[原创]C# 使用BouncyCastle加密套件实现自定义Ja3指纹代码
2023-5-25 12:55:26 Author: bbs.pediy.com(查看原文) 阅读量:38 收藏

JA3 是一种对传输层安全应用程序进行指纹识别的方法。它于 2017 年 6 月首次发布在 GitHub 上,是 Salesforce 研究人员 John Althouse、Jeff Atkinson 和 Josh Atkins 的作品。创建的 JA3 TLS/SSL 指纹可以在应用程序之间重叠,但仍然是一个很好的妥协指标 (IoC)。指纹识别是通过创建客户端问候消息的 5 个十进制字段的哈希来实现的,该消息在 TLS/SSL 会话的初始阶段发送。

JA3/JA3S是SSL/TLS 客户端/服务器指纹的方法,它应该易于在任何平台上生成,并且可以轻松共享以用于威胁情报,也被用于对用户浏览器跟踪,达到识别机器人爬虫的效果。

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

70

71

72

73

74

using Org.BouncyCastle.Security;

using Org.BouncyCastle.Tls;

using System;

using System.Collections.Generic;

using System.Diagnostics;

using System.Linq;

using System.Net;

using System.Net.Http;

using System.Net.Sockets;

using System.Text;

using System.Threading.Tasks;

namespace BypassJa3

{

    class Ja3httpclient

    {

        public static string Get(string uri)

        {

            Uri httpurl = new Uri(uri);

            string result = string.Empty;

            if(httpurl.Scheme =="https")

            {

                using (var client = new TcpClient(httpurl.Host, httpurl.Port))

                {

                    var cl = new Ja3TlsClient(null);

                    cl.ServerNames = new [] { httpurl.Host};

                    var protocol = new TlsClientProtocol(client.GetStream());

                    protocol.Connect(cl);

                    using (var stream = protocol.Stream)

                    {

                        var hdr = new StringBuilder();

                        hdr.AppendLine(string.Format("GET {0} HTTP/1.1", httpurl.PathAndQuery));

                        hdr.AppendLine(string.Format("Host: {0}", httpurl.Host));

                        hdr.AppendLine("Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8");

                        hdr.AppendLine("Accept-Language: zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2");

                        hdr.AppendLine("Accept-Encoding: gzip, deflate, br");

                        hdr.AppendLine("User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/113.0");

                        hdr.AppendLine("Connection: keep-alive");

                        hdr.Append("\r\n");                       

                        string debug = hdr.ToString();

                        Trace.WriteLine(debug);

                        var dataToSend = Encoding.UTF8.GetBytes(hdr.ToString());                       

                        stream.Write(dataToSend, 0, dataToSend.Length);

                        int totalRead = 0;                       

                        string response = "";

                        byte[] buff = new byte[1000];                       

                        do

                        {

                            totalRead = stream.Read(buff, 0, buff.Length);

                            if(totalRead <= 0)

                            {

                                break;

                            }

                            response += Encoding.UTF8.GetString(buff, 0, totalRead);

                        } while (true);

                        result = response;

                    }

                }

            }

            else

            {

                //http

            }

            return result;

        }

    }

}

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

70

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

118

119

120

121

122

123

124

125

126

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

using System;

using System.Collections;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using Org.BouncyCastle.Security;

using Org.BouncyCastle.Tls;

using Org.BouncyCastle.Tls.Crypto;

using Org.BouncyCastle.Tls.Crypto.Impl.BC;

using Org.BouncyCastle.Utilities;

namespace BypassJa3

{

    internal class Ja3TlsClient : DefaultTlsClient

    {

        internal TlsSession m_session;

        private ServerName[] _serverNames;

        public string[] ServerNames

        {

            set

            {

                if (value == null)

                {

                    _serverNames = null;

                }

                else

                {

                    _serverNames = value.Select(x => new ServerName(NameType.host_name, Encoding.ASCII.GetBytes(x))).ToArray();

                }

            }

        }

        internal Ja3TlsClient(TlsSession session)

            : base(new BcTlsCrypto(new SecureRandom()))

        {

            this.m_session = session;

        }

        public IList<SignatureAndHashAlgorithm> SignatureAlgorithms { get; set; } = new[] {

            CreateSignatureAlgorithm(SignatureScheme.ecdsa_secp256r1_sha256),

            CreateSignatureAlgorithm(SignatureScheme.rsa_pss_rsae_sha256),

            CreateSignatureAlgorithm(SignatureScheme.rsa_pkcs1_sha256),

            CreateSignatureAlgorithm(SignatureScheme.ecdsa_secp384r1_sha384),

            CreateSignatureAlgorithm(SignatureScheme.rsa_pss_rsae_sha384),

            CreateSignatureAlgorithm(SignatureScheme.rsa_pkcs1_sha384),

            CreateSignatureAlgorithm(SignatureScheme.rsa_pss_rsae_sha512),

            CreateSignatureAlgorithm(SignatureScheme.rsa_pkcs1_sha512),

            CreateSignatureAlgorithm(SignatureScheme.rsa_pkcs1_sha1),

        };

        public int[] SupportedCiphers { get; set; } = new[] {

            CipherSuite.TLS_CHACHA20_POLY1305_SHA256,

            CipherSuite.TLS_AES_128_GCM_SHA256,

            CipherSuite.TLS_AES_256_GCM_SHA384,

            CipherSuite.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,

            CipherSuite.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,

            CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,

            CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,

            CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,

            CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,

            CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,

            CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,

            CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,

            CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,

            CipherSuite.TLS_RSA_WITH_AES_128_GCM_SHA256,

            CipherSuite.TLS_RSA_WITH_AES_256_GCM_SHA384,

            CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA,

            CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA,

            CipherSuite.TLS_RSA_WITH_3DES_EDE_CBC_SHA,

            CipherSuite.TLS_EMPTY_RENEGOTIATION_INFO_SCSV

        };

        public int[] SupportedGroups { get; set; } = new[] {

            NamedGroup.x25519,

            NamedGroup.secp256r1,

            NamedGroup.secp384r1,

        };

        public override TlsSession GetSessionToResume()

        {

            return m_session;

        }

        public override TlsAuthentication GetAuthentication()

        {

           return new Ja3TlsAuthentication(m_context);

        }

        public ProtocolVersion[] SupportedVersions { get; set; } = ProtocolVersion.TLSv13.DownTo(ProtocolVersion.TLSv10);

        public override void NotifyServerVersion(ProtocolVersion serverVersion)

        {

            base.NotifyServerVersion(serverVersion);

            //Console.WriteLine("TLS client negotiated " + serverVersion);

        }

        public override IList GetExternalPsks()

        {

            byte[] identity = Strings.ToUtf8ByteArray("client");

            TlsSecret key = Crypto.CreateSecret(Strings.ToUtf8ByteArray("TLS_TEST_PSK"));

            int prfAlgorithm = PrfAlgorithm.tls13_hkdf_sha256;

            return TlsUtilities.VectorOfOne(new BasicTlsPskExternal(identity, key, prfAlgorithm));

        }

        //扩展

        public override IDictionary GetClientExtensions()

        {

            IDictionary clientExtensions = TlsExtensionsUtilities.EnsureExtensionsInitialised(base.GetClientExtensions());

            TlsExtensionsUtilities.AddMaxFragmentLengthExtension(clientExtensions, MaxFragmentLength.pow2_9);

            TlsExtensionsUtilities.AddPaddingExtension(clientExtensions, m_context.Crypto.SecureRandom.Next(16));

            TlsExtensionsUtilities.AddTruncatedHmacExtension(clientExtensions);

            TlsExtensionsUtilities.AddRecordSizeLimitExtension(clientExtensions, 16385);

            TlsExtensionsUtilities.AddPaddingExtension(clientExtensions, 0);

            bool offeringTlsV13Plus = false;                  

            ProtocolVersion[] supportedVersions = GetProtocolVersions();

            for (int i = 0; i < supportedVersions.Length; ++i)

            {

                var supportedVersion = supportedVersions[i];

                if (TlsUtilities.IsTlsV13(supportedVersion))

                {

                    offeringTlsV13Plus = true;

                }

            }

            if(offeringTlsV13Plus)

            {

                int[] offeredCipherSuites = this.GetCipherSuites();

                TlsPskExternal[] psks = GetPskExternalsClient(this, offeredCipherSuites);

                var identities = new List<PskIdentity>(psks.Length);

                for (int i = 0; i < psks.Length; ++i)

                {

                    TlsPsk psk = psks[i];

                    // TODO[tls13-psk] Handle obfuscated_ticket_age for resumption PSKs

                    identities.Add(new PskIdentity(psk.Identity, 0L));

                }

                TlsExtensionsUtilities.AddPreSharedKeyClientHello(clientExtensions, new OfferedPsks(identities));

            }

            clientExtensions[ExtensionType.renegotiation_info] = TlsUtilities.EncodeOpaque8(TlsUtilities.EmptyBytes);

            //next_protocol_negotiation

            //clientExtensions[13172] = new byte[0];

            //17513 extensionApplicationSettings

            clientExtensions[17513] = new byte[0];

            return clientExtensions;

        }

        internal static TlsPskExternal[] GetPskExternalsClient(TlsClient client, int[] offeredCipherSuites)

        {

            var externalPsks = client.GetExternalPsks();

            if(externalPsks==null|| externalPsks.Count<1)

            {

                return null;

            }

            int[] prfAlgorithms = GetPrfAlgorithms13(offeredCipherSuites);

            int count = externalPsks.Count;

            TlsPskExternal[] result = new TlsPskExternal[count];

            for (int i = 0; i < count; ++i)

            {

                TlsPskExternal pskExternal = externalPsks[i] as TlsPskExternal;

                if (null == pskExternal)

                    throw new TlsFatalAlert(AlertDescription.internal_error,

                        "External PSKs element is not a TlsPSKExternal");

                if (!Arrays.Contains(prfAlgorithms, pskExternal.PrfAlgorithm))

                    throw new TlsFatalAlert(AlertDescription.internal_error,

                        "External PSK incompatible with offered cipher suites");

                result[i] = pskExternal;

            }

            return result;

        }

        internal static int[] GetPrfAlgorithms13(int[] cipherSuites)

        {

            int[] result = new int[System.Math.Min(3, cipherSuites.Length)];

            int count = 0;

            for (int i = 0; i < cipherSuites.Length; ++i)

            {

                int prfAlgorithm = GetPrfAlgorithm13(cipherSuites[i]);

                if (prfAlgorithm >= 0 && !Arrays.Contains(result, prfAlgorithm))

                {

                    result[count++] = prfAlgorithm;

                }

            }

            return Truncate(result, count);

        }

        internal static int GetPrfAlgorithm13(int cipherSuite)

        {

            // NOTE: GetPrfAlgorithms13 relies on the number of distinct return values

            switch (cipherSuite)

            {

                case CipherSuite.TLS_AES_128_CCM_SHA256:

                case CipherSuite.TLS_AES_128_CCM_8_SHA256:

                case CipherSuite.TLS_AES_128_GCM_SHA256:

                case CipherSuite.TLS_CHACHA20_POLY1305_SHA256:

                    return PrfAlgorithm.tls13_hkdf_sha256;

                case CipherSuite.TLS_AES_256_GCM_SHA384:

                    return PrfAlgorithm.tls13_hkdf_sha384;

                case CipherSuite.TLS_SM4_CCM_SM3:

                case CipherSuite.TLS_SM4_GCM_SM3:

                    return PrfAlgorithm.tls13_hkdf_sm3;

                default:

                    return -1;

            }

        }

        internal static int[] Truncate(int[] a, int n)

        {

            if (n >= a.Length)

                return a;

            int[] t = new int[n];

            Array.Copy(a, 0, t, 0, n);

            return t;

        }

        internal static short[] Truncate(short[] a, int n)

        {

            if (n >= a.Length)

                return a;

            short[] t = new short[n];

            Array.Copy(a, 0, t, 0, n);

            return t;

        }

        public static int[] GetClientExtensionSequence()

        {

            return new int[] {

                ExtensionType.renegotiation_info,       //(65281)

                ExtensionType.server_name,              //(0)

                ExtensionType.extended_master_secret,   //(23)

                ExtensionType.session_ticket,           //(35)

                ExtensionType.signature_algorithms,     //(13)

                ExtensionType.status_request,           //(5)

                13172,//(13172) ExtensionType.next_protocol_negotiation

                ExtensionType.signed_certificate_timestamp,             //(18)

                ExtensionType.application_layer_protocol_negotiation,   //(16)

                ExtensionType.ec_point_formats,         //(11)

                ExtensionType.supported_groups,         //(10)

                ExtensionType.padding,                  //(21) [align 512]

            };

        }

        public int GetExtensionOrder(int type, int[] sequence)

        {

            for (var i = 0; i < sequence.Length; i++)

                if (sequence[i] == type)

                    return i;

            return -1;

        }

        public static IDictionary<TKey, TValue> MakeKeyOrderDictionary<TKey, TValue>(IEnumerable<KeyValuePair<TKey, TValue>> items, Func<KeyValuePair<TKey, TValue>, int> orderFunc)

        {

            List<KeyValuePair<TKey, TValue>> itemList = new List<KeyValuePair<TKey, TValue>>(items);

            itemList.Sort((x, y) => orderFunc(x).CompareTo(orderFunc(y)));

            Dictionary<TKey, TValue> resultDict = new Dictionary<TKey, TValue>();

            foreach (var item in itemList)

            {

                resultDict[item.Key] = item.Value;

            }

            return resultDict;

        }

        protected override IList GetSupportedGroups(IList namedGroupRoles)

        {

            var supportedGroups = new ArrayList();

            TlsUtilities.AddIfSupported(supportedGroups, Crypto, SupportedGroups);

            return supportedGroups;

        }

        protected override ProtocolVersion[] GetSupportedVersions() => SupportedVersions;

        protected override IList GetSupportedSignatureAlgorithms() => (IList)SignatureAlgorithms;

        protected override int[] GetSupportedCipherSuites() => SupportedCiphers;

        protected override IList GetSniServerNames() => _serverNames;

        private static SignatureAndHashAlgorithm CreateSignatureAlgorithm(int signatureScheme)

        {

            short hashAlgorithm = SignatureScheme.GetHashAlgorithm(signatureScheme);

            short signatureAlgorithm = SignatureScheme.GetSignatureAlgorithm(signatureScheme);

            return new SignatureAndHashAlgorithm(hashAlgorithm, signatureAlgorithm);

        }

    }

}


文章来源: https://bbs.pediy.com/thread-277354.htm
如有侵权请联系:admin#unsafe.sh