/// <summary> /// Constructor /// </summary> /// <param name="ticketEncryptKey">Encrypt key of the service principle. This parameter cannot be null.</param> /// <exception cref="System.ArgumentNullException">Thrown when the input parameter is null.</exception> public KerberosServerSecurityContext(EncryptionKey ticketEncryptKey) { if (ticketEncryptKey == null) { throw new ArgumentNullException("ticketEncryptKey"); } server = new KileServer(""); server.context = new KileServerContext(); this.ticketEncryptKey = ticketEncryptKey; isInitialToken = true; contextSizes = new SecurityPackageContextSizes(); contextSizes.MaxTokenSize = ConstValue.MAX_TOKEN_SIZE; contextSizes.MaxSignatureSize = ConstValue.MAX_SIGNATURE_SIZE; contextSizes.BlockSize = ConstValue.BLOCK_SIZE; contextSizes.SecurityTrailerSize = ConstValue.SECURITY_TRAILER_SIZE; }
public GoogleCloudStorageBlobStorage(string bucketName, GoogleCredential credential = null, EncryptionKey encryptionKey = null) : base() { _client = StorageClient.Create(credential, encryptionKey); _bucketName = bucketName; }
// [END storage_generate_signed_url] // [START storage_generate_encryption_key] void GenerateEncryptionKey() { Console.Write(EncryptionKey.Generate().Base64Key); }
public static Error access_override_encryption_key(Access p0, string p1, string p2, EncryptionKey p3) { global::System.IntPtr cPtr = storj_uplinkPINVOKE.access_override_encryption_key(Access.getCPtr(p0), p1, p2, EncryptionKey.getCPtr(p3)); Error ret = (cPtr == global::System.IntPtr.Zero) ? null : new Error(cPtr, false); return(ret); }
private void CrossRealm_Smb2_AccessFile(string localRealmName, string trustuedRealmName, User localUser, Computer localKDC, Computer trustedKDC, TransportType transportType, FileServer fileserverInTrustedRealm, string filePath, string fileName, bool expectAccessDeny) { base.Logging(); client = new KerberosTestClient(localRealmName, localUser.Username, localUser.Password, KerberosAccountType.User, localKDC.IPAddress, localKDC.Port, transportType, testConfig.SupportedOid); //Create and send AS request KdcOptions options = KdcOptions.FORWARDABLE | KdcOptions.CANONICALIZE | KdcOptions.RENEWABLE; client.SendAsRequest(options, null); //Recieve preauthentication required error METHOD_DATA methodData; KerberosKrbError krbError = client.ExpectPreauthRequiredError(out methodData); //Create sequence of PA data string timeStamp = KerberosUtility.CurrentKerberosTime.Value; PaEncTimeStamp paEncTimeStamp = new PaEncTimeStamp(timeStamp, 0, this.client.Context.SelectedEType, this.client.Context.CName.Password, this.client.Context.CName.Salt); PaPacRequest paPacRequest = new PaPacRequest(true); Asn1SequenceOf <PA_DATA> seqOfPaData = new Asn1SequenceOf <PA_DATA>(new PA_DATA[] { paEncTimeStamp.Data, paPacRequest.Data }); //Create and send AS request client.SendAsRequest(options, seqOfPaData); KerberosAsResponse asResponse = client.ExpectAsResponse(); //Create and send TGS request if (this.testConfig.TrustType == Adapter.TrustType.Forest) { client.SendTgsRequest(fileserverInTrustedRealm.Smb2ServiceName, options); } else if (this.testConfig.TrustType == Adapter.TrustType.Realm) { client.SendTgsRequest(trustedKDC.DefaultServiceName, options); } BaseTestSite.Log.Add(LogEntryKind.Comment, "Create and send TGS request"); KerberosTgsResponse tgsResponse = client.ExpectTgsResponse(); BaseTestSite.Log.Add(LogEntryKind.Comment, "Receive a referral TGS response."); BaseTestSite.Assert.AreEqual(trustedKDC.DefaultServiceName, KerberosUtility.PrincipalName2String(tgsResponse.Response.ticket.sname), "The service principal name in referral ticket should match expected."); BaseTestSite.Assert.AreEqual(localRealmName.ToLower(), tgsResponse.Response.ticket.realm.Value.ToLower(), "The realm name in referral ticket should match expected."); //Change realm client.ChangeRealm(trustuedRealmName, trustedKDC.IPAddress, trustedKDC.Port, this.testConfig.TransportType); //Create and send referral TGS request client.SendTgsRequest(fileserverInTrustedRealm.Smb2ServiceName, options); KerberosTgsResponse refTgsResponse = client.ExpectTgsResponse(); BaseTestSite.Assert.AreEqual(fileserverInTrustedRealm.Smb2ServiceName, KerberosUtility.PrincipalName2String(refTgsResponse.Response.ticket.sname), "The service principal name in service ticket should match expected."); BaseTestSite.Assert.AreEqual(trustuedRealmName.ToLower(), refTgsResponse.Response.ticket.realm.Value.ToLower(), "The realm name in service ticket should match expected."); EncryptionKey key = testConfig.QueryKey(fileserverInTrustedRealm.Smb2ServiceName, client.Context.Realm.ToString(), client.Context.SelectedEType); refTgsResponse.DecryptTicket(key); BaseTestSite.Assert.AreEqual(localRealmName.ToLower(), refTgsResponse.TicketEncPart.crealm.Value.ToLower(), "Realm name in service ticket encrypted part should match expected."); BaseTestSite.Assert.AreEqual(localUser.Username.ToLower(), KerberosUtility.PrincipalName2String(refTgsResponse.TicketEncPart.cname).ToLower(), "User name in service ticket encrypted part should match expected."); AuthorizationData data = null; EncryptionKey subkey = KerberosUtility.GenerateKey(client.Context.SessionKey); byte[] token = client.CreateGssApiToken(ApOptions.MutualRequired, data, subkey, ChecksumFlags.GSS_C_MUTUAL_FLAG | ChecksumFlags.GSS_C_INTEG_FLAG); BaseTestSite.Log.Add(LogEntryKind.Comment, "Logon to fileserver and Access File."); AccessFile(filePath, fileName, fileserverInTrustedRealm, token, refTgsResponse.EncPart.key, expectAccessDeny); }
private void DAC_Smb2_AccessFile(string RealmName, User user, Computer kdc, TransportType transportType, FileServer fileserver, string filePath, string fileName, bool expectAccessDeny) { base.Logging(); client = new KerberosTestClient(RealmName, user.Username, user.Password, KerberosAccountType.User, kdc.IPAddress, kdc.Port, transportType, testConfig.SupportedOid); //Create and send AS request KdcOptions options = KdcOptions.FORWARDABLE | KdcOptions.CANONICALIZE | KdcOptions.RENEWABLE; client.SendAsRequest(options, null); //Recieve preauthentication required error METHOD_DATA methodData; KerberosKrbError krbError = client.ExpectPreauthRequiredError(out methodData); //Create sequence of PA data string timeStamp = KerberosUtility.CurrentKerberosTime.Value; PaEncTimeStamp paEncTimeStamp = new PaEncTimeStamp(timeStamp, 0, client.Context.SelectedEType, this.client.Context.CName.Password, this.client.Context.CName.Salt); PaPacRequest paPacRequest = new PaPacRequest(true); Asn1SequenceOf <PA_DATA> seqOfPaData = new Asn1SequenceOf <PA_DATA>(new PA_DATA[] { paEncTimeStamp.Data, paPacRequest.Data }); //Create and send AS request client.SendAsRequest(options, seqOfPaData); KerberosAsResponse asResponse = client.ExpectAsResponse(); BaseTestSite.Assert.IsNotNull(asResponse.Response.ticket, "AS response should contain a TGT."); //Create and send TGS request client.SendTgsRequest(fileserver.Smb2ServiceName, options); KerberosTgsResponse tgsResponse = client.ExpectTgsResponse(); BaseTestSite.Assert.AreEqual(fileserver.Smb2ServiceName, KerberosUtility.PrincipalName2String(tgsResponse.Response.ticket.sname), "Service principal name in service ticket should match expected."); EncryptionKey key = testConfig.QueryKey(fileserver.Smb2ServiceName, client.Context.Realm.ToString(), client.Context.SelectedEType); tgsResponse.DecryptTicket(key); BaseTestSite.Assert.AreEqual(RealmName.ToLower(), tgsResponse.TicketEncPart.crealm.Value.ToLower(), "Realm name in service ticket encrypted part should match expected."); BaseTestSite.Assert.AreEqual(user.Username.ToLower(), KerberosUtility.PrincipalName2String(tgsResponse.TicketEncPart.cname).ToLower(), "User name in service ticket encrypted part should match expected."); //Assert authorization data if (this.testConfig.IsKileImplemented) { BaseTestSite.Assert.IsNotNull(tgsResponse.TicketEncPart.authorization_data, "The ticket contains Authorization data."); AdWin2KPac adWin2kPac = FindOneInAuthData <AdWin2KPac>(tgsResponse.TicketEncPart.authorization_data.Elements); BaseTestSite.Assert.IsNotNull(adWin2kPac, "The Authorization data contains AdWin2KPac."); } AuthorizationData data = null; EncryptionKey subkey = KerberosUtility.GenerateKey(client.Context.SessionKey); byte[] token = client.CreateGssApiToken(ApOptions.MutualRequired, data, subkey, ChecksumFlags.GSS_C_MUTUAL_FLAG | ChecksumFlags.GSS_C_INTEG_FLAG); BaseTestSite.Log.Add(LogEntryKind.Comment, "Logon to fileserver and Access File."); AccessFile(filePath, fileName, fileserver, token, tgsResponse.EncPart.key, expectAccessDeny); }
private EncTicketPart RetrieveAndDecryptServiceTicket(KerberosFunctionalClient kerberosClient, out EncryptionKey serviceKey) { //Create and send AS request const KdcOptions options = KdcOptions.FORWARDABLE | KdcOptions.CANONICALIZE | KdcOptions.RENEWABLE; kerberosClient.SendAsRequest(options, null); BaseTestSite.Log.Add(LogEntryKind.TestStep, "Kerberos Functional Client expects Kerberos Error from KDC"); //Receive preauthentication required error METHOD_DATA methodData; KerberosKrbError krbError = kerberosClient.ExpectPreauthRequiredError(out methodData); BaseTestSite.Log.Add(LogEntryKind.TestStep, "Kerberos Functional Client sends AS request with PA-DATA set"); //Create sequence of PA data string timeStamp = KerberosUtility.CurrentKerberosTime.Value; PaEncTimeStamp paEncTimeStamp = new PaEncTimeStamp(timeStamp, 0, kerberosClient.Context.SelectedEType, kerberosClient.Context.CName.Password, kerberosClient.Context.CName.Salt); PaPacRequest paPacRequest = new PaPacRequest(true); Asn1SequenceOf <PA_DATA> seqOfPaData = new Asn1SequenceOf <PA_DATA>(new[] { paEncTimeStamp.Data, paPacRequest.Data }); //Create and send AS request kerberosClient.SendAsRequest(options, seqOfPaData); BaseTestSite.Log.Add(LogEntryKind.TestStep, "Kerberos Functional Client expects AS response from KDC"); KerberosAsResponse asResponse = kerberosClient.ExpectAsResponse(); BaseTestSite.Assert.IsNotNull(asResponse.Response.ticket, "AS response should contain a TGT."); //Create and send TGS request BaseTestSite.Log.Add(LogEntryKind.TestStep, "Kerberos Functional Client sends TGS request to KDC"); kerberosClient.SendTgsRequest(servicePrincipalName, options); BaseTestSite.Log.Add(LogEntryKind.TestStep, "Kerberos Functional Client expects TGS response from KDC"); KerberosTgsResponse tgsResponse = kerberosClient.ExpectTgsResponse(); BaseTestSite.Assert.AreEqual(servicePrincipalName, KerberosUtility.PrincipalName2String(tgsResponse.Response.ticket.sname), "Service principal name in service ticket should match expected."); BaseTestSite.Log.Add(LogEntryKind.TestStep, "Decrypt SMB2 Service Ticket"); serviceKey = keyManager.QueryKey(servicePrincipalName, TestConfig.DomainName, kerberosClient.Context.SelectedEType); tgsResponse.DecryptTicket(serviceKey); return(tgsResponse.TicketEncPart); }
public AETL_BucketManager(EncryptionKey Key) { AttachEncryption(Key); }
public void Create_Invalid() { Assert.Throws <ArgumentNullException>(() => EncryptionKey.Create(null)); Assert.Throws <ArgumentException>(() => EncryptionKey.Create(new byte[33])); Assert.Throws <ArgumentException>(() => EncryptionKey.Create(new byte[31])); }
/// <summary> /// Parse crypto settings from INI file /// </summary> public static CryptoSettings ParseCryptoSettings(DirectoryReference InProjectDirectory, UnrealTargetPlatform InTargetPlatform) { CryptoSettings Settings = new CryptoSettings(); ConfigHierarchy Ini = ConfigCache.ReadHierarchy(ConfigHierarchyType.Engine, InProjectDirectory, InTargetPlatform); Ini.GetBool("PlatformCrypto", "PlatformRequiresDataCrypto", out Settings.bDataCryptoRequired); { // Start by parsing the legacy encryption.ini settings Ini = ConfigCache.ReadHierarchy(ConfigHierarchyType.Encryption, InProjectDirectory, InTargetPlatform); Ini.GetBool("Core.Encryption", "SignPak", out Settings.bEnablePakSigning); string[] SigningKeyStrings = new string[3]; Ini.GetString("Core.Encryption", "rsa.privateexp", out SigningKeyStrings[0]); Ini.GetString("Core.Encryption", "rsa.modulus", out SigningKeyStrings[1]); Ini.GetString("Core.Encryption", "rsa.publicexp", out SigningKeyStrings[2]); if (String.IsNullOrEmpty(SigningKeyStrings[0]) || String.IsNullOrEmpty(SigningKeyStrings[1]) || String.IsNullOrEmpty(SigningKeyStrings[2])) { SigningKeyStrings = null; } else { Settings.SigningKey = new SigningKeyPair(); Settings.SigningKey.PrivateKey.Exponent = ParseHexStringToByteArray(ProcessSigningKeyInputStrings(SigningKeyStrings[0]), 64); Settings.SigningKey.PrivateKey.Modulus = ParseHexStringToByteArray(ProcessSigningKeyInputStrings(SigningKeyStrings[1]), 64); Settings.SigningKey.PublicKey.Exponent = ParseHexStringToByteArray(ProcessSigningKeyInputStrings(SigningKeyStrings[2]), 64); Settings.SigningKey.PublicKey.Modulus = Settings.SigningKey.PrivateKey.Modulus; if ((Settings.SigningKey.PrivateKey.Exponent.Length > 64) || (Settings.SigningKey.PrivateKey.Modulus.Length > 64) || (Settings.SigningKey.PublicKey.Exponent.Length > 64) || (Settings.SigningKey.PublicKey.Modulus.Length > 64)) { throw new Exception(string.Format("[{0}] Signing keys parsed from encryption.ini are too long. They must be a maximum of 64 bytes long!", InProjectDirectory)); } } Ini.GetBool("Core.Encryption", "EncryptPak", out Settings.bEnablePakIndexEncryption); Settings.bEnablePakFullAssetEncryption = false; Settings.bEnablePakUAssetEncryption = false; Settings.bEnablePakIniEncryption = Settings.bEnablePakIndexEncryption; string EncryptionKeyString; Ini.GetString("Core.Encryption", "aes.key", out EncryptionKeyString); Settings.EncryptionKey = new EncryptionKey(); if (EncryptionKeyString.Length > 0) { if (EncryptionKeyString.Length < 32) { Log.WriteLine(LogEventType.Warning, "AES key parsed from encryption.ini is too short. It must be 32 bytes, so will be padded with 0s, giving sub-optimal security!"); } else if (EncryptionKeyString.Length > 32) { Log.WriteLine(LogEventType.Warning, "AES key parsed from encryption.ini is too long. It must be 32 bytes, so will be truncated!"); } Settings.EncryptionKey.Key = ParseAnsiStringToByteArray(EncryptionKeyString, 32); } } Ini = ConfigCache.ReadHierarchy(ConfigHierarchyType.Crypto, InProjectDirectory, InTargetPlatform); string SectionName = "/Script/CryptoKeys.CryptoKeysSettings"; ConfigHierarchySection CryptoSection = Ini.FindSection(SectionName); // If we have new format crypto keys, read them in over the top of the legacy settings if (CryptoSection != null && CryptoSection.KeyNames.Count() > 0) { Ini.GetBool(SectionName, "bEnablePakSigning", out Settings.bEnablePakSigning); Ini.GetBool(SectionName, "bEncryptPakIniFiles", out Settings.bEnablePakIniEncryption); Ini.GetBool(SectionName, "bEncryptPakIndex", out Settings.bEnablePakIndexEncryption); Ini.GetBool(SectionName, "bEncryptUAssetFiles", out Settings.bEnablePakUAssetEncryption); Ini.GetBool(SectionName, "bEncryptAllAssetFiles", out Settings.bEnablePakFullAssetEncryption); // Parse encryption key string EncryptionKeyString; Ini.GetString(SectionName, "EncryptionKey", out EncryptionKeyString); if (!string.IsNullOrEmpty(EncryptionKeyString)) { Settings.EncryptionKey = new EncryptionKey(); Settings.EncryptionKey.Key = System.Convert.FromBase64String(EncryptionKeyString); } // Parse secondary encryption keys List <EncryptionKey> SecondaryEncryptionKeys = new List <EncryptionKey>(); List <string> SecondaryEncryptionKeyStrings; if (Ini.GetArray(SectionName, "SecondaryEncryptionKeys", out SecondaryEncryptionKeyStrings)) { foreach (string KeySource in SecondaryEncryptionKeyStrings) { EncryptionKey NewKey = new EncryptionKey(); SecondaryEncryptionKeys.Add(NewKey); Regex Search = new Regex("\\(Guid=(?\'Guid\'.*),Name=\\\"(?\'Name\'.*)\\\",Key=\\\"(?\'Key\'.*)\\\"\\)"); Match Match = Search.Match(KeySource); if (Match.Success) { foreach (string GroupName in Search.GetGroupNames()) { string Value = Match.Groups[GroupName].Value; if (GroupName == "Guid") { NewKey.Guid = Value; } else if (GroupName == "Name") { NewKey.Name = Value; } else if (GroupName == "Key") { NewKey.Key = System.Convert.FromBase64String(Value); } } } } } Settings.SecondaryEncryptionKeys = SecondaryEncryptionKeys.ToArray(); // Parse signing key string PrivateExponent, PublicExponent, Modulus; Ini.GetString(SectionName, "SigningPrivateExponent", out PrivateExponent); Ini.GetString(SectionName, "SigningModulus", out Modulus); Ini.GetString(SectionName, "SigningPublicExponent", out PublicExponent); if (!String.IsNullOrEmpty(PrivateExponent) && !String.IsNullOrEmpty(PublicExponent) && !String.IsNullOrEmpty(Modulus)) { Settings.SigningKey = new SigningKeyPair(); Settings.SigningKey.PublicKey.Exponent = System.Convert.FromBase64String(PublicExponent); Settings.SigningKey.PublicKey.Modulus = System.Convert.FromBase64String(Modulus); Settings.SigningKey.PrivateKey.Exponent = System.Convert.FromBase64String(PrivateExponent); Settings.SigningKey.PrivateKey.Modulus = Settings.SigningKey.PublicKey.Modulus; } } // Parse project dynamic keychain keys if (InProjectDirectory != null) { ConfigHierarchy GameIni = ConfigCache.ReadHierarchy(ConfigHierarchyType.Game, InProjectDirectory, InTargetPlatform); if (GameIni != null) { string Filename; if (GameIni.GetString("ContentEncryption", "ProjectKeyChain", out Filename)) { FileReference ProjectKeyChainFile = FileReference.Combine(InProjectDirectory, "Content", Filename); if (FileReference.Exists(ProjectKeyChainFile)) { List <EncryptionKey> EncryptionKeys = new List <EncryptionKey>(Settings.SecondaryEncryptionKeys); string[] Lines = FileReference.ReadAllLines(ProjectKeyChainFile); foreach (string Line in Lines) { string[] KeyParts = Line.Split(':'); if (KeyParts.Length == 4) { EncryptionKey NewKey = new EncryptionKey(); NewKey.Name = KeyParts[0]; NewKey.Guid = KeyParts[2]; NewKey.Key = System.Convert.FromBase64String(KeyParts[3]); if (EncryptionKeys.Find((EncryptionKey OtherKey) => { return(OtherKey.Guid == NewKey.Guid); }) != null) { throw new Exception("Found a duplicated encryption key guid when merging a project keychain into the secondary key list"); } EncryptionKeys.Add(NewKey); } } Settings.SecondaryEncryptionKeys = EncryptionKeys.ToArray(); } } } } if (!Settings.bDataCryptoRequired) { CryptoSettings NewSettings = new CryptoSettings(); NewSettings.SecondaryEncryptionKeys = Settings.SecondaryEncryptionKeys; Settings = NewSettings; } return(Settings); }
public static async Task <DecryptedMessageResponseDto> DecryptMessage(GetDecryptedMessageDto data) { try { if (EconomyMainContext.Wallets.TryGetValue(data.walletId, out var wallet)) { if (string.IsNullOrEmpty(data.accountAddress)) { throw new HttpResponseException((HttpStatusCode)501, $"Cannot decrypt message, account address cannot be empty!"); } if (wallet.Accounts.TryGetValue(data.accountAddress, out var account)) { var msgtok = await NeblioTransactionHelpers.TokenMetadataAsync(TokenTypes.NTP1, EconomyMainContext.MessagingToken.Id, data.TxId); if (string.IsNullOrEmpty(msgtok.TxId)) { throw new Exception("Cannot decrypt message - Cannot find message token data by provided TxId!"); } EncryptionKey key = null; IToken prepretoken = null; if (msgtok.Metadata.TryGetValue("InitMessage", out var prevmsginit)) { if (prevmsginit != "true") { if (msgtok.Metadata.TryGetValue("PrevTxId", out var prevtxid)) { prepretoken = await NeblioTransactionHelpers.TokenMetadataAsync(TokenTypes.NTP1, TokenId, prevtxid); if (string.IsNullOrEmpty(prepretoken.TxId)) { throw new Exception("Cannot send message - Cannot find pre-previous message token metadata and previous message is not init message!"); } } else { throw new Exception("Cannot send message - Cannot find pre-previous message token metadata and previous message is not init message!"); } } } if (msgtok.Metadata.TryGetValue("MessageData", out var prevmsgdatafromMeta)) { if (prepretoken != null) { if (prepretoken.MetadataAvailable) { if (prepretoken.Metadata.TryGetValue("SenderPubKey", out var preprevtokenReceiverKey)) { var accEncKey = account.AccountKeys.FirstOrDefault(k => k.PublicKey == preprevtokenReceiverKey); if (accEncKey != null) { key = accEncKey; } } } } } var resp = new DecryptedMessageResponseDto(); if (key != null) { if (msgtok.MetadataAvailable) { if (msgtok.Metadata.TryGetValue("PreviousMessage", out var prevmsg)) { try { resp.PrevMsg = AsymmetricProvider.DecryptString(prevmsg, key.GetEncryptedKey(data.Password)); } catch (Exception ex) { ;//todo } } if (msgtok.Metadata.TryGetValue("MessageData", out var newvmsg)) { try { resp.NewMsg = AsymmetricProvider.DecryptString(newvmsg, key.GetEncryptedKey(data.Password)); } catch (Exception ex) { ;//todo } } } return(resp); } else { throw new Exception("Cannot decrypt message - Key does not exists!"); } } else { throw new HttpResponseException((HttpStatusCode)501, $"Cannot decrypt message, Account Not Found!"); } } else { throw new HttpResponseException((HttpStatusCode)501, $"Cannot decrypt message, Wallet Not Found!"); } } catch (Exception ex) { log.Error("Cannot decrypt message!", ex); throw new HttpResponseException((HttpStatusCode)501, $"Cannot decrypt messagen!"); } }
/// <summary> /// Get a hash code for the CustomerProvidedKeyInfo. /// </summary> /// <returns>Hash code for the CustomerProvidedKeyInfo.</returns> public override int GetHashCode() => EncryptionKey.GetHashCode() ^ EncryptionKeyHash.GetHashCode() ^ EncryptionAlgorithm.GetHashCode() ;
public void AttachEncryption(EncryptionKey Key) { m_EncryptionKey = Key; }
public AETL_BucketManager(string CredentialFileLocation, EncryptionKey Key) { AttachCredential(CredentialFileLocation); AttachEncryption(Key); }
public UserRepository(SQLiteConnection database, EncryptionKey encryptionKey) : base(database, encryptionKey) { }
public KileTgsResponse CreateTgsResponse( KileConnection kileConnection, _SeqOfPA_DATA seqOfPaData, EncTicketFlags encTicketFlags, EncryptionKey ticketEncryptKey, AuthorizationData ticketAuthorizationData) { KileServerContext serverContext = GetServerContextByKileConnection(kileConnection); if (ticketEncryptKey == null) { throw new ArgumentNullException("ticketEncryptKey"); } else { serverContext.TicketEncryptKey = ticketEncryptKey; } KileTgsResponse response = new KileTgsResponse(serverContext); // Construct a Ticket Ticket ticket = new Ticket(); ticket.tkt_vno = new Asn1Integer(ConstValue.KERBEROSV5); ticket.realm = new Realm(domain); ticket.sname = serverContext.SName; // Set EncTicketPart EncTicketPart encTicketPart = new EncTicketPart(); EncryptionType encryptionType = (EncryptionType)serverContext.EncryptType.elements[0].mValue; encTicketPart.key = new EncryptionKey((int)encryptionType, GetEncryptionKeyByType(encryptionType)); encTicketPart.flags = new TicketFlags(KileUtility.ConvertInt2Flags((int)encTicketFlags)); encTicketPart.crealm = serverContext.TgsTicket.crealm; encTicketPart.cname = serverContext.TgsTicket.cname; encTicketPart.transited = serverContext.TgsTicket.transited; encTicketPart.authtime = KileUtility.CurrentKerberosTime; encTicketPart.starttime = KileUtility.CurrentKerberosTime; encTicketPart.endtime = serverContext.TgsTicket.endtime; encTicketPart.renew_till = serverContext.TgsTicket.renew_till; encTicketPart.caddr = serverContext.Addresses; encTicketPart.authorization_data = ticketAuthorizationData; response.TicketEncPart = encTicketPart; // Set AS_REP response.Response.pvno = new Asn1Integer(ConstValue.KERBEROSV5); response.Response.msg_type = new Asn1Integer((int)MsgType.KRB_TGS_RESP); response.Response.padata = seqOfPaData; response.Response.crealm = serverContext.UserRealm; response.Response.cname = serverContext.UserName; response.Response.ticket = ticket; // Set EncASRepPart EncTGSRepPart encTGSRepPart = new EncTGSRepPart(); encTGSRepPart.key = encTicketPart.key; LastReq_element element = new LastReq_element(new Int32(0), KileUtility.CurrentKerberosTime); encTGSRepPart.last_req = new LastReq(new LastReq_element[] { element }); encTGSRepPart.nonce = serverContext.Nonce; encTGSRepPart.flags = encTicketPart.flags; encTGSRepPart.authtime = encTicketPart.authtime; encTGSRepPart.starttime = encTicketPart.starttime; encTGSRepPart.endtime = encTicketPart.endtime; encTGSRepPart.renew_till = encTicketPart.renew_till; encTGSRepPart.srealm = ticket.realm; encTGSRepPart.sname = ticket.sname; encTGSRepPart.caddr = encTicketPart.caddr; response.EncPart = encTGSRepPart; return response; }
internal static global::System.Runtime.InteropServices.HandleRef getCPtr(EncryptionKey obj) { return((obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr); }
private void Smb2KerberosAuthentication(CaseVariant variant) { BaseTestSite.Log.Add(LogEntryKind.TestStep, "Initialize Kerberos Functional Client"); KerberosFunctionalClient kerberosClient = new KerberosFunctionalClient( TestConfig.DomainName, TestConfig.UserName, TestConfig.UserPassword, KerberosAccountType.User, KDCIP, KDCPort, TransportType.TCP, OidPkt, BaseTestSite); #region Service Ticket EncryptionKey serviceKey; EncTicketPart encTicketPart = RetrieveAndDecryptServiceTicket(kerberosClient, out serviceKey); Ticket serviceTicket = kerberosClient.Context.Ticket.Ticket; Realm crealm = serviceTicket.realm; BaseTestSite.Assert.AreEqual(TestConfig.DomainName.ToLower(), encTicketPart.crealm.Value.ToLower(), "Realm name in service ticket encrypted part should match as expected, case insensitive"); BaseTestSite.Assert.AreEqual(TestConfig.UserName.ToLower(), KerberosUtility.PrincipalName2String(encTicketPart.cname).ToLower(), "User name in service ticket encrypted part should match as expected, case insensitive."); if (variant.HasFlag(CaseVariant.AUTHDATA_UNKNOWN_TYPE_IN_TKT)) { BaseTestSite.Log.Add(LogEntryKind.TestStep, "Add a type-unknown AuthorizationData to the ticket"); AuthorizationDataElement unknownElement = GenerateUnKnownAuthorizationDataElement(); AppendNewAuthDataElement(encTicketPart.authorization_data, unknownElement); } if (variant.HasFlag(CaseVariant.AUTHDATA_UNKNOWN_TYPE_IN_TKT_OPTIONAL)) { BaseTestSite.Log.Add(LogEntryKind.TestStep, "Add a type-unknown AuthorizationData which is inside AD_IF_RELEVANT to the ticket"); AuthorizationDataElement unknownElement = GenerateUnKnownAuthorizationDataElement(); AD_IF_RELEVANT ifRelavantElement = new AD_IF_RELEVANT(new[] { unknownElement }); var dataBuffer = new Asn1BerEncodingBuffer(); ifRelavantElement.BerEncode(dataBuffer); AuthorizationDataElement unknownElementOptional = new AuthorizationDataElement(new KerbInt32((long)AuthorizationData_elementType.AD_IF_RELEVANT), new Asn1OctetString(dataBuffer.Data)); AppendNewAuthDataElement(encTicketPart.authorization_data, unknownElementOptional); } if (variant.HasFlag(CaseVariant.TICKET_NOT_VALID)) { BaseTestSite.Log.Add(LogEntryKind.TestStep, "Change the Ticket start time to tomorrow"); DateTime tomorrow = DateTime.Now.AddDays(1); string kerbTimeString = tomorrow.ToUniversalTime().ToString("yyyyMMddhhmmssZ"); encTicketPart.starttime = new KerberosTime(kerbTimeString, true); } if (variant.HasFlag(CaseVariant.TICKET_EXPIRED)) { BaseTestSite.Log.Add(LogEntryKind.TestStep, "Change the Ticket end time to yesterday"); DateTime yesterday = DateTime.Now.AddDays(-1); string kerbTimeString = yesterday.ToUniversalTime().ToString("yyyyMMddhhmmssZ"); encTicketPart.endtime = new KerberosTime(kerbTimeString, true); } if (variant.HasFlag(CaseVariant.TICKET_WRONG_ENC_KEY)) { BaseTestSite.Log.Add(LogEntryKind.TestStep, "Modify the Ticket, making it encrypted with wrong key"); serviceKey = KerberosUtility.GenerateKey(serviceKey); } EncryptedData data = EncryptTicket(encTicketPart, serviceKey); serviceTicket.enc_part = data; if (variant.HasFlag(CaseVariant.TICKET_WRONG_REALM)) { BaseTestSite.Log.Add(LogEntryKind.TestStep, "Change the Realm in the Ticket to an unknown realm"); serviceTicket.realm = new Realm("kerb.com"); } if (variant.HasFlag(CaseVariant.TICKET_WRONG_SNAME)) { BaseTestSite.Log.Add(LogEntryKind.TestStep, "Change the SNAME in the Ticket to an unknown service name"); serviceTicket.sname = new PrincipalName(new KerbInt32((long)PrincipalType.NT_SRV_INST), KerberosUtility.String2SeqKerbString("UnknownService", TestConfig.DomainName)); } if (variant.HasFlag(CaseVariant.TICKET_WRONG_KVNO)) { BaseTestSite.Log.Add(LogEntryKind.TestStep, "Change the KVNO in the Ticket to an invalid Key Version Number (Int32.MaxValue)"); const int invalidKvno = System.Int32.MaxValue; serviceTicket.enc_part.kvno = new KerbInt32(invalidKvno); } #endregion #region Authenticator BaseTestSite.Log.Add(LogEntryKind.TestStep, "Create Authenticator"); EncryptionKey subkey = KerberosUtility.GenerateKey(kerberosClient.Context.SessionKey); PrincipalName cname; if (variant.HasFlag(CaseVariant.AUTHENTICATOR_CNAME_NOT_MATCH)) { BaseTestSite.Log.Add(LogEntryKind.TestStep, "Use wrong cname in the Authenticator"); cname = new PrincipalName(new KerbInt32((long)PrincipalType.NT_PRINCIPAL), KerberosUtility.String2SeqKerbString(TestConfig.NonAdminUserName, TestConfig.DomainName)); } else { cname = kerberosClient.Context.CName.Name; } Authenticator authenticator = CreateAuthenticator(cname, crealm, subkey); if (variant.HasFlag(CaseVariant.AUTHENTICATOR_CREALM_NOT_MATCH)) { BaseTestSite.Log.Add(LogEntryKind.TestStep, "Use wrong crealm in the Authenticator"); authenticator.crealm = new Realm("kerb.com"); } if (variant.HasFlag(CaseVariant.AUTHENTICATOR_EXCEED_TIME_SKEW)) { BaseTestSite.Log.Add(LogEntryKind.TestStep, "Change the ctime in the Authenticator to one hour later"); DateTime oneHourLater = DateTime.Now.AddHours(1); string kerbTimeString = oneHourLater.ToUniversalTime().ToString("yyyyMMddhhmmssZ"); authenticator.ctime = new KerberosTime(kerbTimeString, true); } if (variant.HasFlag(CaseVariant.AUTHDATA_UNKNOWN_TYPE_IN_AUTHENTICATOR)) { BaseTestSite.Log.Add(LogEntryKind.TestStep, "Add a type-unknown AuthorizationData to the Authenticator"); AuthorizationDataElement unknownElement = GenerateUnKnownAuthorizationDataElement(); authenticator.authorization_data = new AuthorizationData(new[] { unknownElement }); } if (variant.HasFlag(CaseVariant.AUTHDATA_UNKNOWN_TYPE_IN_AUTHENTICATOR_OPTIONAL)) { BaseTestSite.Log.Add(LogEntryKind.TestStep, "Add a type-unknown AuthorizationData which is inside AD_IF_RELEVANT to the Authenticator"); AuthorizationDataElement unknownElement = GenerateUnKnownAuthorizationDataElement(); AD_IF_RELEVANT ifRelavantElement = new AD_IF_RELEVANT(new[] { unknownElement }); var dataBuffer = new Asn1BerEncodingBuffer(); ifRelavantElement.BerEncode(dataBuffer); AuthorizationDataElement unknownElementOptional = new AuthorizationDataElement(new KerbInt32((long)AuthorizationData_elementType.AD_IF_RELEVANT), new Asn1OctetString(dataBuffer.Data)); authenticator.authorization_data = new AuthorizationData(new[] { unknownElementOptional }); } #endregion #region AP Request BaseTestSite.Log.Add(LogEntryKind.TestStep, "Create AP Request"); if (variant.HasFlag(CaseVariant.AUTHENTICATOR_WRONG_ENC_KEY)) { BaseTestSite.Log.Add(LogEntryKind.TestStep, "Use wrong key to encrypt the Authenticator"); kerberosClient.Context.Ticket.SessionKey = KerberosUtility.GenerateKey(kerberosClient.Context.Ticket.SessionKey); } KerberosApRequest request = new KerberosApRequest( kerberosClient.Context.Pvno, new APOptions(KerberosUtility.ConvertInt2Flags((int)ApOptions.MutualRequired)), kerberosClient.Context.Ticket, authenticator, KeyUsageNumber.AP_REQ_Authenticator ); #endregion BaseTestSite.Log.Add(LogEntryKind.TestStep, "Create GSS Token"); byte[] token = KerberosUtility.AddGssApiTokenHeader(request, OidPkt, GssToken); Smb2FunctionalClientForKerbAuth smb2Client = new Smb2FunctionalClientForKerbAuth(TestConfig.Timeout, TestConfig, BaseTestSite); smb2Client.ConnectToServer(TestConfig.UnderlyingTransport, TestConfig.SutComputerName, TestConfig.SutIPAddress); #region Check the result byte[] repToken; uint status = DoSessionSetupWithGssToken(smb2Client, token, out repToken); if (variant.HasFlag(CaseVariant.AUTHENTICATOR_CNAME_NOT_MATCH) || variant.HasFlag(CaseVariant.AUTHENTICATOR_CREALM_NOT_MATCH)) { BaseTestSite.Assert.AreNotEqual(Smb2Status.STATUS_SUCCESS, status, "Session Setup should fail because the cname or crealm in the authenticator does not match the same field in the Ticket"); if (TestConfig.IsWindowsPlatform) { KerberosKrbError krbError = kerberosClient.GetKrbErrorFromToken(repToken); BaseTestSite.Assert.AreEqual(KRB_ERROR_CODE.KRB_AP_ERR_BADMATCH, krbError.ErrorCode, "SMB Server should return {0}", KRB_ERROR_CODE.KRB_AP_ERR_BADMATCH); } smb2Client.Disconnect(); return; } if (variant.HasFlag(CaseVariant.AUTHENTICATOR_WRONG_ENC_KEY) || variant.HasFlag(CaseVariant.TICKET_WRONG_ENC_KEY)) { BaseTestSite.Assert.AreNotEqual(Smb2Status.STATUS_SUCCESS, status, "Session Setup should fail because Ticket or Authenticator cannot be correctly decrypted"); if (TestConfig.IsWindowsPlatform) { KerberosKrbError krbError = kerberosClient.GetKrbErrorFromToken(repToken); BaseTestSite.Assert.AreEqual(KRB_ERROR_CODE.KRB_AP_ERR_MODIFIED, krbError.ErrorCode, "SMB Server should return {0}", KRB_ERROR_CODE.KRB_AP_ERR_MODIFIED); } smb2Client.Disconnect(); return; } if (variant.HasFlag(CaseVariant.AUTHENTICATOR_EXCEED_TIME_SKEW)) { BaseTestSite.Assert.AreNotEqual(Smb2Status.STATUS_SUCCESS, status, "Session Setup should fail because the server time and the client time " + "in the Authenticator differ by (1 hour) more than the allowable clock skew"); if (TestConfig.IsWindowsPlatform) { KerberosKrbError krbError = kerberosClient.GetKrbErrorFromToken(repToken); BaseTestSite.Assert.AreEqual(KRB_ERROR_CODE.KRB_AP_ERR_SKEW, krbError.ErrorCode, "SMB Server should return {0}", KRB_ERROR_CODE.KRB_AP_ERR_SKEW); } smb2Client.Disconnect(); return; } if (variant.HasFlag(CaseVariant.TICKET_WRONG_KVNO) || variant.HasFlag(CaseVariant.TICKET_WRONG_REALM) || variant.HasFlag(CaseVariant.TICKET_WRONG_SNAME)) { BaseTestSite.Log.Add(LogEntryKind.Comment, "If decryption fails, server would try other keys"); } if (variant.HasFlag(CaseVariant.TICKET_NOT_VALID)) { BaseTestSite.Assert.AreNotEqual(Smb2Status.STATUS_SUCCESS, status, "Session Setup should fail because the starttime (tomorrow) in the Ticket " + "is later than the current time by more than the allowable clock skew"); if (TestConfig.IsWindowsPlatform) { KerberosKrbError krbError = kerberosClient.GetKrbErrorFromToken(repToken); BaseTestSite.Assert.AreEqual(KRB_ERROR_CODE.KRB_AP_ERR_TKT_NYV, krbError.ErrorCode, "SMB Server should return {0}", KRB_ERROR_CODE.KRB_AP_ERR_TKT_NYV); } smb2Client.Disconnect(); return; } if (variant.HasFlag(CaseVariant.TICKET_EXPIRED)) { BaseTestSite.Assert.AreNotEqual(Smb2Status.STATUS_SUCCESS, status, "Session Setup should fail because the current time is later than the endtime (yesterday)" + " in the Ticket by more than the allowable clock skew"); if (TestConfig.IsWindowsPlatform) { KerberosKrbError krbError = kerberosClient.GetKrbErrorFromToken(repToken); BaseTestSite.Assert.AreEqual(KRB_ERROR_CODE.KRB_AP_ERR_TKT_EXPIRED, krbError.ErrorCode, "SMB Server should return {0}", KRB_ERROR_CODE.KRB_AP_ERR_TKT_EXPIRED); } smb2Client.Disconnect(); return; } if (variant.HasFlag(CaseVariant.AUTHDATA_UNKNOWN_TYPE_IN_TKT)) { BaseTestSite.Assert.AreNotEqual(Smb2Status.STATUS_SUCCESS, status, "Session Setup should fail because of the unknown AutherizationData in the ticket"); smb2Client.Disconnect(); return; } if (variant.HasFlag(CaseVariant.AUTHDATA_UNKNOWN_TYPE_IN_AUTHENTICATOR)) { BaseTestSite.Log.Add(LogEntryKind.Comment, "Unknown AuthorizationData in the Authenticator should not fail the request"); } if (variant.HasFlag(CaseVariant.AUTHDATA_UNKNOWN_TYPE_IN_TKT_OPTIONAL) || variant.HasFlag(CaseVariant.AUTHDATA_UNKNOWN_TYPE_IN_AUTHENTICATOR_OPTIONAL)) { BaseTestSite.Log.Add(LogEntryKind.Comment, "Unknown AuthorizationData in AD_IF_RELEVANT is optional. " + "Server should not fail the request."); } KerberosApResponse apRep = kerberosClient.GetApResponseFromToken(repToken, GssToken); // Get subkey from AP response, which used for signing in smb2 apRep.Decrypt(kerberosClient.Context.Ticket.SessionKey.keyvalue.ByteArrayValue); smb2Client.SetSessionSigningAndEncryption(true, false, apRep.ApEncPart.subkey.keyvalue.ByteArrayValue); string path = Smb2Utility.GetUncPath(TestConfig.SutComputerName, TestConfig.BasicFileShare); AccessFile(smb2Client, path); #endregion smb2Client.LogOff(); smb2Client.Disconnect(); }
public TransactionCacheRepository(SQLiteConnection database, EncryptionKey encryptionKey) : base(database, encryptionKey) { }
protected SecureRepository(SQLiteConnection database, EncryptionKey encryptionKey) : base(database) { EncryptionKey = encryptionKey; }
static void Main(string[] args) { // step 1 create customer encryption key var key = EncryptionKey.Generate().Base64Key; var encryptionKey = EncryptionKey.Create(Convert.FromBase64String(key)); // step 2 get you service Acount cert for auth string serviceAcountCert = "stackoverflow54387198-xxxxxxxx.json"; // step 3 get you service Acount cert for auth string bucketName = "stackoverflow_54387198_bucket"; string localPath = "FileToUpload.txt"; string objectName = null; // step 4 create a local text file to upload File.WriteAllText(localPath, "test"); // step 5 Create Google Storage Client var storage = StorageClient.Create( GoogleCredential.FromJson(File.ReadAllText(serviceAcountCert))); // step 6 upload the file with the customer encryption key from step 1 using (var f = File.OpenRead(localPath)) { objectName = objectName ?? Path.GetFileName(localPath); storage.UploadObject(bucketName, objectName, null, f, new UploadObjectOptions() { EncryptionKey = encryptionKey }); Console.WriteLine($"Uploaded {objectName}."); } // step 7 create a url // step 7.1 create add x-goog-encryption-algorithm hear //to tell google you are using customer encryption key var requestHeaders = new Dictionary <string, IEnumerable <string> > { { "x-goog-encryption-algorithm", new [] { "AES256" } } }; // step 7.2 set other parameters var expireAfter = TimeSpan.FromHours(30.0); var verb = HttpMethod.Get; // step 7.3 create a Url Signer var urlSigner = UrlSigner.FromServiceAccountPath(serviceAcountCert); // step 7.4 create a secure url var url = urlSigner.Sign( bucketName, objectName, expireAfter, verb, requestHeaders); // step 8 use the Your Url // step 8.1 create HttpClient var client = new HttpClient(); // step 8.1 add x-goog-encryption-algorithm header the same from step 7 client.DefaultRequestHeaders.Add("x-goog-encryption-algorithm", "AES256"); // step 8.2 add x-goog-encryption-key header with customer encryption key (Base64Hash) client.DefaultRequestHeaders.Add("x-goog-encryption-key", encryptionKey.Base64Key); // step 8.3 add x-goog-encryption-key header with customer encryption key (Base64Hash) client.DefaultRequestHeaders.Add("x-goog-encryption-key-sha256", encryptionKey.Base64Hash); // step 8.4 Download the file Task.Run(async() => { var response = await client.GetAsync(url); var contents = await response.Content.ReadAsStringAsync(); // contents == "test" Console.WriteLine($"contents=>{contents}"); }).GetAwaiter().GetResult(); Console.ReadLine(); }
private void CBAC_Smb2_AccessFile(string RealmName, User user, Computer kdc, TransportType transportType, FileServer fileserver, string filePath, string fileName, bool expectAccessDeny) { base.Logging(); client = new KerberosTestClient(RealmName, user.Username, user.Password, KerberosAccountType.User, kdc.IPAddress, kdc.Port, transportType, testConfig.SupportedOid); KdcOptions options = KdcOptions.FORWARDABLE | KdcOptions.CANONICALIZE | KdcOptions.RENEWABLE; client.SendAsRequest(options, null); METHOD_DATA methodData; KerberosKrbError krbError = client.ExpectPreauthRequiredError(out methodData); BaseTestSite.Log.Add(LogEntryKind.Comment, "Create and send AS request with PaEncTimeStamp, PaPacRequest and paPacOptions."); string timeStamp = KerberosUtility.CurrentKerberosTime.Value; PaEncTimeStamp paEncTimeStamp = new PaEncTimeStamp(timeStamp, 0, client.Context.SelectedEType, client.Context.CName.Password, this.client.Context.CName.Salt); PaPacRequest paPacRequest = new PaPacRequest(true); PaPacOptions paPacOptions = new PaPacOptions(PacOptions.Claims | PacOptions.ForwardToFullDc); Asn1SequenceOf <PA_DATA> seqOfPaData = new Asn1SequenceOf <PA_DATA>(new PA_DATA[] { paEncTimeStamp.Data, paPacRequest.Data, paPacOptions.Data }); client.SendAsRequest(options, seqOfPaData); KerberosAsResponse asResponse = client.ExpectAsResponse(); //Verify encrypted padata PaSupportedEncTypes paSupportedEncTypes = null; BaseTestSite.Assert.IsNotNull(asResponse.EncPart, "The encrypted part of AS-REP is decrypted."); BaseTestSite.Assert.IsNotNull(asResponse.EncPart.pa_datas, "The encrypted padata is not null."); if (this.testConfig.IsKileImplemented) { foreach (var padata in asResponse.EncPart.pa_datas.Elements) { var parsedPadata = PaDataParser.ParseRepPaData(padata); if (parsedPadata is PaSupportedEncTypes) { paSupportedEncTypes = parsedPadata as PaSupportedEncTypes; } } BaseTestSite.Assert.IsNotNull(paSupportedEncTypes, "The encrypted padata of AS-REP contains PA_SUPPORTED_ENCTYPES."); if (this.testConfig.IsClaimSupported) { BaseTestSite.Assert.IsTrue( paSupportedEncTypes.SupportedEncTypes.HasFlag(SupportedEncryptionTypes.Claims_Supported), "Claims is supported."); } } //TGS exchange BaseTestSite.Log.Add(LogEntryKind.Comment, "Create and send FAST armored TGS request: {0}.", fileserver.Smb2ServiceName); Asn1SequenceOf <PA_DATA> seqOfPaData2 = new Asn1SequenceOf <PA_DATA>(new PA_DATA[] { paPacRequest.Data, paPacOptions.Data }); client.SendTgsRequest(fileserver.Smb2ServiceName, options, seqOfPaData2); KerberosTgsResponse tgsResponse = client.ExpectTgsResponse(); EncryptionKey key = testConfig.QueryKey(fileserver.Smb2ServiceName, client.Context.Realm.ToString(), client.Context.SelectedEType); tgsResponse.DecryptTicket(key); BaseTestSite.Assert.IsNotNull(tgsResponse.EncPart, "The encrypted part of TGS-REP is decrypted."); //Verify TGS encryped padata paSupportedEncTypes = null; BaseTestSite.Assert.IsNotNull(tgsResponse.EncPart, "The encrypted part of TGS-REP is decrypted."); BaseTestSite.Assert.IsNotNull(tgsResponse.EncPart.pa_datas, "The encrypted padata of TGS-REP is not null."); if (this.testConfig.IsKileImplemented) { foreach (var padata in tgsResponse.EncPart.pa_datas.Elements) { var parsedPadata = PaDataParser.ParseRepPaData(padata); if (parsedPadata is PaSupportedEncTypes) { paSupportedEncTypes = parsedPadata as PaSupportedEncTypes; } } BaseTestSite.Assert.IsNotNull(paSupportedEncTypes, "The encrypted padata of TGS-REP contains PA_SUPPORTED_ENCTYPES."); } if (this.testConfig.IsKileImplemented) { BaseTestSite.Assert.IsNotNull(tgsResponse.TicketEncPart.authorization_data, "The ticket contains Authorization data."); AdWin2KPac adWin2kPac = FindOneInAuthData <AdWin2KPac>(tgsResponse.TicketEncPart.authorization_data.Elements); BaseTestSite.Assert.IsNotNull(adWin2kPac, "The Authorization data contains AdWin2KPac."); } AuthorizationData data = null; EncryptionKey subkey = KerberosUtility.GenerateKey(client.Context.SessionKey); byte[] token = client.CreateGssApiToken(ApOptions.MutualRequired, data, subkey, ChecksumFlags.GSS_C_MUTUAL_FLAG | ChecksumFlags.GSS_C_INTEG_FLAG); BaseTestSite.Log.Add(LogEntryKind.Comment, "Logon to fileserver and Access File."); AccessFile(filePath, fileName, fileserver, token, tgsResponse.EncPart.key, expectAccessDeny); }
/// <inheritdoc /> public async Task <DbUser> CreateAsync(Seed seed, string name, string imagePath, string imageBase64, EncryptionKey encryptionKey) { var response = await this.CreateUserInteractor.ExecuteAsync(new CreateUserRequest { Seed = seed }); if (response.Code != ResponseCode.Success) { return(null); } return(new DbUser { Name = name, Seed = seed.Value, ImagePath = imagePath, ImageBase64 = imageBase64, StoreSeed = true, PublicKeyAddress = response.PublicKeyAddress.Value, RequestAddress = response.RequestAddress.Value, NtruKeyPair = response.NtruKeyPair, EncryptionKey = encryptionKey }); }
private void AccessFile(string sharePath, string fileName, FileServer fileServer, byte[] gssApiToken, EncryptionKey subkey, bool expectAccessDeny) { BaseTestSite.Log.Add(LogEntryKind.Comment, "AccessFile: Create a SMB2 Client and Negotiate"); Smb2FunctionalTestClient smb2Client = new Smb2FunctionalTestClient(KerberosConstValue.TIMEOUT_FOR_SMB2AP); smb2Client.ConnectToServerOverTCP(System.Net.IPAddress.Parse(fileServer.IPAddress)); DialectRevision smb2Dialect = (DialectRevision)Enum.Parse(typeof(DialectRevision), fileServer.Smb2Dialect); DialectRevision selectedDialect; uint status = smb2Client.Negotiate( new DialectRevision[] { smb2Dialect }, SecurityMode_Values.NONE, Capabilities_Values.GLOBAL_CAP_DFS, Guid.NewGuid(), out selectedDialect); BaseTestSite.Assert.AreEqual(Smb2Status.STATUS_SUCCESS, status, "Negotiate failed with error: {0}", status); byte[] repToken; BaseTestSite.Log.Add(LogEntryKind.Comment, "AccessFile: Session Setup"); status = smb2Client.SessionSetup( SESSION_SETUP_Request_SecurityMode_Values.NONE, SESSION_SETUP_Request_Capabilities_Values.GLOBAL_CAP_DFS, SecurityPackageType.Kerberos, fileServer.FQDN, gssApiToken, out repToken); BaseTestSite.Assert.AreEqual(Smb2Status.STATUS_SUCCESS, status, "Session setup failed with error: {0}", status); KerberosApResponse apRep = client.GetApResponseFromToken(repToken); // Get subkey from AP response, which used for signing in smb2 apRep.Decrypt(subkey.keyvalue.ByteArrayValue); smb2Client.SetSessionSigningAndEncryption(true, false, apRep.ApEncPart.subkey.keyvalue.ByteArrayValue); BaseTestSite.Log.Add(LogEntryKind.Comment, "AccessFile: Tree Connect"); uint treeId; string path = @"\\" + fileServer.FQDN + @"\" + sharePath; status = smb2Client.TreeConnect(path, out treeId); BaseTestSite.Assert.AreEqual(Smb2Status.STATUS_SUCCESS, status, "TreeConnect failed with error: {0}", status); BaseTestSite.Log.Add(LogEntryKind.Comment, "AccessFile: Create"); Smb2CreateContextResponse[] serverCreateContexts; FILEID fileId; status = smb2Client.Create( treeId, fileName, CreateOptions_Values.FILE_NON_DIRECTORY_FILE, out fileId, out serverCreateContexts, RequestedOplockLevel_Values.OPLOCK_LEVEL_LEASE, new Smb2CreateContextRequest[] { new Smb2CreateRequestLeaseV2 { LeaseKey = Guid.NewGuid(), LeaseState = LeaseStateValues.SMB2_LEASE_READ_CACHING | LeaseStateValues.SMB2_LEASE_HANDLE_CACHING | LeaseStateValues.SMB2_LEASE_WRITE_CACHING, } }, checker: SkipResponseCheck); if (expectAccessDeny) { BaseTestSite.Assert.AreEqual(Smb2Status.STATUS_ACCESS_DENIED, status, "Create Operation should fail due to STATUS_ACCESS_DENIED, the received status is: {0}", status); } else { // Create success BaseTestSite.Assert.AreEqual(Smb2Status.STATUS_SUCCESS, status, "Create failed with error: {0}", status); BaseTestSite.Log.Add(LogEntryKind.Comment, "AccessFile: Close"); status = smb2Client.Close(treeId, fileId); BaseTestSite.Assert.AreEqual(Smb2Status.STATUS_SUCCESS, status, "Close failed with error: {0}", status); } BaseTestSite.Log.Add(LogEntryKind.Comment, "AccessFile: Tree Disconnect"); status = smb2Client.TreeDisconnect(treeId); BaseTestSite.Assert.AreEqual(Smb2Status.STATUS_SUCCESS, status, "Tree Disconnect failed with error: {0}", status); BaseTestSite.Log.Add(LogEntryKind.Comment, "AccessFile: Logoff"); status = smb2Client.LogOff(); BaseTestSite.Assert.AreEqual(Smb2Status.STATUS_SUCCESS, status, "Logoff failed with error: {0}", status); smb2Client.Disconnect(); }
public KileTgsResponse CreateTgsResponse( KileConnection kileConnection, Asn1SequenceOf <PA_DATA> seqOfPaData, EncTicketFlags encTicketFlags, EncryptionKey ticketEncryptKey, AuthorizationData ticketAuthorizationData) { KileServerContext serverContext = GetServerContextByKileConnection(kileConnection); if (ticketEncryptKey == null) { throw new ArgumentNullException(nameof(ticketEncryptKey)); } else { serverContext.TicketEncryptKey = ticketEncryptKey; } var response = new KileTgsResponse(serverContext); // Construct a Ticket var ticket = new Ticket(); ticket.tkt_vno = new Asn1Integer(ConstValue.KERBEROSV5); ticket.realm = new Realm(domain); ticket.sname = serverContext.SName; // Set EncTicketPart var encTicketPart = new EncTicketPart(); EncryptionType encryptionType = (EncryptionType)serverContext.EncryptType.Elements[0].Value; encTicketPart.key = new EncryptionKey(new KerbInt32((int)encryptionType), new Asn1OctetString(GetEncryptionKeyByType(encryptionType))); encTicketPart.flags = new TicketFlags(KileUtility.ConvertInt2Flags((int)encTicketFlags)); encTicketPart.crealm = serverContext.TgsTicket.crealm; encTicketPart.cname = serverContext.TgsTicket.cname; encTicketPart.transited = serverContext.TgsTicket.transited; encTicketPart.authtime = KileUtility.CurrentKerberosTime; encTicketPart.starttime = KileUtility.CurrentKerberosTime; encTicketPart.endtime = serverContext.TgsTicket.endtime; encTicketPart.renew_till = serverContext.TgsTicket.renew_till; encTicketPart.caddr = serverContext.Addresses; encTicketPart.authorization_data = ticketAuthorizationData; response.TicketEncPart = encTicketPart; // Set AS_REP response.Response.pvno = new Asn1Integer(ConstValue.KERBEROSV5); response.Response.msg_type = new Asn1Integer((int)MsgType.KRB_TGS_RESP); response.Response.padata = seqOfPaData; response.Response.crealm = serverContext.UserRealm; response.Response.cname = serverContext.UserName; response.Response.ticket = ticket; // Set EncASRepPart var encTGSRepPart = new EncTGSRepPart(); encTGSRepPart.key = encTicketPart.key; var element = new LastReqElement(new KerbInt32(0), KileUtility.CurrentKerberosTime); encTGSRepPart.last_req = new LastReq(new LastReqElement[] { element }); encTGSRepPart.nonce = serverContext.Nonce; encTGSRepPart.flags = encTicketPart.flags; encTGSRepPart.authtime = encTicketPart.authtime; encTGSRepPart.starttime = encTicketPart.starttime; encTGSRepPart.endtime = encTicketPart.endtime; encTGSRepPart.renew_till = encTicketPart.renew_till; encTGSRepPart.srealm = ticket.realm; encTGSRepPart.sname = ticket.sname; encTGSRepPart.caddr = encTicketPart.caddr; response.EncPart = encTGSRepPart; return(response); }
/// <summary> /// This function will change Coruzant Post NFT /// You can use this function for sending the NFT when you will fill receiver parameter /// </summary> /// <param name="address">sender address</param> /// <param name="ekey">Encryption Key object of the address</param> /// <param name="NFT">Input NFT object with data to save to metadata. Must contain Utxo hash</param> /// <param name="nutxos">List of spendable neblio utxos if you have it loaded.</param> /// <param name="receiver">Fill when you want to send NFT to another address</param> /// <returns>New Tx Id Hash</returns> public static async Task <string> ChangeCoruzantPostNFT(string address, EncryptionKey ekey, INFT NFT, ICollection <Utxos> nutxos, NBitcoin.BitcoinSecret secret, string receiver = "") { var cnft = NFT as CoruzantArticleNFT; // create token metadata var metadata = new Dictionary <string, string>(); metadata.Add("NFT", "true"); metadata.Add("Type", "NFT CoruzantPost"); metadata.Add("Name", NFT.Name); metadata.Add("Author", NFT.Author); metadata.Add("AuthorProfileUtxo", cnft.AuthorProfileUtxo); metadata.Add("Description", NFT.Description); metadata.Add("Image", NFT.ImageLink); metadata.Add("Link", NFT.Link); metadata.Add("Tags", NFT.Tags); metadata.Add("FullPostLink", cnft.FullPostLink); metadata.Add("LastComment", cnft.LastComment); metadata.Add("LastCommentBy", cnft.LastCommentBy); if (NFT.Price > 0) { metadata.Add("Price", NFT.Price.ToString(CultureInfo.InvariantCulture)); } var rec = address; if (!string.IsNullOrEmpty(receiver)) { rec = receiver; } // fill input data for sending tx var dto = new SendTokenTxData() // please check SendTokenTxData for another properties such as specify source UTXOs { Id = CoruzantTokenId, // id of token Metadata = metadata, Amount = 1, sendUtxo = new List <string>() { NFT.Utxo }, SenderAddress = address, ReceiverAddress = rec }; try { // send tx var transaction = await NeblioTransactionHelpers.SendNFTTokenAsync(dto, nutxos); var rtxid = await NeblioTransactionHelpers.SignAndBroadcastTransaction(transaction, secret); if (rtxid != null) { return(rtxid); } else { return(string.Empty); } } catch (Exception ex) { throw ex; } }
/// <summary> /// Initialize the context from a token. /// </summary> /// <param name="inToken">The token used to initialize.</param> /// <exception cref="System.NotSupportedException">Thrown when the ContextAttribute contains a flag that not be /// supported.</exception> /// <exception cref="System.InvalidOperationException">Thrown when an error is returned.</exception> public override void Initialize(byte[] inToken) { if (inToken == null || inToken.Length == 0) { // a new connection KilePdu response = null; string sname = ConstValue.KERBEROS_SNAME; KRBFlags flags = KRBFlags.FORWARDABLE | KRBFlags.RENEWABLE | KRBFlags.CANONICALIZE | KRBFlags.RENEWABLEOK; PaEncTimeStamp timestamp = client.ConstructPaEncTimeStamp(EncryptionType.RC4_HMAC); PaPacRequest pacRequest = client.ConstructPaPacRequest(true); Asn1SequenceOf <PA_DATA> paData = client.ConstructPaData(timestamp, pacRequest); KileAsRequest asRequest; EncryptionKey subkey = null; if ((contextAttribute & ClientSecurityContextAttribute.DceStyle) == ClientSecurityContextAttribute.DceStyle) { asRequest = client.CreateAsRequest(sname, flags, paData, EncryptionType.AES256_CTS_HMAC_SHA1_96, EncryptionType.RC4_HMAC); //subkey = new EncryptionKey((int)EncryptionType.AES256_CTS_HMAC_SHA1_96, // KileUtility.GenerateRandomBytes(ConstValue.AES_KEY_LENGTH)); var key = KeyGenerator.MakeKey(EncryptionType.AES256_CTS_HMAC_SHA1_96, client.ClientContext.Password, client.ClientContext.Salt); subkey = new EncryptionKey(new KerbInt32((long)EncryptionType.AES256_CTS_HMAC_SHA1_96), new Asn1OctetString(key)); } else { asRequest = client.CreateAsRequest(sname, flags, paData, EncryptionType.RC4_HMAC); } client.SendPdu(asRequest); response = client.ExpectPdu(ConstValue.TIMEOUT_DEFAULT); if (response.GetType() == typeof(KileKrbError)) { throw new InvalidOperationException("Received Kerberos Error response: " + ((KileKrbError)response).ErrorCode); } KileAsResponse asResponse = (KileAsResponse)response; sname = service; // for example: "KERB.COMldapsut02.kerb.com" client.ClientContext.Salt = domain.ToUpper(); string[] nameList = userLogonName.Split('/'); foreach (string name in nameList) { client.ClientContext.Salt += name; } KileTgsRequest tgsRequest = client.CreateTgsRequest(sname, flags, new KerbUInt32((long)Math.Abs((long)DateTime.Now.Ticks)), null, ChecksumType.hmac_md5_string, null, null); client.SendPdu(tgsRequest); response = client.ExpectPdu(ConstValue.TIMEOUT_DEFAULT); if (response.GetType() == typeof(KileKrbError)) { throw new InvalidOperationException("Received Kerberos Error response: " + ((KileKrbError)response).ErrorCode); } KileTgsResponse tgsResponse = (KileTgsResponse)response; ApOptions apOption; ChecksumFlags checksumFlag; GetFlagsByContextAttribute(out apOption, out checksumFlag); KerbAuthDataTokenRestrictions adRestriction = client.ConstructKerbAuthDataTokenRestrictions(0, (uint)LSAP_TOKEN_INFO_INTEGRITY_Flags.FULL_TOKEN, (uint)LSAP_TOKEN_INFO_INTEGRITY_TokenIL.Medium, new Guid().ToString()); AdAuthDataApOptions adApOptions = client.ConstructAdAuthDataApOptions(ConstValue.KERB_AP_OPTIONS_CBT); AuthorizationData authData = client.ConstructAuthorizationData(adRestriction, adApOptions); KileApRequest apRequest = client.CreateApRequest(apOption, ChecksumType.ap_authenticator_8003, ConstValue.SEQUENCE_NUMBER_DEFAULT, checksumFlag, subkey, authData); token = apRequest.ToBytes(); bool isMutualAuth = (contextAttribute & ClientSecurityContextAttribute.MutualAuth) == ClientSecurityContextAttribute.MutualAuth; bool isDceStyle = (contextAttribute & ClientSecurityContextAttribute.DceStyle) == ClientSecurityContextAttribute.DceStyle; if (isMutualAuth || isDceStyle) { continueProcess = true; // SEC_I_CONTINUE_NEEDED; } else { continueProcess = false; // SEC_E_OK; } } else // mutual authentication { KileApResponse apResponse = client.ParseApResponse(inToken); token = null; if ((contextAttribute & ClientSecurityContextAttribute.DceStyle) == ClientSecurityContextAttribute.DceStyle) { KileApResponse apResponseSend = client.CreateApResponse(null); token = apResponseSend.ToBytes(); } continueProcess = false; // SEC_E_OK; } }
/// Visualize that channel mask mess public static string ListChannels(ChatChannel channels, string separator = ", ") { string listChannels = string.Join(separator, EncryptionKey.getChannelsByMask(channels)); return(listChannels == "" ? "None" : listChannels); }
/// <summary> /// Create/Load an encryption key based around 3DES (Triple-DES). /// </summary> /// <param name="key">Encryption key</param> /// <param name="cipherMode">Cipher mode to use (advanced users only)</param> /// <param name="chainedInnerKey">Key operation to run prior to this key</param> public TripleDesEncryptionKey(byte[] key, CipherMode cipherMode = CipherMode.CBC, EncryptionKey chainedInnerKey = null) : base(key, chainedInnerKey) { TripleDes = new TripleDESCryptoServiceProvider(); TripleDes.Mode = cipherMode; TripleDes.Padding = PaddingMode.PKCS7; try { TripleDes.GenerateIV(); Transform(new byte[] { 0, 1, 2, 3, 4 }, TripleDes.CreateEncryptor(key, TripleDes.IV)); } catch (Exception ex) { throw new Exception("3DES encryption test unsuccessful", ex); } }
/// <summary> /// Accept client token. /// </summary> /// <param name="inToken">The client's token.</param> /// <exception cref="System.ArgumentNullException">Thrown when the input parameter is null.</exception> /// <exception cref="System.FormatException">Thrown when the token format is invalid.</exception> public override void Accept(byte[] inToken) { if (inToken == null) { throw new ArgumentNullException("inToken"); } if (isInitialToken) { KileApRequest apRequest = new KileApRequest(server.Context); apRequest.FromBytes(inToken, ticketEncryptKey); bool isMutualAuth = (apRequest.Request.ap_options.mValue[0] << 24 & (int)ApOptions.MutualRequired) == (int)ApOptions.MutualRequired; bool isDceStyle = inToken[0] != ConstValue.KERBEROS_TAG; if (isMutualAuth || isDceStyle) { EncryptionKey apSubKey = new EncryptionKey((int)EncryptionType.RC4_HMAC, Guid.NewGuid().ToByteArray()); KileApResponse apResponse = server.CreateApResponse(apSubKey); // Set a random sequence number Random randomNumber = new Random(); apResponse.ApEncPart.seq_number = new UInt32(randomNumber.Next()); server.context.currentLocalSequenceNumber = (ulong)apResponse.ApEncPart.seq_number.mValue; token = apResponse.ToBytes(); } isInitialToken = false; if (inToken[0] != ConstValue.KERBEROS_TAG) { // SEC_I_CONTINUE_NEEDED; continueProcess = true; } else { // SEC_E_OK; continueProcess = false; } } else { KileApResponse apResponse = new KileApResponse(server.Context); apResponse.FromBytes(inToken); if (server.Context.CurrentLocalSequenceNumber != (ulong)apResponse.ApEncPart.seq_number.mValue) { throw new FormatException("Sequence number does not match."); } // SEC_E_OK; continueProcess = false; token = null; } }
/// <summary> /// Create a new encryption key based around 3DES (Triple-DES) /// </summary> /// <param name="blockSize">Block size to use for key</param> /// <param name="cipherMode">Cipher mode to use (advanced users only)</param> /// <param name="chainedInnerKey">Key operation to run prior to this key</param> /// <returns>New 3DES key</returns> public static TripleDesEncryptionKey Create(int blockSize = 64, CipherMode cipherMode = CipherMode.CBC, EncryptionKey chainedInnerKey = null) { var tripleDes = new TripleDESCryptoServiceProvider(); tripleDes.Mode = cipherMode; tripleDes.Padding = PaddingMode.PKCS7; tripleDes.BlockSize = blockSize; tripleDes.GenerateKey(); return(new TripleDesEncryptionKey(tripleDes.Key, cipherMode, chainedInnerKey)); }
public KileApResponse CreateApResponse(KileConnection kileConnection, EncryptionKey subkey) { context = GetServerContextByKileConnection(kileConnection); KileApResponse apResponse = CreateApResponse(subkey); // Set a random sequence number Random randomNumber = new Random(); apResponse.ApEncPart.seq_number = new UInt32(randomNumber.Next()); context.currentLocalSequenceNumber = (ulong)apResponse.ApEncPart.seq_number.mValue; return apResponse; }
public void KerbAuth_Replay() { #region Get Service Ticket BaseTestSite.Log.Add(LogEntryKind.TestStep, "Initialize Kerberos Functional Client"); KerberosFunctionalClient kerberosClient = new KerberosFunctionalClient( TestConfig.DomainName, TestConfig.UserName, TestConfig.UserPassword, KerberosAccountType.User, KDCIP, KDCPort, TransportType.TCP, OidPkt, BaseTestSite); //Create and send AS request const KdcOptions options = KdcOptions.FORWARDABLE | KdcOptions.CANONICALIZE | KdcOptions.RENEWABLE; kerberosClient.SendAsRequest(options, null); BaseTestSite.Log.Add(LogEntryKind.TestStep, "Kerberos Functional Client expects Kerberos Error from KDC"); //Receive preauthentication required error METHOD_DATA methodData; KerberosKrbError krbError = kerberosClient.ExpectPreauthRequiredError(out methodData); BaseTestSite.Log.Add(LogEntryKind.TestStep, "Kerberos Functional Client sends AS request with PA-DATA set"); //Create sequence of PA data string timeStamp = KerberosUtility.CurrentKerberosTime.Value; PaEncTimeStamp paEncTimeStamp = new PaEncTimeStamp(timeStamp, 0, kerberosClient.Context.SelectedEType, kerberosClient.Context.CName.Password, kerberosClient.Context.CName.Salt); PaPacRequest paPacRequest = new PaPacRequest(true); Asn1SequenceOf <PA_DATA> seqOfPaData = new Asn1SequenceOf <PA_DATA>(new[] { paEncTimeStamp.Data, paPacRequest.Data }); //Create and send AS request kerberosClient.SendAsRequest(options, seqOfPaData); BaseTestSite.Log.Add(LogEntryKind.TestStep, "Kerberos Functional Client expects AS response from KDC"); KerberosAsResponse asResponse = kerberosClient.ExpectAsResponse(); BaseTestSite.Assert.IsNotNull(asResponse.Response.ticket, "AS response should contain a TGT."); //Create and send TGS request BaseTestSite.Log.Add(LogEntryKind.TestStep, "Kerberos Functional Client sends TGS request to KDC"); kerberosClient.SendTgsRequest(servicePrincipalName, options); BaseTestSite.Log.Add(LogEntryKind.TestStep, "Kerberos Functional Client expects TGS response from KDC"); KerberosTgsResponse tgsResponse = kerberosClient.ExpectTgsResponse(); BaseTestSite.Assert.AreEqual(servicePrincipalName, KerberosUtility.PrincipalName2String(tgsResponse.Response.ticket.sname), "Service principal name in service ticket should match expected."); #endregion #region Create AP request Ticket serviceTicket = kerberosClient.Context.Ticket.Ticket; Realm crealm = serviceTicket.realm; EncryptionKey subkey = KerberosUtility.GenerateKey(kerberosClient.Context.SessionKey); PrincipalName cname = kerberosClient.Context.CName.Name; Authenticator authenticator = CreateAuthenticator(cname, crealm, subkey); BaseTestSite.Log.Add(LogEntryKind.TestStep, "Create AP Request"); KerberosApRequest request = new KerberosApRequest( kerberosClient.Context.Pvno, new APOptions(KerberosUtility.ConvertInt2Flags((int)ApOptions.MutualRequired)), kerberosClient.Context.Ticket, authenticator, KeyUsageNumber.AP_REQ_Authenticator ); #endregion #region Create GSS token and send session setup request BaseTestSite.Log.Add(LogEntryKind.TestStep, "Create GSS Token"); byte[] token = KerberosUtility.AddGssApiTokenHeader(request, OidPkt, GssToken); Smb2FunctionalClientForKerbAuth smb2Client = new Smb2FunctionalClientForKerbAuth(TestConfig.Timeout, TestConfig, BaseTestSite); smb2Client.ConnectToServer(TestConfig.UnderlyingTransport, TestConfig.SutComputerName, TestConfig.SutIPAddress); byte[] repToken; uint status = DoSessionSetupWithGssToken(smb2Client, token, out repToken); KerberosApResponse apRep = kerberosClient.GetApResponseFromToken(repToken, GssToken); // Get subkey from AP response, which used for signing in smb2 apRep.Decrypt(kerberosClient.Context.Ticket.SessionKey.keyvalue.ByteArrayValue); smb2Client.SetSessionSigningAndEncryption(true, false, apRep.ApEncPart.subkey.keyvalue.ByteArrayValue); #endregion #region Second client BaseTestSite.Log.Add(LogEntryKind.TestStep, "Replay the request from another client"); Smb2FunctionalClientForKerbAuth smb2Client2 = new Smb2FunctionalClientForKerbAuth(TestConfig.Timeout, TestConfig, BaseTestSite); smb2Client2.ConnectToServer(TestConfig.UnderlyingTransport, TestConfig.SutComputerName, TestConfig.SutIPAddress); status = DoSessionSetupWithGssToken(smb2Client2, token, out repToken); BaseTestSite.Assert.AreNotEqual(Smb2Status.STATUS_SUCCESS, status, "Session Setup should fail because it uses a Replay of KRB_AP_REQ"); if (TestConfig.IsWindowsPlatform) { krbError = kerberosClient.GetKrbErrorFromToken(repToken); BaseTestSite.Assert.AreEqual(KRB_ERROR_CODE.KRB_AP_ERR_REPEAT, krbError.ErrorCode, "SMB Server should return {0}", KRB_ERROR_CODE.KRB_AP_ERR_REPEAT); } smb2Client2.Disconnect(); #endregion string path = Smb2Utility.GetUncPath(TestConfig.SutComputerName, TestConfig.BasicFileShare); AccessFile(smb2Client, path); smb2Client.LogOff(); smb2Client.Disconnect(); }
public KileTgsResponse CreateTgsResponse( KileConnection kileConnection, _SeqOfPA_DATA seqOfPaData, EncTicketFlags encTicketFlags, byte[] ticketEncryptKey) { if (ticketEncryptKey == null) { throw new ArgumentNullException("ticketEncryptKey"); } EncryptionKey ticketKey = new EncryptionKey((int)EncryptionType.RC4_HMAC, ticketEncryptKey); return CreateTgsResponse(kileConnection, seqOfPaData, encTicketFlags, ticketKey, null); }
private static void ResumableUploadWithCustomerSuppliedEncryptionKeysTest_Common(StorageFixture fixture, SigningVersion signingVersion, [CallerMemberName] string caller = null) { EncryptionKey key = EncryptionKey.Generate(); var bucket = fixture.SingleVersionBucket; var name = IdGenerator.FromGuid(); var requestTemplate = RequestTemplate .FromBucket(bucket) .WithObjectName(name) .WithHttpMethod(ResumableHttpMethod) .WithRequestHeaders(new Dictionary <string, IEnumerable <string> > { { "x-goog-encryption-algorithm", new [] { "AES256" } }, { "x-goog-encryption-key-sha256", new [] { key.Base64Hash } }, { "x-goog-encryption-key", new [] { key.Base64Key } } }); var content = fixture.SmallContent; string url = null; fixture.RegisterDelayTest( s_duration, beforeDelay: async duration => { url = fixture.UrlSigner.Sign(requestTemplate, Options.FromDuration(duration).WithSigningVersion(signingVersion)); // Verify that the URL works initially. var uploader = SignedUrlResumableUpload.Create( url, new MemoryStream(content), new ResumableUploadOptions { ModifySessionInitiationRequest = key.ModifyRequest }); var progress = await uploader.UploadAsync(); Assert.Null(progress.Exception); Assert.Equal(UploadStatus.Completed, progress.Status); // Make sure the encryption succeeded. var downloadedData = new MemoryStream(); await Assert.ThrowsAsync <GoogleApiException>( () => fixture.Client.DownloadObjectAsync(bucket, name, downloadedData)); await fixture.Client.DownloadObjectAsync(bucket, name, downloadedData, new DownloadObjectOptions { EncryptionKey = key }); AssertContentEqual(content, downloadedData.ToArray()); }, afterDelay: async() => { var uploader = SignedUrlResumableUpload.Create( url, new MemoryStream(content), new ResumableUploadOptions { ModifySessionInitiationRequest = key.ModifyRequest }); // Verify that the URL no longer works. var progress = await uploader.UploadAsync(); Assert.Equal(UploadStatus.Failed, progress.Status); Assert.IsType <GoogleApiException>(progress.Exception); }, caller); }