// snippet-start:[ec2.dotnet.spot_instance_request_spot_instance] /* Creates a spot instance * * Takes six args: * AmazonEC2Client ec2Client is the EC2 client through which the spot instance request is made * string amiId is the AMI of the instance to request * string securityGroupName is the name of the security group of the instance to request * InstanceType instanceType is the type of the instance to request * string spotPrice is the price of the instance to request * int instanceCount is the number of instances to request * * See https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/EC2/MEC2RequestSpotInstancesRequestSpotInstancesRequest.html */ private static SpotInstanceRequest RequestSpotInstance( AmazonEC2Client ec2Client, string amiId, string securityGroupName, InstanceType instanceType, string spotPrice, int instanceCount) { RequestSpotInstancesRequest request = new RequestSpotInstancesRequest { SpotPrice = spotPrice, InstanceCount = instanceCount }; LaunchSpecification launchSpecification = new LaunchSpecification { ImageId = amiId, InstanceType = instanceType }; launchSpecification.SecurityGroups.Add(securityGroupName); request.LaunchSpecification = launchSpecification; var result = ec2Client.RequestSpotInstancesAsync(request); return(result.Result.SpotInstanceRequests[0]); }
public void TestDeserialization() { var deserialized = LaunchSpecification.Deserialize(expectedLaunchSpec); //Assert.Equal(handshakeKey, deserialized.HandshakeKey); Assert.Equal(sessionId, deserialized.SessionId); }
public void TestSerialization() { var launchSpecs = LaunchSpecification.GetStandardSpecs(sessionId, handshakeKey); var assembled = launchSpecs.Serialize(); //Assert.Equal(expectedLaunchSpec.Length, assembled.Length); Assert.Equal(expectedLaunchSpec, assembled); }
private static void PopulateLaunchSpecificationSecurityGroupNames(LaunchSpecification launchSpecification) { if (launchSpecification != null) { var groupNames = new List <string>(); foreach (GroupIdentifier group in launchSpecification.AllSecurityGroups) { groupNames.Add(group.GroupName); } launchSpecification.SecurityGroups = groupNames; } }
private async Task BidForInstanceAsync(CancellationToken?cancellationToken = null) { CancellationToken token = cancellationToken.HasValue ? cancellationToken.Value : new CancellationToken(); if (!this.Specification.SpotBidPrice.HasValue) { throw new ArgumentNullException("specification.SpotBidPrice"); } this.Logger.Log("Bidding for new instance. Price: ${0}, AMI: {1}, size: {2}", this.Specification.SpotBidPrice.ToString(), this.Specification.Ami, this.Specification.Size.Name); var launchSpecification = new LaunchSpecification() { ImageId = this.Specification.Ami, InstanceType = this.Specification.Size.Key, KeyName = this.privateKeyPair.KeyName, SecurityGroups = new List <string>() { this.SecurityGroupName }, }; if (!string.IsNullOrWhiteSpace(this.Specification.AvailabilityZone)) { launchSpecification.Placement = new SpotPlacement() { AvailabilityZone = this.Specification.AvailabilityZone }; } var spotResponse = await this.Client.RequestSpotInstancesAsync(new RequestSpotInstancesRequest() { InstanceCount = 1, SpotPrice = this.Specification.SpotBidPrice.ToString(), LaunchSpecification = launchSpecification, }); this.bidRequestId = spotResponse.SpotInstanceRequests[0].SpotInstanceRequestId; this.Logger.Log("Bid ID {0} created. Waiting for spot bid request to be fulfilled", this.bidRequestId); this.Logger.Log("This normally takes at least a few minutes"); this.InstanceId = await this.UntilBidActiveAsync(this.bidRequestId, token); this.Logger.Log("New instance created. Instance ID: {0}", this.InstanceId); await this.SetupInstanceAsync(token); }
public bool request_spot(string instance_type, string availability_zone, string spot_price, string key_tag) { write_log(region + " に対してスポットリクエストを作成しています。"); int nn = setting_.getValueInt("common", "request_spot_width_of_minutes"); try { InstanceNetworkInterfaceSpecification instanceNetworkInterfaceSpecification = new InstanceNetworkInterfaceSpecification(); instanceNetworkInterfaceSpecification.DeviceIndex = 0; instanceNetworkInterfaceSpecification.SubnetId = subnet_ids[availability_zone]; instanceNetworkInterfaceSpecification.Groups.Add(security_group_id); instanceNetworkInterfaceSpecification.AssociatePublicIpAddress = true; LaunchSpecification launchSpecification = new LaunchSpecification(); launchSpecification.ImageId = image_id; launchSpecification.KeyName = Helper.build_name(setting_, key_tag); launchSpecification.InstanceType = InstanceType.FindValue(instance_type); launchSpecification.Placement = new SpotPlacement(region + availability_zone); launchSpecification.NetworkInterfaces.Add(instanceNetworkInterfaceSpecification); var client = get_client(); var spot_req = new RequestSpotInstancesRequest(); spot_req.SpotPrice = spot_price; spot_req.InstanceCount = 1; spot_req.Type = SpotInstanceType.OneTime; spot_req.ValidUntil = DateTime.Now.AddMinutes(nn); spot_req.LaunchSpecification = launchSpecification; var query_res = client.RequestSpotInstances(spot_req); spot_request_id = query_res.SpotInstanceRequests[0].SpotInstanceRequestId; } catch (Exception ex) { write_log("ERROR: " + ex.ToString()); return(false); } return(true); }
public async Task <RequestSpotInstancesResponse> RequestSpotInstance( string amiId, string securityGroupName, InstanceType instanceType, string spotPrice, int instanceCount) { var request = new RequestSpotInstancesRequest(); // https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RequestSpotLaunchSpecification.html var launchSpecification = new LaunchSpecification(); launchSpecification.ImageId = amiId; launchSpecification.InstanceType = instanceType; launchSpecification.SecurityGroups.Add(securityGroupName); request.SpotPrice = spotPrice; request.InstanceCount = instanceCount; request.LaunchSpecification = launchSpecification; RequestSpotInstancesResponse response = await ec2Client.RequestSpotInstancesAsync(request); return(response); }
/// <summary> /// This function creates a spot instance request inside a VPC. It returns the request ID if successful, or sets the error /// code and message otherwise /// </summary> /// <param name="SubnetId">Id of the VPC subnet where the instances will be launched</param> /// <param name="AMI_ID">Id of the AMI that will be used as a base for the instances</param> /// <param name="SecurityGroupId">The name of the security group to be assigned to the instance(s)</param> /// <param name="KeyPairName">The name of the keypair to be assigned to the instance(s)</param> /// <param name="InstanceType">The type of the instance(s)</param> /// <param name="InstancePrice">The max price to pay for the instance(s)</param> /// <param name="InstanceCount">The number of instances to be launched</param> /// <param name="UserData">The user-data script that will be run as the instance(s) is(are) initialized</param> /// <returns>The list of Request Ids if successful</returns> public List <string> RequestVPCSpotInstances(string SubnetId, string AMI_ID, string SecurityGroupId, string KeyPairName, string InstanceType, double InstancePrice, int InstanceCount = 1, string UserData = "") { List <string> RequestIds = new List <string> (); // Initialize error values ErrorCode = 0; ErrorMessage = ""; // Create the list with security groups List <string> SecurityGroups = new List <string> () { SecurityGroupId }; // Create the network interface object (to connect with the VPC) var NetworkInterface = new InstanceNetworkInterfaceSpecification() { DeviceIndex = 0, SubnetId = SubnetId, Groups = SecurityGroups, AssociatePublicIpAddress = true }; List <InstanceNetworkInterfaceSpecification> NetworkInterfaces = new List <InstanceNetworkInterfaceSpecification> () { NetworkInterface }; // Create the launch specification LaunchSpecification launchSpecification = new LaunchSpecification() { ImageId = AMI_ID, InstanceType = InstanceType, KeyName = KeyPairName, SecurityGroups = SecurityGroups, NetworkInterfaces = NetworkInterfaces, UserData = Gadgets.Base64Encode(UserData) }; // Create the request object RequestSpotInstancesRequest spotRequest = new RequestSpotInstancesRequest() { SpotPrice = InstancePrice.ToString(), InstanceCount = InstanceCount, LaunchSpecification = launchSpecification }; // Request the instances try { var spotResponse = EC2client.RequestSpotInstances(spotRequest); // Check response for errors if (spotResponse.HttpStatusCode != HttpStatusCode.OK) { ErrorCode = Convert.ToInt32(spotResponse.HttpStatusCode); ErrorMessage = "Http Error [" + spotResponse.HttpStatusCode.ToString() + "]"; } else { foreach (SpotInstanceRequest request in spotResponse.SpotInstanceRequests) { RequestIds.Add(request.SpotInstanceRequestId); } } } catch (Exception ex) { ErrorCode = -1; ErrorMessage = ex.Message + "::" + ex.InnerException; } return(RequestIds); }
/// <summary> /// This function creates a spot instance request inside a VPC. It returns the request ID if successful, or sets the error /// code and message otherwise /// </summary> /// <param name="AvailabilityZone">Name of the Availability Zone where the instances will be launched</param> /// <param name="AMI_ID">Id of the AMI that will be used as a base for the instances</param> /// <param name="SecurityGroupId">The name of the security group to be assigned to the instance(s)</param> /// <param name="KeyPairName">The name of the keypair to be assigned to the instance(s)</param> /// <param name="InstanceType">The type of the instance(s)</param> /// <param name="InstancePrice">The max price to pay for the instance(s)</param> /// <param name="InstanceCount">The number of instances to be launched</param> /// <param name="UserData">The user-data script that will be run as the instance(s) is(are) initialized</param> /// <returns>The list of Request Ids if successful</returns> public List <string> RequestClassicSpotInstances(string AvailabilityZone, string AMI_ID, string SecurityGroupId, string KeyPairName, string InstanceType, double InstancePrice, int InstanceCount = 1, string UserData = "") { List <string> RequestIds = new List <string> (); // Initialize error values ErrorCode = 0; ErrorMessage = ""; // Create the list with security groups List <string> SecurityGroups = new List <string> () { SecurityGroupId }; // Create placement object SpotPlacement spotPlacement = new SpotPlacement() { AvailabilityZone = AvailabilityZone }; // Create the launch specification LaunchSpecification launchSpecification = new LaunchSpecification() { ImageId = AMI_ID, InstanceType = InstanceType, KeyName = KeyPairName, SecurityGroups = SecurityGroups, Placement = spotPlacement, UserData = Gadgets.Base64Encode(UserData) }; // Create the request object RequestSpotInstancesRequest spotRequest = new RequestSpotInstancesRequest() { SpotPrice = InstancePrice.ToString(), InstanceCount = InstanceCount, LaunchSpecification = launchSpecification }; // Request the instances try { var spotResponse = EC2client.RequestSpotInstances(spotRequest); // Check response for errors if (spotResponse.HttpStatusCode != HttpStatusCode.OK) { ErrorCode = Convert.ToInt32(spotResponse.HttpStatusCode); ErrorMessage = "Http Error [" + spotResponse.HttpStatusCode.ToString() + "]"; } else { foreach (SpotInstanceRequest request in spotResponse.SpotInstanceRequests) { RequestIds.Add(request.SpotInstanceRequestId); } } } catch (Exception ex) { ErrorCode = -1; ErrorMessage = ex.Message + "::" + ex.InnerException; } return(RequestIds); }
public IRequest Marshall(RequestSpotInstancesRequest requestSpotInstancesRequest) { IRequest request = new DefaultRequest(requestSpotInstancesRequest, "AmazonEC2"); request.Parameters.Add("Action", "RequestSpotInstances"); request.Parameters.Add("Version", "2014-02-01"); if (requestSpotInstancesRequest != null && requestSpotInstancesRequest.IsSetSpotPrice()) { request.Parameters.Add("SpotPrice", StringUtils.FromString(requestSpotInstancesRequest.SpotPrice)); } if (requestSpotInstancesRequest != null && requestSpotInstancesRequest.IsSetInstanceCount()) { request.Parameters.Add("InstanceCount", StringUtils.FromInt(requestSpotInstancesRequest.InstanceCount)); } if (requestSpotInstancesRequest != null && requestSpotInstancesRequest.IsSetType()) { request.Parameters.Add("Type", StringUtils.FromString(requestSpotInstancesRequest.Type)); } if (requestSpotInstancesRequest != null && requestSpotInstancesRequest.IsSetValidFrom()) { request.Parameters.Add("ValidFrom", StringUtils.FromDateTime(requestSpotInstancesRequest.ValidFrom)); } if (requestSpotInstancesRequest != null && requestSpotInstancesRequest.IsSetValidUntil()) { request.Parameters.Add("ValidUntil", StringUtils.FromDateTime(requestSpotInstancesRequest.ValidUntil)); } if (requestSpotInstancesRequest != null && requestSpotInstancesRequest.IsSetLaunchGroup()) { request.Parameters.Add("LaunchGroup", StringUtils.FromString(requestSpotInstancesRequest.LaunchGroup)); } if (requestSpotInstancesRequest != null && requestSpotInstancesRequest.IsSetAvailabilityZoneGroup()) { request.Parameters.Add("AvailabilityZoneGroup", StringUtils.FromString(requestSpotInstancesRequest.AvailabilityZoneGroup)); } if (requestSpotInstancesRequest != null) { LaunchSpecification launchSpecification = requestSpotInstancesRequest.LaunchSpecification; if (launchSpecification != null && launchSpecification.IsSetImageId()) { request.Parameters.Add("LaunchSpecification.ImageId", StringUtils.FromString(launchSpecification.ImageId)); } if (launchSpecification != null && launchSpecification.IsSetKeyName()) { request.Parameters.Add("LaunchSpecification.KeyName", StringUtils.FromString(launchSpecification.KeyName)); } if (launchSpecification != null) { List <GroupIdentifier> allSecurityGroupsList = launchSpecification.AllSecurityGroups; int allSecurityGroupsListIndex = 1; foreach (GroupIdentifier allSecurityGroupsListValue in allSecurityGroupsList) { if (allSecurityGroupsListValue != null && allSecurityGroupsListValue.IsSetGroupName()) { request.Parameters.Add("LaunchSpecification.GroupSet." + allSecurityGroupsListIndex + ".GroupName", StringUtils.FromString(allSecurityGroupsListValue.GroupName)); } if (allSecurityGroupsListValue != null && allSecurityGroupsListValue.IsSetGroupId()) { request.Parameters.Add("LaunchSpecification.GroupSet." + allSecurityGroupsListIndex + ".GroupId", StringUtils.FromString(allSecurityGroupsListValue.GroupId)); } allSecurityGroupsListIndex++; } } if (launchSpecification != null) { List <string> securityGroupsList = launchSpecification.SecurityGroups; int securityGroupsListIndex = 1; foreach (string securityGroupsListValue in securityGroupsList) { request.Parameters.Add("LaunchSpecification.SecurityGroup." + securityGroupsListIndex, StringUtils.FromString(securityGroupsListValue)); securityGroupsListIndex++; } } if (launchSpecification != null && launchSpecification.IsSetUserData()) { request.Parameters.Add("LaunchSpecification.UserData", StringUtils.FromString(launchSpecification.UserData)); } if (launchSpecification != null && launchSpecification.IsSetAddressingType()) { request.Parameters.Add("LaunchSpecification.AddressingType", StringUtils.FromString(launchSpecification.AddressingType)); } if (launchSpecification != null && launchSpecification.IsSetInstanceType()) { request.Parameters.Add("LaunchSpecification.InstanceType", StringUtils.FromString(launchSpecification.InstanceType)); } if (launchSpecification != null) { SpotPlacement placement = launchSpecification.Placement; if (placement != null && placement.IsSetAvailabilityZone()) { request.Parameters.Add("LaunchSpecification.Placement.AvailabilityZone", StringUtils.FromString(placement.AvailabilityZone)); } if (placement != null && placement.IsSetGroupName()) { request.Parameters.Add("LaunchSpecification.Placement.GroupName", StringUtils.FromString(placement.GroupName)); } } if (launchSpecification != null && launchSpecification.IsSetKernelId()) { request.Parameters.Add("LaunchSpecification.KernelId", StringUtils.FromString(launchSpecification.KernelId)); } if (launchSpecification != null && launchSpecification.IsSetRamdiskId()) { request.Parameters.Add("LaunchSpecification.RamdiskId", StringUtils.FromString(launchSpecification.RamdiskId)); } if (launchSpecification != null) { List <BlockDeviceMapping> blockDeviceMappingsList = launchSpecification.BlockDeviceMappings; int blockDeviceMappingsListIndex = 1; foreach (BlockDeviceMapping blockDeviceMappingsListValue in blockDeviceMappingsList) { if (blockDeviceMappingsListValue != null && blockDeviceMappingsListValue.IsSetVirtualName()) { request.Parameters.Add("LaunchSpecification.BlockDeviceMapping." + blockDeviceMappingsListIndex + ".VirtualName", StringUtils.FromString(blockDeviceMappingsListValue.VirtualName)); } if (blockDeviceMappingsListValue != null && blockDeviceMappingsListValue.IsSetDeviceName()) { request.Parameters.Add("LaunchSpecification.BlockDeviceMapping." + blockDeviceMappingsListIndex + ".DeviceName", StringUtils.FromString(blockDeviceMappingsListValue.DeviceName)); } if (blockDeviceMappingsListValue != null) { EbsBlockDevice ebs = blockDeviceMappingsListValue.Ebs; if (ebs != null && ebs.IsSetSnapshotId()) { request.Parameters.Add("LaunchSpecification.BlockDeviceMapping." + blockDeviceMappingsListIndex + ".Ebs.SnapshotId", StringUtils.FromString(ebs.SnapshotId)); } if (ebs != null && ebs.IsSetVolumeSize()) { request.Parameters.Add("LaunchSpecification.BlockDeviceMapping." + blockDeviceMappingsListIndex + ".Ebs.VolumeSize", StringUtils.FromInt(ebs.VolumeSize)); } if (ebs != null && ebs.IsSetDeleteOnTermination()) { request.Parameters.Add("LaunchSpecification.BlockDeviceMapping." + blockDeviceMappingsListIndex + ".Ebs.DeleteOnTermination", StringUtils.FromBool(ebs.DeleteOnTermination)); } if (ebs != null && ebs.IsSetVolumeType()) { request.Parameters.Add("LaunchSpecification.BlockDeviceMapping." + blockDeviceMappingsListIndex + ".Ebs.VolumeType", StringUtils.FromString(ebs.VolumeType)); } if (ebs != null && ebs.IsSetIops()) { request.Parameters.Add("LaunchSpecification.BlockDeviceMapping." + blockDeviceMappingsListIndex + ".Ebs.Iops", StringUtils.FromInt(ebs.Iops)); } } if (blockDeviceMappingsListValue != null && blockDeviceMappingsListValue.IsSetNoDevice()) { request.Parameters.Add("LaunchSpecification.BlockDeviceMapping." + blockDeviceMappingsListIndex + ".NoDevice", StringUtils.FromString(blockDeviceMappingsListValue.NoDevice)); } blockDeviceMappingsListIndex++; } } if (launchSpecification != null && launchSpecification.IsSetMonitoringEnabled()) { request.Parameters.Add("LaunchSpecification.Monitoring.Enabled", StringUtils.FromBool(launchSpecification.MonitoringEnabled)); } if (launchSpecification != null && launchSpecification.IsSetSubnetId()) { request.Parameters.Add("LaunchSpecification.SubnetId", StringUtils.FromString(launchSpecification.SubnetId)); } if (launchSpecification != null) { List <InstanceNetworkInterfaceSpecification> networkInterfacesList = launchSpecification.NetworkInterfaces; int networkInterfacesListIndex = 1; foreach (InstanceNetworkInterfaceSpecification networkInterfacesListValue in networkInterfacesList) { if (networkInterfacesListValue != null && networkInterfacesListValue.IsSetNetworkInterfaceId()) { request.Parameters.Add("LaunchSpecification.NetworkInterface." + networkInterfacesListIndex + ".NetworkInterfaceId", StringUtils.FromString(networkInterfacesListValue.NetworkInterfaceId)); } if (networkInterfacesListValue != null && networkInterfacesListValue.IsSetDeviceIndex()) { request.Parameters.Add("LaunchSpecification.NetworkInterface." + networkInterfacesListIndex + ".DeviceIndex", StringUtils.FromInt(networkInterfacesListValue.DeviceIndex)); } if (networkInterfacesListValue != null && networkInterfacesListValue.IsSetSubnetId()) { request.Parameters.Add("LaunchSpecification.NetworkInterface." + networkInterfacesListIndex + ".SubnetId", StringUtils.FromString(networkInterfacesListValue.SubnetId)); } if (networkInterfacesListValue != null && networkInterfacesListValue.IsSetDescription()) { request.Parameters.Add("LaunchSpecification.NetworkInterface." + networkInterfacesListIndex + ".Description", StringUtils.FromString(networkInterfacesListValue.Description)); } if (networkInterfacesListValue != null && networkInterfacesListValue.IsSetPrivateIpAddress()) { request.Parameters.Add("LaunchSpecification.NetworkInterface." + networkInterfacesListIndex + ".PrivateIpAddress", StringUtils.FromString(networkInterfacesListValue.PrivateIpAddress)); } if (networkInterfacesListValue != null) { List <string> groupsList = networkInterfacesListValue.Groups; int groupsListIndex = 1; foreach (string groupsListValue in groupsList) { request.Parameters.Add("LaunchSpecification.NetworkInterface." + networkInterfacesListIndex + ".SecurityGroupId." + groupsListIndex, StringUtils.FromString(groupsListValue)); groupsListIndex++; } } if (networkInterfacesListValue != null && networkInterfacesListValue.IsSetDeleteOnTermination()) { request.Parameters.Add("LaunchSpecification.NetworkInterface." + networkInterfacesListIndex + ".DeleteOnTermination", StringUtils.FromBool(networkInterfacesListValue.DeleteOnTermination)); } if (networkInterfacesListValue != null) { List <PrivateIpAddressSpecification> privateIpAddressesList = networkInterfacesListValue.PrivateIpAddresses; int privateIpAddressesListIndex = 1; foreach (PrivateIpAddressSpecification privateIpAddressesListValue in privateIpAddressesList) { if (privateIpAddressesListValue != null && privateIpAddressesListValue.IsSetPrivateIpAddress()) { request.Parameters.Add("LaunchSpecification.NetworkInterface." + networkInterfacesListIndex + ".PrivateIpAddresses." + privateIpAddressesListIndex + ".PrivateIpAddress", StringUtils.FromString(privateIpAddressesListValue.PrivateIpAddress)); } if (privateIpAddressesListValue != null && privateIpAddressesListValue.IsSetPrimary()) { request.Parameters.Add("LaunchSpecification.NetworkInterface." + networkInterfacesListIndex + ".PrivateIpAddresses." + privateIpAddressesListIndex + ".Primary", StringUtils.FromBool(privateIpAddressesListValue.Primary)); } privateIpAddressesListIndex++; } } if (networkInterfacesListValue != null && networkInterfacesListValue.IsSetSecondaryPrivateIpAddressCount()) { request.Parameters.Add("LaunchSpecification.NetworkInterface." + networkInterfacesListIndex + ".SecondaryPrivateIpAddressCount", StringUtils.FromInt(networkInterfacesListValue.SecondaryPrivateIpAddressCount)); } if (networkInterfacesListValue != null && networkInterfacesListValue.IsSetAssociatePublicIpAddress()) { request.Parameters.Add("LaunchSpecification.NetworkInterface." + networkInterfacesListIndex + ".AssociatePublicIpAddress", StringUtils.FromBool(networkInterfacesListValue.AssociatePublicIpAddress)); } networkInterfacesListIndex++; } } if (launchSpecification != null) { IamInstanceProfileSpecification iamInstanceProfile = launchSpecification.IamInstanceProfile; if (iamInstanceProfile != null && iamInstanceProfile.IsSetArn()) { request.Parameters.Add("LaunchSpecification.IamInstanceProfile.Arn", StringUtils.FromString(iamInstanceProfile.Arn)); } if (iamInstanceProfile != null && iamInstanceProfile.IsSetName()) { request.Parameters.Add("LaunchSpecification.IamInstanceProfile.Name", StringUtils.FromString(iamInstanceProfile.Name)); } } if (launchSpecification != null && launchSpecification.IsSetEbsOptimized()) { request.Parameters.Add("LaunchSpecification.EbsOptimized", StringUtils.FromBool(launchSpecification.EbsOptimized)); } } return(request); }
private RemotePlayContext SendBigBangMessages(Socket udpClient, Session session, RemotePlayContext remotePlayContext) { /******** Big Payload send ********/ // Generate random handshake key, for ECDH pubkey signature calculation byte[] handshakeKey = new byte[16]; new Random().NextBytes(handshakeKey); // Generate ECDH keypair var ecdhKeyPair = CryptoService.GenerateEcdhKeyPair(); // Get public key bytes var ownPublicKey = Session.GetPublicKeyBytesFromKeyPair(ecdhKeyPair); // Calculate ECDH pubkey signature var ecdhSignature = Session.CalculateHMAC(handshakeKey, ownPublicKey); int unixTimestamp = (int)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds; string timestampUnix = unixTimestamp.ToString(); string sessionKey = timestampUnix + CryptoService.GetUniqueKey(64); LaunchSpecification launchSpecs = LaunchSpecification.GetStandardSpecs("sessionId123", handshakeKey); byte[] launchSpecBuffer = Encoding.UTF8.GetBytes(launchSpecs.Serialize()); byte[] cryptoBuffer = new byte[launchSpecBuffer.Length]; cryptoBuffer = session.Encrypt(cryptoBuffer, 0); byte[] newLaunchSpec = new byte[launchSpecBuffer.Length]; for (int i = 0; i < launchSpecBuffer.Length; i++) { newLaunchSpec[i] = (byte)(launchSpecBuffer[i] ^ cryptoBuffer[i]); } TakionMessage takionBigPayloadMessage = new TakionMessage { Type = TakionMessage.PayloadType.Big, bigPayload = new BigPayload { clientVersion = 9, sessionKey = sessionKey, launchSpec = Convert.ToBase64String(newLaunchSpec), encryptedKey = new byte[] { 0, 0, 0, 0 }, ecdhPubKey = ownPublicKey, ecdhSig = ecdhSignature } }; MemoryStream bigPayloadStream = new MemoryStream(); Serializer.Serialize(bigPayloadStream, takionBigPayloadMessage); byte[] bigPayloadBuffer = ByteUtil.ConcatenateArrays(new byte[1], bigPayloadStream.ToArray()); // Padding byte + BigPayload ushort bigPayloadSize = (ushort)(12 + bigPayloadBuffer.Length); ControlMessage controlMessageBigPayload = new ControlMessage(0, remotePlayContext.ReceiverId, 0, 0, 0, 1, bigPayloadSize, remotePlayContext.FuncIncr, 0x10000); controlMessageBigPayload.UnParsedPayload = bigPayloadBuffer; byte[] initialControlMessage2Data = GetByteArrayForControlMessage(controlMessageBigPayload); OnPs4LogInfo?.Invoke(this, Environment.NewLine + "Sending big payload:"); OnPs4LogInfo?.Invoke(this, "ECDH pubkey: " + HexUtil.Hexlify(takionBigPayloadMessage.bigPayload.ecdhPubKey)); OnPs4LogInfo?.Invoke(this, "ECDH sig: " + HexUtil.Hexlify(takionBigPayloadMessage.bigPayload.ecdhSig)); OnPs4LogInfo?.Invoke(this, "Session key: " + takionBigPayloadMessage.bigPayload.sessionKey + Environment.NewLine); ControlResult bigPayloadResult = SendControlDataAndWaitForAnswer(udpClient, initialControlMessage2Data, 2, "Send BigPayload"); if (!bigPayloadResult.WasSuccessful) { return(null); } /******** Bang Payload receive ********/ ControlMessage answerPacket1 = bigPayloadResult.ControlMessages[0]; ControlMessage answerPacket2 = bigPayloadResult.ControlMessages[1]; if (answerPacket1.ProtoBuffFlag != 1 && answerPacket2.ProtoBuffFlag != 1) { return(null); } TakionMessage bangPayload = answerPacket1.ProtoBuffFlag == 1 ? Serializer.Deserialize <TakionMessage>(new MemoryStream(answerPacket1.UnParsedPayload)) : Serializer.Deserialize <TakionMessage>(new MemoryStream(answerPacket2.UnParsedPayload)); if (bangPayload.bangPayload == null) { return(null); } ControlMessage bangPayloadControl = answerPacket1.ProtoBuffFlag == 1 ? answerPacket1 : answerPacket2; OnPs4LogInfo?.Invoke(this, Environment.NewLine + "Received bang payload:"); OnPs4LogInfo?.Invoke(this, "ECDH pubkey: " + HexUtil.Hexlify(bangPayload.bangPayload.ecdhPubKey)); OnPs4LogInfo?.Invoke(this, "ECDH sig: " + HexUtil.Hexlify(bangPayload.bangPayload.ecdhSig)); OnPs4LogInfo?.Invoke(this, "Session key: " + bangPayload.bangPayload.sessionKey); /* Derive ECDH shared secret */ var foreignPubkeyParams = Session.ConvertPubkeyBytesToCipherParams(bangPayload.bangPayload.ecdhPubKey); remotePlayContext.SharedSecret = Session.GenerateSharedSecret(ecdhKeyPair.Private, foreignPubkeyParams); remotePlayContext.LocalGmacInfo = CryptoService.SetUpGmac(2, handshakeKey, remotePlayContext.SharedSecret); remotePlayContext.RemoteGmacInfo = CryptoService.SetUpGmac(3, handshakeKey, remotePlayContext.SharedSecret); OnPs4LogInfo?.Invoke(this, "HANDSHAKE KEY: " + HexUtil.Hexlify(handshakeKey)); OnPs4LogInfo?.Invoke(this, "SHARED SECRET: " + HexUtil.Hexlify(remotePlayContext.SharedSecret)); byte[] ackBangPayload = HexUtil.Unhexlify("00000000"); ushort ackBangPayloadSize = (ushort)(12 + ackBangPayload.Length); ControlMessage ackBangPayloadMessage = new ControlMessage(0, bangPayloadControl.FuncIncr, 0, 0, 3, 0, ackBangPayloadSize, bangPayloadControl.FuncIncr, 0x19000); ackBangPayloadMessage.UnParsedPayload = ackBangPayload; byte[] ackBangPayloadMessageData = GetByteArrayForControlMessage(ackBangPayloadMessage); remotePlayContext.LastSentMessage = ackBangPayloadMessageData; SendData(udpClient, ackBangPayloadMessageData); return(remotePlayContext); }
private void HandleControlMessage(byte[] payload, Session session) { if (payload[0] == 0) // Control Packet { byte[] message = payload; ControlMessage controlMessage = new ControlMessage(); using (MemoryStream memoryStream = new MemoryStream(message, 0, message.Length)) using (BinaryReader binaryWriter = new BinaryReader(memoryStream)) { controlMessage.Deserialize(binaryWriter); } if (controlMessage.ProtoBuffFlag == 1 && controlMessage.PLoadSize > 100) { TakionMessage takionMessage = ProtobufUtil.Deserialize <TakionMessage>(controlMessage.UnParsedPayload); if (takionMessage.bigPayload != null) { this.textBoxPcapLogOutput.Invoke(new MethodInvoker(() => AppendLogOutputToPcapLogTextBox("!!! Big payload session key: " + takionMessage.bigPayload.sessionKey))); this.textBoxPcapLogOutput.Invoke(new MethodInvoker(() => AppendLogOutputToPcapLogTextBox("!!! Big payload ecdh pub key in hex: " + HexUtil.Hexlify(takionMessage.bigPayload.ecdhPubKey)))); this.textBoxPcapLogOutput.Invoke(new MethodInvoker(() => AppendLogOutputToPcapLogTextBox("!!! Big payload ecdh sig in hex: " + HexUtil.Hexlify(takionMessage.bigPayload.ecdhSig)))); if (session != null) { byte[] launchSpecBuffer = Convert.FromBase64String(takionMessage.bigPayload.launchSpec); byte[] cryptoBuffer = new byte[launchSpecBuffer.Length]; cryptoBuffer = session.Encrypt(cryptoBuffer, 0); byte[] newLaunchSpec = new byte[launchSpecBuffer.Length]; for (int j = 0; j < launchSpecBuffer.Length; j++) { newLaunchSpec[j] = (byte)(launchSpecBuffer[j] ^ cryptoBuffer[j]); } string launchSpecs = Encoding.UTF8.GetString(newLaunchSpec); LaunchSpecification launchSpecJsonObject = LaunchSpecification.Deserialize(launchSpecs); byte[] handshakeKey = launchSpecJsonObject.HandshakeKey; if (handshakeKey != null) { this.textBoxPcapLogOutput.Invoke(new MethodInvoker(() => AppendLogOutputToPcapLogTextBox("!!! Big payload handshake key in launchSpec in hex: " + HexUtil.Hexlify(handshakeKey)))); var ecdhSignatureVerification = Session.CalculateHMAC(handshakeKey, takionMessage.bigPayload.ecdhPubKey); if (ecdhSignatureVerification.SequenceEqual(takionMessage.bigPayload.ecdhSig)) { this.textBoxPcapLogOutput.Invoke(new MethodInvoker(() => AppendLogOutputToPcapLogTextBox("ECDH Signature matches!"))); } else { this.textBoxPcapLogOutput.Invoke(new MethodInvoker(() => AppendLogOutputToPcapLogTextBox("!!!! ECDH Signature mismatch"))); } } this.textBoxPcapLogOutput.Invoke(new MethodInvoker(() => AppendLogOutputToPcapLogTextBox("!!! Big payload full launchSpec: " + Environment.NewLine + launchSpecJsonObject.Serialize() + Environment.NewLine))); } else { this.textBoxPcapLogOutput.Invoke(new MethodInvoker(() => AppendLogOutputToPcapLogTextBox(Environment.NewLine))); } } else if (takionMessage.bangPayload != null) { this.textBoxPcapLogOutput.Invoke(new MethodInvoker(() => AppendLogOutputToPcapLogTextBox("!!! Bang payload session key: " + takionMessage.bangPayload.sessionKey))); this.textBoxPcapLogOutput.Invoke(new MethodInvoker(() => AppendLogOutputToPcapLogTextBox("!!! Bang payload ecdh pub key in hex: " + HexUtil.Hexlify(takionMessage.bangPayload.ecdhPubKey)))); this.textBoxPcapLogOutput.Invoke(new MethodInvoker(() => AppendLogOutputToPcapLogTextBox("!!! Bang payload ecdh sig in hex: " + HexUtil.Hexlify(takionMessage.bangPayload.ecdhSig) + Environment.NewLine))); } } else { if (controlMessage.Crypto != 0) { this.textBoxPcapLogOutput.Invoke(new MethodInvoker(() => AppendLogOutputToPcapLogTextBox("!!! Control message with crypto value: " + HexUtil.Hexlify(ByteUtil.UIntToByteArray(controlMessage.Crypto))))); } } } }