<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Alexandru Puiu on Medium]]></title>
        <description><![CDATA[Stories by Alexandru Puiu on Medium]]></description>
        <link>https://medium.com/@alex.puiu?source=rss-d658781ec9e3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*V7WrlUTef_kVD8MPuHX26Q.jpeg</url>
            <title>Stories by Alexandru Puiu on Medium</title>
            <link>https://medium.com/@alex.puiu?source=rss-d658781ec9e3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 12:43:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alex.puiu/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Write a REST API in C# using Chat GPT]]></title>
            <link>https://medium.com/@alex.puiu/write-a-rest-api-in-c-using-chat-gpt-4517b8ac8097?source=rss-d658781ec9e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/4517b8ac8097</guid>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[ai-code]]></category>
            <category><![CDATA[ravendb]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <dc:creator><![CDATA[Alexandru Puiu]]></dc:creator>
            <pubDate>Thu, 08 Dec 2022 19:10:42 GMT</pubDate>
            <atom:updated>2022-12-08T19:10:42.985Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Robot writing code" src="https://cdn-images-1.medium.com/max/1024/1*7iHE0vRzc0W53T2w81kbQg.png" /></figure><p>Last night I decided to check out Chat GPT and see how far along it is, and I was blown away.</p><p>I’ve used GPT-3 based systems like RYTR for expanding ideas, marketing headlines, and played around with it for writing all sorts of content to see what it can do. But Chat GPT is the first model I can see myself really using in my day-to-day to write production code. Do I see it replacing me? Not really, but not because it can’t. I think the industry will adopt it, and the landscape will change in a way as significant to the industrial revolution.</p><p>So far I had it create a business plan, marketing plan, even wrote a poem, but the coding part is the one of interest here, so here’s what my conversation looked like:</p><h3><strong>Write integration api documentation</strong></h3><p>Sure, here’s a rough outline for integration API documentation:</p><p>Introduction: This section should provide an overview of the API, including its purpose, features, and requirements.</p><p>Authentication: This section should describe the authentication methods and requirements for accessing the API, such as API keys or OAuth tokens.</p><p>Endpoints: This section should list and describe the available API endpoints, including their URLs, methods (e.g. GET, POST), and parameters.</p><p>Request and response examples: This section should provide examples of API requests and responses, including the request format, parameters, and possible response codes and data.</p><p>Error handling: This section should describe the error codes and messages that may be returned by the API, and how to handle them in the client application.</p><p>Versioning: This section should describe how the API is versioned, and how to specify the desired API version in the request.</p><p>Deprecation: This section should describe the process for deprecating old API versions and transitioning to newer versions.</p><p>Contact information: This section should provide contact information for the API team, including support email or web form, and a link to the API’s terms of use and privacy policy.</p><p>Overall, the goal of the integration API documentation is to provide clear and detailed information about the API, so that developers can easily integrate it into their applications and use it to access the API’s features and data. The documentation should be well-organized and easy to understand, with clear examples and error handling information.</p><h3><strong>Write an API code sample in C#</strong></h3><p>Sure, here’s a sample API code in C#:</p><pre>using System;<br>using System.Net;<br>using System.Net.Http;<br>using System.Threading.Tasks;<br><br>namespace MyAPI<br>{<br>    public class MyAPI<br>    {<br>        private readonly HttpClient _httpClient;<br><br>        public MyAPI(string apiKey)<br>        {<br>            _httpClient = new HttpClient<br>            {<br>                BaseAddress = new Uri(&quot;https://myapi.com/v1/&quot;)<br>            };<br>            _httpClient.DefaultRequestHeaders.Add(&quot;Authorization&quot;, $&quot;Bearer {apiKey}&quot;);<br>        }<br><br>        public async Task&lt;string&gt; GetDataAsync(string id)<br>        {<br>            var response = await _httpClient.GetAsync($&quot;data/{id}&quot;);<br>            if (response.StatusCode == HttpStatusCode.OK)<br>            {<br>                return await response.Content.ReadAsStringAsync();<br>            }<br><br>            throw new Exception(&quot;Error retrieving data from API&quot;);<br>        }<br>    }<br>}</pre><h3><strong>Create a REST API in C# to manage customers</strong></h3><pre>using System.Collections.Generic;<br>using System.Linq;<br>using System.Web.Http;<br><br>namespace MyAPI<br>{<br>    public class CustomersController : ApiController<br>    {<br>        private static readonly List&lt;Customer&gt; Customers = new List&lt;Customer&gt;<br>        {<br>            new Customer { Id = 1, Name = &quot;John Doe&quot; },<br>            new Customer { Id = 2, Name = &quot;Jane Doe&quot; },<br>            new Customer { Id = 3, Name = &quot;Robert Smith&quot; }<br>        };<br><br>        public IEnumerable&lt;Customer&gt; Get()<br>        {<br>            return Customers;<br>        }<br><br>        public Customer Get(int id)<br>        {<br>            return Customers.SingleOrDefault(c =&gt; c.Id == id);<br>        }<br><br>        public void Post([FromBody] Customer customer)<br>        {<br>            Customers.Add(customer);<br>        }<br><br>        public void Put(int id, [FromBody] Customer customer)<br>        {<br>            var existingCustomer = Customers.SingleOrDefault(c =&gt; c.Id == id);<br>            if (existingCustomer != null)<br>            {<br>                existingCustomer.Name = customer.Name;<br>            }<br>        }<br><br>        public void Delete(int id)<br>        {<br>            Customers.RemoveAll(c =&gt; c.Id == id);<br>        }<br>    }<br><br>    public class Customer<br>    {<br>        public int Id { get; set; }<br><br>        public string Name { get; set; }<br>    }<br>}</pre><p>This code defines a CustomersController class that exposes a set of RESTful API endpoints for managing customers. It includes methods for GET, POST, PUT, and DELETE requests, which allow clients to retrieve a list of customers, retrieve a single customer by ID, create a new customer, update an existing customer, and delete a customer.</p><p>The Customers property is a static list of Customer objects that will be used to store the customer data. This list is initialized with some sample data, but in a real-world application, this data would typically be stored in a database.</p><p>The Get method is used to handle both the GET /customers and GET /customers/{id} requests. When called without an ID parameter, it returns the entire list of customers. When called with an ID parameter, it returns the customer with the specified ID, or null if no such customer exists.</p><p>The Post method is used to handle the POST /customers request, which creates a new customer based on the data in the request body. It adds the new customer to the `</p><h3><strong>Add the following properties to the customer: Birth date, address, phone numbers and email</strong></h3><pre>using System;<br>using System.Collections.Generic;<br>using System.Linq;<br>using System.Web.Http;<br><br>namespace MyAPI<br>{<br>    public class CustomersController : ApiController<br>    {<br>        private static readonly List&lt;Customer&gt; Customers = new List&lt;Customer&gt;<br>        {<br>            new Customer<br>            {<br>                Id = 1,<br>                Name = &quot;John Doe&quot;,<br>                BirthDate = new DateTime(1990, 1, 1),<br>                Address = &quot;123 Main St&quot;,<br>                PhoneNumbers = new List&lt;string&gt; { &quot;555-555-1212&quot;, &quot;555-555-1213&quot; },<br>                Email = &quot;johndoe@example.com&quot;<br>            },<br>            new Customer<br>            {<br>                Id = 2,<br>                Name = &quot;Jane Doe&quot;,<br>                BirthDate = new DateTime(1995, 5, 15),<br>                Address = &quot;456 Park Ave&quot;,<br>                PhoneNumbers = new List&lt;string&gt; { &quot;555-555-2121&quot;, &quot;555-555-2122&quot; },<br>                Email = &quot;janedoe@example.com&quot;<br>            },<br>            new Customer<br>            {<br>                Id = 3,<br>                Name = &quot;Robert Smith&quot;,<br>                BirthDate = new DateTime(1985, 8, 30),<br>                Address = &quot;789 Oak St&quot;,<br>                PhoneNumbers = new List&lt;string&gt; { &quot;555-555-3434&quot;, &quot;555-555-3435&quot; },<br>                Email = &quot;robertsmith@example.com&quot;<br>            }<br>        };<br><br>        public IEnumerable&lt;Customer&gt; Get()<br>        {<br>            return Customers;<br>        }<br><br>        public Customer Get(int id)<br>        {<br>            return Customers.SingleOrDefault(c =&gt; c.Id == id);<br>        }<br><br>        public void Post([FromBody] Customer customer)<br>        {<br>            Customers.Add(customer);<br>        }<br><br>        public void Put(int id, [FromBody] Customer customer)<br>        {<br>            var existingCustomer = Customers.SingleOrDefault(c =&gt; c.Id == id);<br>            if (existingCustomer != null)<br>            {<br>                existingCustomer.Name = customer.Name;<br>                existingCustomer.BirthDate = customer.BirthDate;<br>                existingCustomer.Address = customer.Address;<br>                existingCustomer.PhoneNumbers = customer.PhoneNumbers;<br>                existingCustomer.Email = customer.Email;<br>            }<br>        }<br><br>        public void Delete(int id)<br>        {<br>            Customers.RemoveAll(c =&gt; c.Id == id);<br>        }<br>    }<br><br>    public class Customer<br>    {<br>        public int Id { get; set; }<br>        public string Name { get; set; }<br>        public DateTime BirthDate { get; set; }<br>        public string Address { get; set; }<br>        public List&lt;string&gt; PhoneNumbers { get; set; }<br>        public string Email { get; set; }<br>    }<br>}</pre><h3><strong>Change Address to an object containing the properties Address, Address2, City, State, Zipcode</strong></h3><pre>using System;<br>using System.Collections.Generic;<br>using System.Linq;<br>using System.Web.Http;<br><br>namespace MyAPI<br>{<br>    public class CustomersController : ApiController<br>    {<br>        private static readonly List&lt;Customer&gt; Customers = new List&lt;Customer&gt;<br>        {<br>            new Customer<br>            {<br>                Id = 1,<br>                Name = &quot;John Doe&quot;,<br>                BirthDate = new DateTime(1990, 1, 1),<br>                Address = new Address<br>                {<br>                    Address1 = &quot;123 Main St&quot;,<br>                    Address2 = &quot;Apt 101&quot;,<br>                    City = &quot;New York&quot;,<br>                    State = &quot;NY&quot;,<br>                    ZipCode = &quot;10001&quot;<br>                },<br>                PhoneNumbers = new List&lt;string&gt; { &quot;555-555-1212&quot;, &quot;555-555-1213&quot; },<br>                Email = &quot;johndoe@example.com&quot;<br>            },<br>            new Customer<br>            {<br>                Id = 2,<br>                Name = &quot;Jane Doe&quot;,<br>                BirthDate = new DateTime(1995, 5, 15),<br>                Address = new Address<br>                {<br>                    Address1 = &quot;456 Park Ave&quot;,<br>                    Address2 = &quot;Suite 202&quot;,<br>                    City = &quot;Los Angeles&quot;,<br>                    State = &quot;CA&quot;,<br>                    ZipCode = &quot;90001&quot;<br>                },<br>                PhoneNumbers = new List&lt;string&gt; { &quot;555-555-2121&quot;, &quot;555-555-2122&quot; },<br>                Email = &quot;janedoe@example.com&quot;<br>            },<br>            new Customer<br>            {<br>                Id = 3,<br>                Name = &quot;Robert Smith&quot;,<br>                BirthDate = new DateTime(1985, 8, 30),<br>                Address = new Address<br>                {<br>                    Address1 = &quot;789 Oak St&quot;,<br>                    Address2 = &quot;&quot;,<br>                    City = &quot;Chicago&quot;,<br>                    State = &quot;IL&quot;,<br>                    ZipCode = &quot;60007&quot;<br>                },<br>                PhoneNumbers = new List&lt;string&gt; { &quot;555-555-3434&quot;, &quot;555-555-3435&quot; },<br>                Email = &quot;robertsmith@example.com&quot;<br>            }<br>        };<br><br>        public IEnumerable&lt;Customer&gt; Get()<br>        {<br>            return Customers;<br>        }<br><br>        public Customer Get(int id)<br>        {<br>            return Customers.SingleOrDefault(c =&gt; c.Id == id);<br>        }<br><br>        public void Post([FromBody] Customer customer)<br>        {<br>            Customers.Add(customer);<br>        }<br><br>        public void Put(int id, [FromBody] Customer customer)<br>        {<br>            var existingCustomer = Customers.SingleOrDefault(c =&gt; c.Id == id);<br>            if (existingCustomer != null)<br>            {<br>                existingCustomer.Name = customer.Name;<br>                existingCustomer.BirthDate = customer.BirthDate;<br>                existingCustomer.Address = customer.Address;<br>                existingCustomer.PhoneNumbers = customer.PhoneNumbers;<br>                existingCustomer.Email = customer.Email;<br>            }<br>        }<br><br>        public void Delete(int id)<br>        {<br>            Customers.RemoveAll(c =&gt; c.Id == id);<br>        }<br>    }<br><br>    public class Customer<br>    {<br>        public int Id { get; set; }<br>        public string Name { get; set; }<br>        public DateTime BirthDate { get; set; }<br>        public Address Address { get; set; }<br>        public List&lt;string&gt; PhoneNumbers { get; set; }<br>        public string Email { get; set; }<br>    }<br><br>    public class Address<br>    {<br>        public string Address1 { get; set; }<br>        public string Address2 { get; set; }<br>        public string City { get; set; }<br>        public string State { get; set; }<br>        public string ZipCode { get; set; }<br>    }<br>}</pre><h3><strong>Add Country to the address, but make it an enum of all countries</strong></h3><pre>using System;<br>using System.Collections.Generic;<br>using System.Linq;<br>using System.Web.Http;<br><br>namespace MyAPI<br>{<br>    public class CustomersController : ApiController<br>    {<br>        private static readonly List&lt;Customer&gt; Customers = new List&lt;Customer&gt;<br>        {<br>            new Customer<br>            {<br>                Id = 1,<br>                Name = &quot;John Doe&quot;,<br>                BirthDate = new DateTime(1990, 1, 1),<br>                Address = new Address<br>                {<br>                    Address1 = &quot;123 Main St&quot;,<br>                    Address2 = &quot;Apt 101&quot;,<br>                    City = &quot;New York&quot;,<br>                    State = &quot;NY&quot;,<br>                    ZipCode = &quot;10001&quot;,<br>                    Country = Country.UnitedStates<br>                },<br>                PhoneNumbers = new List&lt;string&gt; { &quot;555-555-1212&quot;, &quot;555-555-1213&quot; },<br>                Email = &quot;johndoe@example.com&quot;<br>            },<br>            new Customer<br>            {<br>                Id = 2,<br>                Name = &quot;Jane Doe&quot;,<br>                BirthDate = new DateTime(1995, 5, 15),<br>                Address = new Address<br>                {<br>                    Address1 = &quot;456 Park Ave&quot;,<br>                    Address2 = &quot;Suite 202&quot;,<br>                    City = &quot;Los Angeles&quot;,<br>                    State = &quot;CA&quot;,<br>                    ZipCode = &quot;90001&quot;,<br>                    Country = Country.UnitedStates<br>                },<br>                PhoneNumbers = new List&lt;string&gt; { &quot;555-555-2121&quot;, &quot;555-555-2122&quot; },<br>                Email = &quot;janedoe@example.com&quot;<br>            }<br>        }<br><br>        public Customer Get(int id)<br>        {<br>            return Customers.SingleOrDefault(c =&gt; c.Id == id);<br>        }<br><br>        public void Post([FromBody] Customer customer)<br>        {<br>            Customers.Add(customer);<br>        }<br><br>        public void Put(int id, [FromBody] Customer customer)<br>        {<br>            var existingCustomer = Customers.SingleOrDefault(c =&gt; c.Id == id);<br>            if (existingCustomer != null)<br>            {<br>                existingCustomer.Name = customer.Name;<br>                existingCustomer.BirthDate = customer.BirthDate;<br>                existingCustomer.Address = customer.Address;<br>                existingCustomer.PhoneNumbers = customer.PhoneNumbers;<br>                existingCustomer.Email = customer.Email;<br>            }<br>        }<br><br>        public void Delete(int id)<br>        {<br>            Customers.RemoveAll(c =&gt; c.Id == id);<br>        }<br>    }<br><br>    public class Customer<br>    {<br>        public int Id { get; set; }<br>        public string Name { get; set; }<br>        public DateTime BirthDate { get; set; }<br>        public Address Address { get; set; }<br>        public List&lt;string&gt; PhoneNumbers { get; set; }<br>        public string Email { get; set; }<br>    }<br><br>    public class Address<br>    {<br>        public string Address1 { get; set; }<br>        public string Address2 { get; set; }<br>        public string City { get; set; }<br>        public string State { get; set; }<br>        public string ZipCode { get; set; }<br>        public Country Country { get; set; }<br>    }<br><br>    public enum Country<br>    {<br>        UnitedStates,<br>        Canada,<br>        Mexico,<br>        Brazil,<br>        Argentina,<br>        Colombia,<br>        Peru,<br>        Chile<br><br>        // Additional countries omitted for brevity<br>    }<br>}</pre><h3><strong>Add validation to make the country, name and email required</strong></h3><pre>using System;<br>using System.Collections.Generic;<br>using System.ComponentModel.DataAnnotations;<br>using System.Linq;<br>using System.Web.Http;<br><br>namespace MyAPI<br>{<br>    public class CustomersController : ApiController<br>    {<br>        private static readonly List&lt;Customer&gt; Customers = new List&lt;Customer&gt;<br>        {<br>            new Customer<br>            {<br>                Id = 1,<br>                Name = &quot;John Doe&quot;,<br>                BirthDate = new DateTime(1990, 1, 1),<br>                Address = new Address<br>                {<br>                    Address1 = &quot;123 Main St&quot;,<br>                    Address2 = &quot;Apt 101&quot;,<br>                    City = &quot;New York&quot;,<br>                    State = &quot;NY&quot;,<br>                    ZipCode = &quot;10001&quot;,<br>                    Country = Country.UnitedStates<br>                },<br>                PhoneNumbers = new List&lt;string&gt; { &quot;555-555-1212&quot;, &quot;555-555-1213&quot; },<br>                Email = &quot;johndoe@example.com&quot;<br>            },<br>            new Customer<br>            {<br>                Id = 2,<br>                Name = &quot;Jane Doe&quot;,<br>                BirthDate = new DateTime(1995, 5, 15),<br>                Address = new Address<br>                {<br>                    Address1 = &quot;456 Park Ave&quot;,<br>                    Address2 = &quot;Suite 202&quot;,<br>                    City = &quot;Los Angeles&quot;,<br>                    State = &quot;CA&quot;,<br>                    ZipCode = &quot;90001&quot;,<br>                    Country = Country.UnitedStates<br>                },<br>                PhoneNumbers = new List&lt;string&gt; { &quot;555-555-2121&quot;, &quot;555-555-2122&quot; },<br>                Email = &quot;janedoe@example.com&quot;<br>            },<br>            new Customer<br>            {<br>                Id = 3,<br>                Name = &quot;Robert Smith&quot;,<br>                BirthDate = new DateTime(1985, 8, 30),<br>                Address = new Address<br>                {<br>                    Address1 = &quot;789 Oak St&quot;,<br>                    Address2 = &quot;&quot;,<br>                    City = &quot;Chicago&quot;,<br>                    State = &quot;IL&quot;,<br>                    ZipCode = &quot;60007&quot;,<br>                    Country = Country.UnitedStates<br>                },<br>                PhoneNumbers = new List&lt;string&gt; { &quot;555-555-3434&quot;, &quot;555-555-3435&quot; },<br>                Email = &quot;robertsmith@example.com&quot;<br>            }<br>        }<br><br>        public void Post([FromBody] Customer customer)<br>        {<br>            if (ModelState.IsValid)<br>            {<br>                Customers.Add(customer);<br>            }<br>        }<br><br>        public void Put(int id, [FromBody] Customer customer)<br>        {<br>            if (ModelState.IsValid)<br>            {<br>                var existingCustomer = Customers.SingleOrDefault(c =&gt; c.Id == id);<br>                if (existingCustomer != null)<br>                {<br>                    existingCustomer.Name = customer.Name;<br>                    existingCustomer.BirthDate = customer.BirthDate;<br>                    existingCustomer.Address = customer.Address;<br>                    existingCustomer.PhoneNumbers = customer.PhoneNumbers;<br>                    existingCustomer.Email = customer.Email;<br>                }<br>            }<br>        }<br><br>        public void Delete(int id)<br>        {<br>            Customers.RemoveAll(c =&gt; c.Id == id);<br>        }<br>    }<br><br>    public class Customer<br>    {<br>        public int Id { get; set; }<br>        [Required]<br>        public string Name { get; set; }<br>        public DateTime BirthDate { get; set; }<br>        [Required]<br>        public Address Address { get; set; }<br>        public List&lt;string&gt; PhoneNumbers { get; set; }<br>        [Required]<br>        [EmailAddress]<br>        public string Email { get; set; }<br>    }<br><br>    public class Address<br>    {<br>        public string Address1 { get; set; }<br>        public string Address2 { get; set; }<br>        public string City { get; set; }<br>        public string State { get; set; }<br>        public string ZipCode { get; set; }<br>        [Required]<br>        public Country Country { get; set; }<br>    }<br><br>    public enum Country<br>    {<br>        UnitedStates,<br>        Canada,<br>        Mexico,<br>        Brazil,<br>        Argentina,<br>        Colombia,<br>        Peru,<br>        Chile<br>        // Additional countries omitted for brevity<br>    }<br>}</pre><p>In this updated version of the code, the Customer and Address classes include several [Required] attributes, which indicate that the Name, Address, and Email properties are required and must be non-null when creating or updating a customer. Additionally, the Email property includes the [EmailAddress] attribute, which indicates that it must be a valid email address.</p><p>The Post and Put methods check the ModelState to ensure that all required properties are present and valid before adding or updating a customer. If any of the required properties are missing or invalid, the</p><h3><strong>Write a customers REST API in C# where the customer has the properties Id, Name, Birth Date, Phone numbers, email, an Address object with Address1, address2, city, state, zipcode and a country enum, and add validation to the api</strong></h3><pre>using System;<br>using System.Collections.Generic;<br>using System.ComponentModel.DataAnnotations;<br><br>namespace CustomerAPI<br>{<br>    public class Customer<br>    {<br>        public int Id { get; set; }<br><br>        [Required]<br>        public string Name { get; set; }<br><br>        [Required]<br>        public DateTime BirthDate { get; set; }<br><br>        [Required]<br>        public List&lt;string&gt; PhoneNumbers { get; set; }<br><br>        [Required]<br>        [EmailAddress]<br>        public string Email { get; set; }<br><br>        [Required]<br>        public Address Address { get; set; }<br>    }<br><br>    public class Address<br>    {<br>        [Required]<br>        public string Address1 { get; set; }<br><br>        public string Address2 { get; set; }<br><br>        [Required]<br>        public string City { get; set; }<br><br>        [Required]<br>        public string State { get; set; }<br><br>        [Required]<br>        [RegularExpression(@&quot;^\d{5}(?:[-\s]\d{4})?$&quot;)]<br>        public string ZipCode { get; set; }<br><br>        [Required]<br>        public Country Country { get; set; }<br>    }<br><br>    public enum Country<br>    {<br>        USA,<br>        Canada,<br>        Mexico,<br>        Other<br>    }<br>}</pre><p>This example uses the [Required] attribute to mark properties that must have a value, the [EmailAddress] attribute to validate that a string is a valid email address, and the [RegularExpression] attribute to validate that a string is a valid zip code.</p><p>You can add additional validation logic as needed in the setters of the properties or in a separate method. For example, you could add a method to validate the customer’s age and ensure that they are over 18 years old.</p><h3><strong>Write the REST Controller for managing the customer resource and save it in RavenDB</strong></h3><pre>using System.Linq;<br>using System.Web.Http;<br>using CustomerAPI.Models;<br>using Raven.Client.Documents;<br><br>namespace CustomerAPI.Controllers<br>{<br>    public class CustomerController : ApiController<br>    {<br>        private readonly IDocumentStore store;<br><br>        public CustomerController()<br>        {<br>            store = new DocumentStore<br>            {<br>                Urls = new[] { &quot;http://localhost:8080&quot; },<br>                Database = &quot;Customers&quot;<br>            };<br><br>            store.Initialize();<br>        }<br><br>        // GET api/customer<br>        public IEnumerable&lt;Customer&gt; Get()<br>        {<br>            using (var session = store.OpenSession())<br>            {<br>                return session.Query&lt;Customer&gt;().ToList();<br>            }<br>        }<br><br>        // GET api/customer/5<br>        public Customer Get(int id)<br>        {<br>            using (var session = store.OpenSession())<br>            {<br>                return session.Load&lt;Customer&gt;(id);<br>            }<br>        }<br><br>        // POST api/customer<br>        public void Post([FromBody]Customer customer)<br>        {<br>            using (var session = store.OpenSession())<br>            {<br>                session.Store(customer);<br>                session.SaveChanges();<br>            }<br>        }<br><br>        // PUT api/customer/5<br>        public void Put(int id, [FromBody]Customer customer)<br>        {<br>            using (var session = store.OpenSession())<br>            {<br>                var existingCustomer = session.Load&lt;Customer&gt;(id);<br>                existingCustomer.Name = customer.Name;<br>                existingCustomer.BirthDate = customer.BirthDate;<br>                existingCustomer.PhoneNumbers = customer.PhoneNumbers;<br>                existingCustomer.Email = customer.Email;<br>                existingCustomer.Address = customer.Address;<br><br>                session.SaveChanges();<br>            }<br>        }<br><br>        // DELETE api/customer/5<br>        public void Delete(int id)<br>        {<br>            using (var session = store.OpenSession())<br>            {<br>                var customer = session.Load&lt;Customer&gt;(id);<br>                session.Delete(customer);<br>                session.SaveChanges();<br>            }<br>        }<br>    }<br>}</pre><p>This controller defines the following endpoints for managing customer resources:</p><pre>GET api/customer: Returns a list of all customers.<br>GET api/customer/{id}: Returns the customer with the specified ID.<br>POST api/customer: Creates a new customer. The customer data should be provided in the request body.<br>PUT api/customer/{id}: Updates the customer with the specified ID. The updated customer data should be provided in the request body.<br>DELETE api/customer/{id}: Deletes the customer with the specified ID.</pre><p>This example uses the RavenDB document store to save and retrieve customer data. The store is initialized with the URL of the RavenDB server and the name of the database to use. The controller’s actions then use the store to open a session and perform the requested operations on the customer data.</p><p>Note that this is just one possible implementation of a REST controller for managing customer resources, and there are many other ways to implement such a controller depending on your specific requirements and preferences.</p><h3><strong>Add data validation</strong></h3><p>To validate the model, you can use the Validator.TryValidateObject method in the controller’s actions before saving or updating the customer data. For example:</p><pre>// POST api/customer<br>public void Post([FromBody]Customer customer)<br>{<br>    var validationContext = new ValidationContext(customer);<br>    var validationResults = new List&lt;ValidationResult&gt;();<br><br>    if (!Validator.TryValidateObject(customer, validationContext, validationResults))<br>    {<br>        // Handle validation errors<br>    }<br>    else<br>    {<br>        using (var session = store.OpenSession())<br>        {<br>            session.Store(customer);<br>            session.SaveChanges();<br>        }<br>    }<br>}</pre><p>This example uses the Validator.TryValidateObject method to validate the customer model before saving it to the database. If the model is not valid, the method returns false and the validationResults list contains the validation errors. You can then handle the validation errors as needed, for example by returning an appropriate HTTP response to the client.</p><p>Note that this is just one possible approach to adding data validation to the customer REST API.</p><h3><strong>Make it async</strong></h3><p>To make the customer REST API asynchronous, you can use the async and await keywords to mark methods that contain asynchronous operations, and the Task class to represent the asynchronous operation.</p><p>Here is an example of how you could modify the customer controller to make it asynchronous:</p><pre>using System.Linq;<br>using System.Threading.Tasks;<br>using System.Web.Http;<br>using CustomerAPI.Models;<br>using Raven.Client.Documents;<br><br>namespace CustomerAPI.Controllers<br>{<br>    public class CustomerController : ApiController<br>    {<br>        private readonly IDocumentStore store;<br><br>        public CustomerController()<br>        {<br>            store = new DocumentStore<br>            {<br>                Urls = new[] { &quot;http://localhost:8080&quot; },<br>                Database = &quot;Customers&quot;<br>            };<br><br>            store.Initialize();<br>        }<br><br>        // GET api/customer<br>        public async Task&lt;IEnumerable&lt;Customer&gt;&gt; Get()<br>        {<br>            using (var session = store.OpenAsyncSession())<br>            {<br>                return await session.Query&lt;Customer&gt;().ToListAsync();<br>            }<br>        }<br><br>        // GET api/customer/5<br>        public async Task&lt;Customer&gt; Get(int id)<br>        {<br>            using (var session = store.OpenAsyncSession())<br>            {<br>                return await session.LoadAsync&lt;Customer&gt;(id);<br>            }<br>        }<br><br>        // POST api/customer<br>        public async Task Post([FromBody]Customer customer)<br>        {<br>            var validationContext = new ValidationContext(customer);<br>            var validationResults = new List&lt;ValidationResult&gt;();<br><br>            if (!Validator.TryValidateObject(customer, validationContext, validationResults))<br>            {<br>                // Handle validation errors<br>            }<br>            else<br>            {<br>                using (var session = store.OpenAsyncSession())<br>                {<br>                    await session.StoreAsync(customer);<br>                    await session.SaveChangesAsync();<br>                }<br>            }<br>        }<br><br>        // PUT api/customer/5<br>        public async Task Put(int id, [FromBody]Customer customer)<br>        {<br>            var validationContext = new ValidationContext(customer);<br>            var validationResults = new List&lt;ValidationResult&gt;();<br><br>            if (!Validator.TryValidateObject(customer, validationContext, validationResults))<br>            {<br>                // Handle validation errors<br>            }<br>            else<br>            {<br>                using (var session = store.OpenAsyncSession())<br>                {<br>                    var existingCustomer = await session.LoadAsync&lt;Customer&gt;(id);<br>                    existingCustomer.Name = customer.Name;<br>                    existingCustomer.BirthDate = customer.BirthDate;<br>                    existingCustomer.PhoneNumbers = customer.PhoneNumbers;<br>                    existingCustomer.Email = customer.Email;<br>                    existingCustomer.Address = customer.Address;<br><br>                    await session.SaveChangesAsync();<br>                }<br>            }<br>        }<br><br>        // DELETE api/customer/5<br>        public async Task Delete(int id)<br>        {<br>            using (var session = store.OpenAsyncSession())<br>            {<br>                var customer = await session.LoadAsync&lt;Customer&gt;(id);<br>                session.Delete(customer);<br>                await session.SaveChangesAsync();<br>            }<br>        }<br>    }<br>}</pre><p>This example uses the async and await keywords</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4517b8ac8097" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Protect Against Enumeration Attacks in C# in 2022]]></title>
            <link>https://medium.com/@alex.puiu/tips-for-defending-against-enumeration-attacks-in-c-fbfab54827b?source=rss-d658781ec9e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/fbfab54827b</guid>
            <category><![CDATA[vulnerability-management]]></category>
            <category><![CDATA[brute-force]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[enumeration-attack]]></category>
            <dc:creator><![CDATA[Alexandru Puiu]]></dc:creator>
            <pubDate>Sun, 13 Mar 2022 00:00:00 GMT</pubDate>
            <atom:updated>2022-03-25T12:24:05.592Z</atom:updated>
            <content:encoded><![CDATA[<p>Enumeration Attacks are a type of attack in which the attacker tries to guess or validate a data set with the goal of extracting more information than they had to start out. For example, finding out if a user is a member of the site by trying to log in with millions of email addresses and checking if the page responds differently to an account existing but with a bad password vs not existing in the system.</p><h3>How an Enumeration Attack Works</h3><p>Enumeration is a type of cyber attack that involves using trial and error to find valid usernames or passwords, typically by trying many different combinations.</p><p>Enumeration attacks are often used in brute force attacks. The attacker uses a program to automatically try different passwords until they find the right one. The more guesses an attacker can make, the more likely they are to succeed at their goal.</p><h3>How to Prevent and Mitigate an Enumeration Attack In C#</h3><p>The first step in defending against enumeration attacks is making it infeasible to extract the data they’re after by limiting the number of attempts they can make, and monitoring user activity closely so you know when someone might be trying to break. This could be a limit on the number of attempts per account for login, or from a given IP address. Google Captcha and Cloudflare bot fighting mode can assist in preventing automated attempts from being made.</p><p>We’ll use a simple request throttling mechanism, along with an artificial delay to slow down the number of attempts an attacker can make:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/edfe967c1d777bc045d9d60fb0ee846f/href">https://medium.com/media/edfe967c1d777bc045d9d60fb0ee846f/href</a></iframe><p>Next, we’ll try to add the user’s IP Address to the list of running requests. Because it’s a Concurrent Dictionary, if they’re already running a request, then the add will fail, and we’ll just wait 3 seconds before trying again</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a7a80ab7d5f5dd79240db9fa6a1f8eaa/href">https://medium.com/media/a7a80ab7d5f5dd79240db9fa6a1f8eaa/href</a></iframe><p>Next, we’ll wait 3 seconds regardless of the previous one, which covers the case of the user making the first request</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/10df0fb28e6a107925cc98ffd1301a80/href">https://medium.com/media/10df0fb28e6a107925cc98ffd1301a80/href</a></iframe><p>We’ll want to do the above in a try/catch block, and then remove the user’s IP address from the list in the finally block. Otherwise, the user could be stuck not being able to make more requests.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ca43f7a8c95f7a074247d53c0e9c98a5/href">https://medium.com/media/ca43f7a8c95f7a074247d53c0e9c98a5/href</a></iframe><p>Then finally we’ll continue with our business logic.</p><p>Full code</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e840b59db13414c5c5481a7802c4f238/href">https://medium.com/media/e840b59db13414c5c5481a7802c4f238/href</a></iframe><p><em>Originally published at </em><a href="https://scatteredcode.net/tips-for-defending-against-enumeration-attacks-in-c/"><em>https://scatteredcode.net</em></a><em> on March 13, 2022.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fbfab54827b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Observability using Elasticsearch and Neo4j]]></title>
            <link>https://medium.com/@alex.puiu/observability-using-elasticsearch-and-neo4j-292354fc9e88?source=rss-d658781ec9e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/292354fc9e88</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[knowledge-graph]]></category>
            <category><![CDATA[elasticsearch]]></category>
            <category><![CDATA[neo4j]]></category>
            <category><![CDATA[insights]]></category>
            <dc:creator><![CDATA[Alexandru Puiu]]></dc:creator>
            <pubDate>Sun, 24 May 2020 18:50:21 GMT</pubDate>
            <atom:updated>2020-05-24T18:50:21.542Z</atom:updated>
            <cc:license>https://creativecommons.org/publicdomain/mark/1.0/</cc:license>
            <content:encoded><![CDATA[<p>Elasticsearch continues to add features at an astonishing rate, and people find really creative ways to use them and enhance it even more. What Neo4j can do is just way too cool to pass on. So we’ll look at how to ingest data with elasticsearch and analyze the data with neo4j. Combining the two helps us achieve some really powerful solutions.</p><p>I originally was intrigued by elasticsearch for log aggregation and its capability to instantly aggregate and search over millions of records. We could ship logs from all sorts of data sources like application logs, web server logs (Nginx, IIS). Then we can filter through those logs in Kibana’s Discover, choose the columns we wanted to see for particular use-cases and create saved searches. This immediately made it useful to us, the engineering team. We then use query-based filtering to add restrictions on documents people should access, and with field-level security, we can control which fields they even see inside each document. All of a sudden we have the ability to give our level 1 support real-time visibility into customer issues, without overloading them. On top of this, we add Windows event logs and Syslogs and create some alerts.</p><p>We start sending system metrics like memory and CPU usage, and it becomes useful to the infrastructure team for capacity planning. This leads to teams sharing indices across products and correlating logs across several microservices used by a customer during a session. We then start having dashboards optimized for each team, with everyone looking at this emergent Systems Engineering project with everyone building upon everyone else’s data, and everyone working with the same data, but without any restrictions on how they can interact with it.</p><h3>Ingesting Data from Other Sources</h3><p>We are of course not limited in any way as to what type of data we can ingest. Adding firewall logs and maybe some NetFlow data can add value. Capturing data from honeypots centrally allows us to catch threats in real-time. We can of use metricbeat to connect into our Kafka and Redis clusters and capture statistics and tag the data with the location of the data center or part of the business it serves.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lmj0keUbDPIQlx24KGAcdw.png" /></figure><p><a href="https://www.elastic.co/guide/en/beats/metricbeat/current/metricbeat-modules.html">Modules | Metricbeat Reference [7.12] | Elastic</a></p><p>And we can use filebeat to get logs from all our 3rd party dependencies like MySQL, or Suricata IDS/IPS, and even about our cloud infrastructure with hooks into GCP, AWS, and Azure.</p><p><a href="https://www.elastic.co/guide/en/beats/filebeat/current/filebeat-modules.html">Modules | Filebeat Reference [7.11] | Elastic</a></p><h3>Expanding Elasticsearch to more Domains</h3><p>With the merging of Elastic and Endgame, we start to ship data from every endpoint in our network and create an antivirus system that can really take advantage of the full picture of what’s happening in your network.</p><p>Adding Application Performance Monitoring into each application starts to understand what’s happening inside the normal flow of each one of your applications, and what normal looks like. This leads to a level of observability of our entire infrastructure, globally, and incredibly granular of absolutely incredible value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r1pIjCGErtjANqqjBMnSxw.jpeg" /></figure><p>On top of all this, we add Machine Learning, the trained unattended anomaly detection kind, and we really have the system itself understand what normal CPU across each VM looks like; what normal network traffic and normal DNS patterns look like. We automatically get notifications when something out of the ordinary happens, and we can effortlessly track it down to the root cause. Combining anomalous alerts across multiple different types of data models lets you really get a clear picture of where the problem really is.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NLQzfNT2LPN6M0bD9bjGHg.jpeg" /></figure><p><a href="https://scatteredcode.net/monitoring-dns-lookups-against-your-dns-server-using-elasticsearch-logstash-and-kibana/">Monitoring DNS Lookups against your DNS Server using Elasticsearch</a></p><h3>Globally Scalable</h3><p>One of the things Elasticsearch has done incredibly well from the get-go was its ability to scale horizontally. Indices can be sharded across many servers and replicated in a way that creates both safety and speed. Having a cluster of 200 elasticsearch nodes isn’t necessarily for everyone, but companies that need that can just set that up and if they do it properly, it works. Companies have gone even larger, since the early days of Elasticsearch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*32XMfFUDJSf8vP4GsGLuRA.png" /></figure><p><a href="https://underthehood.meltwater.com/blog/2018/02/06/running-a-400+-node-es-cluster/">Running a 400+ Node Elasticsearch Cluster</a></p><h3>Ingesting and Enriching Data</h3><p>A scalable ingesting pipeline might have Logstash servers distributed throughout each subnet in our global network, handling data transformations and enrichment. Any IP addresses can be enriched with GeoIP information. Dates can be standardized regardless of what format they come in as. Properties can be renamed to keep consistency across applications. And a user-agent string can be turned into detailed information about the user’s browser version and operating system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*gxeB6J-phzxNIK4oNGOlgw.png" /></figure><h3>Realizing Value</h3><p>All this data can seem overwhelming, but it all has value to someone. And having it all in the same place means that everyone is seeing the same thing. If contradictions arise, you have all the data needed to create another visualization that answers the confusion. But when we have machine learning, and the system finds patterns, it starts to get interesting when Elastic brings in Forecasting. This means more than just relying on current data, we have data now that can tell us that we should pre-order some servers for next month because we’re outgrowing our resources. Or we can add financial data, and be alerted that a customer’s spending has all of a sudden increased and we need to pay attention.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_FA9Du4MQEfM4o9vR_K5Tg.png" /></figure><h3>Let’s Get Creative</h3><p>So far we’ve been just in the world of Elastic, but the integration part goes both ways, and any data you put in, can be made available to any other pipelines you need; and then data from those can be ingested back.</p><p>We have all this data that includes IP addresses of VMs, and application data that tells us when each user is likely to log onto a system. Adding to that data about which VM lives on which host, and which ethernet cable is plugged into which switch and router, and other infrastructure data we collect, really starts to make it possible to answer some really interesting questions.</p><p>Let’s find the most depended-upon component in our infrastructure</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/87b32ceb7aebc450eeb23318ac92d007/href">https://medium.com/media/87b32ceb7aebc450eeb23318ac92d007/href</a></iframe><p>Or maybe map out and analyze CVEs</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G0GYAydwEgnw-JHkPDUrAg.png" /></figure><p>Taking it a few steps forward, we can ask: Give me a list of email addresses of users which are likely to log on between 10–11 PM ET on Tuesday and use an application which lives on a VM which sits on a host, who’s traffic passes through Router NY2 and doesn’t have a redundant route between the user and the application. Because I want to email just those users that I’ll be doing maintenance on that router. This is actually a pretty simple graph problem, and in Neo4j / Cypher [query language] it might look something like this</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0aaa9c8274c964371562cacf6656849d/href">https://medium.com/media/0aaa9c8274c964371562cacf6656849d/href</a></iframe><ul><li><a href="https://neo4j.com/business-edge/managing-network-operations-with-graphs/">Managing Network Operations with Graphs - Neo4j Graph Database Platform</a></li><li><a href="https://neo4j.com/docs/cypher-manual/current/functions/temporal/datetime/">4.9.3. DateTime: datetime() - 4.9. Temporal functions - instant types</a></li><li><a href="https://neo4j.com/graphgist/information-flow-through-a-network">Neo4j GraphGists</a></li></ul><p>The following article has a lot more dependency chain analysis examples:</p><p><a href="https://neo4j.com/graphgist/network-dependency-graph">Neo4j GraphGists</a></p><h3>Setting up Neo4j</h3><p>Download the Neo4j Community Server from <a href="https://neo4j.com/download/">https://neo4j.com/download/</a> or install with a package manager like Chocolatey, apt-get or yum. If you’re installing Neo4j for the first time and testing things out, I recommend installing Neo4j Desktop. It comes with great visualizations and neo4j servers included. I’ll continue the setup example using neo4j Desktop as it’s more graphical, but you can also connect Neo4j Desktop to your community server.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/278516eb06223bc86a8bd86efe643cb7/href">https://medium.com/media/278516eb06223bc86a8bd86efe643cb7/href</a></iframe><h3>Create your Graph</h3><p>First, let’s create a new graph and call it Infrastructure. I noticed a trend with a lot of big companies to create interconnected data systems that graph incredible amounts of data that might not be obviously connected, so you might want to name it something broader than Infrastructure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/1*Hlbp3GgR2pF2t0sJVaFIPA.png" /></figure><h3>Install Plugins</h3><p>Plugins extend the graph functionality with new features. The APOC and Graph Algorithms libraries contain a lot of algorithms that are going to be very useful for graph analysis, so let’s install them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*dE7mwMY1WqnLqzeFesqfng.png" /></figure><h3>Get Data Into Neo4j</h3><h4>Importing data from CSV</h4><p>One of the simplest ways to import data into neo4j is to load it from a .csv. Here we’ll create a CSV with headers hostname, dc, os, and last and save it in neo4j’s import directory. Neo4j by default blocks local files from only being allowed to be read from the import folder, which is different on each system. On Neo4j Desktop, click the Open Folder button to find it</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*3IX0oY4dNIx69Kjlu7uwlA.png" /></figure><p>Other OS file locations:</p><p><a href="https://neo4j.com/docs/operations-manual/current/configuration/file-locations/">Default file locations - Operations Manual</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/781ef08cc97e6ccf618d353b4e38741e/href">https://medium.com/media/781ef08cc97e6ccf618d353b4e38741e/href</a></iframe><h4>Import data from external JSON</h4><p>We can just as easily load data from external sources as JSON</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/034534d7a1463e63f0668fe9a6283bc6/href">https://medium.com/media/034534d7a1463e63f0668fe9a6283bc6/href</a></iframe><h4>Conditionally Create Relationships</h4><p>This one’s a bit hacky maybe, but sometimes the raw structure of our data might need us to only crate a relationship if the value is not an empty string</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/85c0d263d9bbdaf33e792dffbfa7d023/href">https://medium.com/media/85c0d263d9bbdaf33e792dffbfa7d023/href</a></iframe><h3>Connect Neo4j to Elasticsearch</h3><p>Getting data in manually is ok, and the above can be put on a schedule, where one process exports data into CSV and makes it accessible in a folder or remote location like an FTP. Then another scheduled task runs the import query. But we can take a step here to cut out the middle step in the process, and just connect the 2 systems directly. This simplifies our architecture, which means fewer parts that are likely to fail.</p><h4>Create a new user in Neo4j</h4><p>Create a new user you’ll use later for connecting from logstash.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/470ca6f603bd9d4fd85dc32774f15b29/href">https://medium.com/media/470ca6f603bd9d4fd85dc32774f15b29/href</a></iframe><h4>Trust elasticsearch certificate</h4><p>Download the public key certificate from your elasticsearch cluster, and let’s add it to the trust store.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9480722c975ab040fb237b5bf6c5639c/href">https://medium.com/media/9480722c975ab040fb237b5bf6c5639c/href</a></iframe><h4>Connect to elasticsearch</h4><p>apoc.es.* is the procedure pack that makes it all possible. Let’s try it out and just fetch some stats</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e16d1a323adf72e5b3ca9e5b357ca4f0/href">https://medium.com/media/e16d1a323adf72e5b3ca9e5b357ca4f0/href</a></iframe><p>We should get something like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*Woq1Ln0Qc58WQhQrt4GLqg.png" /></figure><h3>Import Structured Data From Elasticsearch to Neo4j</h3><p>Next, we’ll create a paged query, which uses the Scroll API (similar to a cursor in SQL) to load paged data from elasticsearch, and process one record at a time. First, we’ll get a chunk of data, and then we’ll use the scrollId to iterate through the rest of the results.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c3f6215f6e63bc94955c4c07d9b4e38d/href">https://medium.com/media/c3f6215f6e63bc94955c4c07d9b4e38d/href</a></iframe><h3>Loading Aggregated Data from Elasticsearch to Neo4j</h3><p>If our data source isn’t structured, say we just ingest logs, but we already indexed them, and can extract useful data from aggregations, it might be more efficient to just ingest aggregations. For this, we need to rely on apoc.es.postRaw and compose our own JSON aggregation definition. We’ll also limit our aggregation over a specific time span, which we can use later to optimize our scheduled task.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad64eacf6b7250ce09a36d179afc1a97/href">https://medium.com/media/ad64eacf6b7250ce09a36d179afc1a97/href</a></iframe><p>The query above expanded for readability:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9202458a435728babd3b636614cf4a8f/href">https://medium.com/media/9202458a435728babd3b636614cf4a8f/href</a></iframe><p>Our response will be grouped into aggregation buckets looking like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/290/1*gYm-6xUDGqLfm0Iw8ftVRg.png" /></figure><p>Now we can form our import logic based on these aggregations, and create our model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a0d9ad1876772b57012c6b25a515694f/href">https://medium.com/media/a0d9ad1876772b57012c6b25a515694f/href</a></iframe><p>Full command reference:</p><p><a href="https://neo4j-contrib.github.io/neo4j-apoc-procedures/3.5/database-integration/elasticsearch/">8.3. ElasticSearch Integration - Chapter 8. Database Integration</a></p><h3>Importing Data Automatically on a Schedule</h3><p>We have a lot of scheduling options overall, but with keeping dependencies to a minimum, let’s schedule our imports to run from right within Neo4j</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e82c48f82d4153b7d193c37a7ef97623/href">https://medium.com/media/e82c48f82d4153b7d193c37a7ef97623/href</a></iframe><h3>Create Some Useful Queries</h3><p>Now that we have aggregated data represented as a graph, maybe the state of our environment at a given time, we can start to extract some insights. Here are some ideas</p><p>Find email addresses of users which use application A and application B</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/31b0e676ed956d771105be34e5d2064b/href">https://medium.com/media/31b0e676ed956d771105be34e5d2064b/href</a></iframe><p>Find email addresses of users who use application A and application B and are not employees of Facebook</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1b745349e4773d5c8e256620bf05ad82/href">https://medium.com/media/1b745349e4773d5c8e256620bf05ad82/href</a></iframe><h4>List organizations and count of users who use more than one application and are not your employees</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/38989091775affd45f7bd8b37ce52704/href">https://medium.com/media/38989091775affd45f7bd8b37ce52704/href</a></iframe><h3>Other ideas</h3><ul><li><a href="https://neo4j.com/blog/knowledge-graph-search-elasticsearch-neo4j/">Knowledge Graph Search with Elasticsearch and Neo4j</a></li><li><a href="https://neo4j.com/graphgists/?category=network-and-it-operations">Neo4j GraphGists</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=292354fc9e88" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Signing Git Commits Using YubiKey on Windows]]></title>
            <link>https://medium.com/@alex.puiu/signing-git-commits-using-yubikey-on-windows-75f99ea79c82?source=rss-d658781ec9e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/75f99ea79c82</guid>
            <category><![CDATA[yubikey]]></category>
            <category><![CDATA[codesign]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[gpg]]></category>
            <category><![CDATA[git]]></category>
            <dc:creator><![CDATA[Alexandru Puiu]]></dc:creator>
            <pubDate>Sun, 02 Feb 2020 19:25:21 GMT</pubDate>
            <atom:updated>2020-06-25T05:03:55.240Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OrpIrdsX2unjp1Io.png" /></figure><p>There are several things we need to do in order to achieve end-to-end security in our release pipeline. In this post, I’ll explain how to set up signing git commits and store the private key on a YubiKey using it as a smart card. Signing our commits is especially important in public projects like those on GitHub, to avoid people impersonating us. For private projects and later on in the build pipeline, we can validate that all our commits are signed by trusted parties, and add gates to protect against unauthorized code making it into our products.</p><p>If you don’t already have one, go pick up a YubiKey, you’ll be really glad you did. Then set it up as a 2nd factor everywhere you can.</p><p>Alternatively, you can now build your own security key thanks to Google</p><p><a href="https://security.googleblog.com/2020/01/say-hello-to-opensk-fully-open-source.html">Say hello to OpenSK: a fully open-source security key implementation</a></p><p>I haven’t tried that yet, as my nRF52840 board is arriving next week.</p><p>YubiKey supports a large number of protocols. The YubiKey 5 NFS supports WebAuthn, FIDO2 CTAP1, FIDO2 CTAP2, Universal 2nd Factor (U2F), Smart card (PIV-compatible), Yubico OTP, OATH — HOTP (Event), OATH — TOTP (Time), Open PGP and Secure Static Password, and cryptographic operations using RSA 2048, RSA 4096 (PGP), ECC p256, ECC p384. On top of all of these, it can function as a FIDO HID Device, CCID Smart Card and HID Keyboard.</p><p>For our purpose, we’re interested in it acting like a Smart Card that holds a GPG* (Gnu Privacy Guard) key since the YubiKey can look like a PIV (Personal Identity Verification) Smart Card.</p><blockquote>GPG is a rewrite of PGP (Pretty Good Privacy). PGP uses the RSA and IDEA encryption algorithms, while GPG uses the NIST AES (Advanced Encryption Standard).</blockquote><h3>Install Gpg4Win</h3><p>First, we’ll need a toolkit to facilitate our GPG usage. I found Gpg4Win to be very well suited for the task. You can download it at</p><p><a href="https://www.gpg4win.org/thanks-for-download.html">Gpg4win - Thanks for downloading</a></p><p>The install is straightforward, defaults work fine.</p><h3>Generate a GPG Key Pair</h3><p>Take your existing private key pair and import it, or generate a new one. I recommend going with a 4096 GPG key pair, as that’s the largest supported by newer YubiKeys. If you have a YubiKey Neo, you can create a separate 2048 signing key. Scott Hanselman covers how to set up a YubiKey Neo with 2048 bit keys</p><p><a href="https://www.hanselman.com/blog/HowToSetupSignedGitCommitsWithAYubiKeyNEOAndGPGAndKeybaseOnWindows.aspx">How to setup Signed Git Commits with a YubiKey NEO and GPG and Keybase on Windows</a></p><p>To create a new key, click File -&gt; New Key Pair... then click Create a personal OpenPGP key pair. Enter your name and Email (make sure it&#39;s the same email you use on GitHub). Then click Advanced Settings and select 4096 bits for RSA and + RSA and choose a validity period. The default 2 years is good, which will force you to rotate your key frequently enough for this type of usage. I don&#39;t recommend having a key that doesn&#39;t expire, since losing it puts you at greater risk long-term, and you have to take extra-special care of your revocation keys.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*m70zU3VAmYGNDkmxAak5cQ.png" /></figure><p>Then hit Next and Create and you&#39;ll be prompted to enter a Passphrase and repeat it. Choose a strong one, ideally generated by your password manager, click Ok and wait until your keys are generated. At this stage, you might want to make a backup of your Key Pair, but if you do, make sure to keep it in some sort of offline storage like a USB drive or floppy disk you got just for this purpose (they keys are small enough and floppy drives still exist).</p><p>If you imported your key, make sure that your UID contains the email address that you use on GitHub.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*ShaJ0IcDTjPTB83T_SPJKw.png" /></figure><h3>Create a revocation certificate</h3><p>This step is very important because our YubiKey might get lost or stolen. While our GitHub accounts are protected by separate SSH keys, and the private key is protected by a PIN, there’s still risk present in other forms. We want to take the extra measure of revoking the key in those situations.</p><p>Double click on the certificate you created, click Generate revocation certificate and save it to a safe place that you back up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*WnsNz7lpYbJGE97riT5kNw.png" /></figure><h3>Prepare The YubiKey</h3><p>When you plug in your YubiKey, it should get auto-detected and installed. It’ll show up in Device Manager under Smart cards something like Identity Device (NIST SP800-73[PIV]). This is fine for most Multi-factor authentication usages, but we&#39;ll need some additional functionality, so we need to install the YubiKey Smart Card Minidriver which we can get from</p><p><a href="https://www.yubico.com/products/services-software/download/smart-card-drivers-tools/">Smart card drivers and tools | Yubico</a></p><p>Download and unzip the driver to a folder. Go to Device Manager, right-click on Smart Cards -&gt; Identity Device (NIST SP800-73[PIV]), click Update Driver and point it to the folder containing the driver you downloaded. It should now see it as YubiKey Smart Card Minidriver.</p><p>Next, go to the command line and let’s confirm that we can see it as a smart card.</p><pre>&gt;gpg --card-status</pre><pre>Reader ...........: Yubico YubiKey OTP FIDO CCID 0</pre><pre>Application ID ...: ...</pre><pre>Application type .: OpenPGP</pre><pre>Version ..........: 2.1</pre><pre>Manufacturer .....: Yubico</pre><p>If you see something like the above, mentioning your YubiKey, you’re good to go. Sometimes Windows machines and corporate laptops might have multiple smart card readers, or might not detect your Yubikey as one here. To solve that, we’ll need to manually point GPG to the right place.</p><p>Create an empty file %appdata%\gnupg\scdaemon.conf and add a reader-port line that points to your YubiKey. To get the exact name of the device, go to Device Manager, then View -&gt; Show Hidden Devices and expand Software Devices. Then add the exact spelling into the scdaemon.conf file you created like this:</p><pre>reader-port &quot;Yubico YubiKey OTP+FIDO+CCID 0&quot;</pre><p>Save the file, and next you’ll need to kill/restart any GPG services or background apps you have open, so it detects the changes. Alternatively, you can restart your computer. In my case, I just had to close Kleopatra and kill the GnuPG&#39;s private key daemon processes. If all goes well, when you run gpg --card-status now, you should see the YubiKey.</p><h3>Change Pin</h3><p>YubiKeys come with a user pin set to 123456 by default, and an admin pin set to 12345678. Before starting to use the PIV functionality of a YubiKey, it is important to change the PIN, PUK and Management keys from their default values. For this step, you’ll need to download and install the Yubikey Manager, which you can get from <a href="https://developers.yubico.com/yubikey-manager-qt/Releases/">https://developers.yubico.com/yubikey-manager-qt/Releases/</a>.</p><p>I had trouble with the GUI not seeing my key, but the CLI lets us specify some additional params so we can force the correct reader. Open a command prompt in C:\Program Files\Yubico\YubiKey Manager and make sure you can see the key. Run ykman info to check. If it doens&#39;t see it, try ykman --reader yubico info. Here&#39;s what mine looks like:</p><pre>C:\Program Files\Yubico\YubiKey Manager&gt;ykman --reader yubico info</pre><pre>Device type: YubiKey 5 NFC</pre><pre>Serial number: ...</pre><pre>Firmware version: 5.1.1</pre><pre>Form factor: Keychain (USB-A)</pre><pre>Enabled USB interfaces: OTP+FIDO+CCID</pre><pre>NFC interface is enabled.</pre><pre>Applications    USB     NFC</pre><pre>OTP             Enabled Enabled</pre><pre>FIDO U2F        Enabled Enabled</pre><pre>OpenPGP         Enabled Enabled</pre><pre>PIV             Enabled Disabled</pre><pre>OATH            Enabled Enabled</pre><pre>FIDO2           Enabled Enabled</pre><p>Now we can set all our pins and create a random management key and store it on the device, protected with the PIN.</p><pre>ykman --reader yubico piv change-pin</pre><pre>ykman --reader yubico piv change-puk</pre><pre>ykman --reader yubico piv change-management-key --generate --protect</pre><p>For more details, including recovering from a blocked PIN see <a href="https://developers.yubico.com/PIV/Guides/Device_setup.html">https://developers.yubico.com/PIV/Guides/Device_setup.html</a></p><h3>Move Private Key to YubiKey</h3><p>Back in the command</p><p>&gt; gpg --edit-key <a href="https://scatteredcode.net/cdn-cgi/l/email-protection">[email protected]</a></p><pre>gpg (GnuPG) 2.2.19; Copyright (C) 2019 Free Software Foundation, Inc.</pre><pre>This is free software: you are free to change and redistribute it.</pre><pre>There is NO WARRANTY, to the extent permitted by law.</pre><pre>Secret key is available.</pre><pre>sec  rsa4096/683AB68D867FEB5C</pre><pre>created: 2020-02-02  expires: 2022-02-02  usage: SC</pre><pre>trust: ultimate      validity: ultimate</pre><pre>ssb  rsa4096/4B4C3D1428F04A81</pre><pre>created: 2020-02-02  expires: 2022-02-02  usage: E</pre><pre>[ultimate] (1). Alexandru Puiu &lt;alex@ops.ai&gt;</pre><p>Next enter the toggle command, then key 1 (key you want to select).</p><p>To transfer the private key of the currently selected key you’re in, run keytocard</p><pre>gpg&gt; toggle</pre><pre>sec  rsa4096/683AB68D867FEB5C</pre><pre>created: 2020-02-02  expires: 2022-02-02  usage: SC</pre><pre>trust: ultimate      validity: ultimate</pre><pre>ssb* rsa4096/4B4C3D1428F04A81</pre><pre>created: 2020-02-02  expires: 2022-02-02  usage: E</pre><pre>[ultimate] (1). Alexandru Puiu &lt;alex@ops.ai&gt;</pre><pre>gpg&gt; key 1</pre><pre>sec  rsa4096/683AB68D867FEB5C</pre><pre>created: 2020-02-02  expires: 2022-02-02  usage: SC</pre><pre>trust: ultimate      validity: ultimate</pre><pre>ssb  rsa4096/4B4C3D1428F04A81</pre><pre>created: 2020-02-02  expires: 2022-02-02  usage: E</pre><pre>[ultimate] (1). Alexandru Puiu &lt;alex@ops.ai&gt;</pre><pre>gpg&gt; keytocard</pre><pre>Really move the primary key? (y/N) y</pre><pre>Please select where to store the key:</pre><pre>(1) Signature key</pre><pre>(3) Authentication key</pre><pre>Your selection? 1</pre><pre>sec  rsa4096/683AB68D867FEB5C</pre><pre>created: 2020-02-02  expires: 2022-02-02  usage: SC</pre><pre>trust: ultimate      validity: ultimate</pre><pre>ssb  rsa4096/4B4C3D1428F04A81</pre><pre>created: 2020-02-02  expires: 2022-02-02  usage: E</pre><pre>[ultimate] (1). Alexandru Puiu &lt;alex@ops.ai&gt;</pre><pre>gpg&gt; save</pre><p>Once complete, the private key is moved to your Yubikey, and the Yubikey will need to be inserted and unlocked with the pin in order to sign anything.</p><h3>Configure Git to use our key</h3><p>Now that we have our key secure, it’s time to configure Git to use it.</p><p>First, let’s verify that our key is set up correctly:</p><pre>&gt;gpg --list-secret-keys --keyid-format LONG</pre><pre>C:/Users/{username}/AppData/Roaming/gnupg/pubring.kbx</pre><pre>--------------------------------------------------------</pre><pre>sec&gt;  rsa4096/683AB68D867FEB5C 2020-02-02 [SC] [expires: 2022-02-02]</pre><pre>uid                 [ultimate] Alexandru Puiu &lt;alex@ops.ai&gt;</pre><p>Next, we’ll point Git globally on our system to use our GnuPG installation as the default for gpg operations. You can also configure it per project, by removing -global and running these commands on every project, but for our purposes, system-wide works best:</p><pre>&gt;git config --global gpg.program &quot;c:\Program Files (x86)\GnuPG\bin\gpg.exe&quot;</pre><pre>&gt;git config --global commit.gpgsign true</pre><pre>&gt;git config --global user.signingkey 683AB68D867FEB5C</pre><p>Now all our new commits will be signed using our key. Note that you won’t be able to commit anything without inserting and unlocking the private key.</p><h3>Add the GPG Public Key to GitHub</h3><p>This is a different set of keys than your SSH keys, but they are both managed under the SSH and GPG keys tab.</p><p>Open Kleopatra, double-click on your key, then click Export.... Make sure you&#39;re exporting the public key. It should start with -----BEGIN PGP PUBLIC KEY BLOCK-----</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/1*vDc8_yJw7Ett0pDr-I39fw.png" /></figure><p>Copy the key. Then go into GitHub, click on your profile image -&gt; Settings then on the left sidebar click SSH and GPG keys. Then click New GPG key and paste the key from above.</p><h3>Test Signed Commits</h3><p>When you try to commit your changes, you should be prompted to enter the pin for your key:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/236/1*ZIZTvpQwFVGiJKV4I3FNDg.png" /></figure><p>Then push the commit(s) to your GitHub project and go to your Commits tab on the web, and notice the Verified badge</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/971/1*yAVcSiP4kv-XuihoieMzYQ.png" /></figure><h3>Setting Up on Other Machines</h3><p>Next, we’ll probably want to set this up on the other computers we use like our laptop.</p><p>First, we need to install Gpg4Win on the computer, and make sure it sees our Yubikey as a smart card.</p><pre>gpg --card-status</pre><p>If it doesn’t, just repeat the same steps as above, by creating a %appdata%\gnupg\scdaemon.conf file.</p><p>Next, import your public key. This is the same key you uploaded to GitHub. Save it as publickey.asc and run</p><pre>gpg --import &quot;publickey.asc&quot;</pre><p>Finally, configure Git to sign commits on this machine as well with our key.</p><pre>&gt;git config --global gpg.program &quot;c:\Program Files (x86)\GnuPG\bin\gpg.exe&quot;</pre><pre>&gt;git config --global commit.gpgsign true</pre><pre>&gt;git config --global user.signingkey 683AB68D867FEB5C</pre><p><em>Originally published at </em><a href="https://scatteredcode.net/signing-git-commits-using-yubikey-on-windows/"><em>https://scatteredcode.net</em></a><em> on February 2, 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75f99ea79c82" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enhanced Authentication Ideas]]></title>
            <link>https://medium.com/@alex.puiu/enhanced-authentication-ideas-3653a6a7d7b6?source=rss-d658781ec9e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/3653a6a7d7b6</guid>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[password-security]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[Alexandru Puiu]]></dc:creator>
            <pubDate>Fri, 10 Jan 2020 14:33:36 GMT</pubDate>
            <atom:updated>2020-01-10T14:33:36.621Z</atom:updated>
            <content:encoded><![CDATA[<p>Security, and particularly around authentication, authorization, and auditing, is my favorite part of software development. It’s the stuff that not just lets us be safe, but rather, the reason I like it so much is that it’s by far the broadest part of software development. It requires us to understand the full breadth of the field, from hardware security components like TPM (Trusted Platform Module) chips to IETF standards-based protocols that not only make things safer but open the door to creating simpler, better, and more integrated systems. Historically it may not have always been the case, and security was at odds with other fields like performance and usability. Those problems have long been addressed now, once we realized that thinking of systems as having behavior emergent from the interaction of many systems and focusing on the end problem we’re trying to solve, instead of trying to fit the problem into an isolated individual system.</p><p>This new way of thinking gave way to new fields such as Systems Engineering, where the focus moves to focus on discovering the real problems that need to be resolved and identifying the most probable and highest impact failures that can occur. The domain of security, and organizations like (ISC)², OWASP and NIST have recognized and pushed the application of this understanding very well over the years, and standards have changed and become better.</p><p>One concrete example of this I think is NIST’s update to NIST 800–171 to remove periodic password change requirements, and drop the password complexity requirements in favor of screening new passwords against a list of commonly used or compromised passwords.</p><p>We figured out that we need to understand the user and make security decisions that work around them, thus the field of UX (User Experience) became very relevant to security. Here are some ideas I’ve collected so far to add into an authentication server:</p><h3>Slow Verification instead of Account Locking</h3><p>Account locking was developed in order to prevent password brute-forcing or password guessing. The idea is simple and effective; lock an account for 30 minutes if the user enters their password wrong 5 times or some variant of this. This basically makes it infeasible for an attacker, but its strength depends on the implementation, and there are questions like if we reset the lock count every time the user enters the correct password. If the password is used by a service account that reauthenticates every minute for example and the count is reset then, then our attack vector is to try 4 passwords every minute, thus avoiding locking. This is still pretty good actually, but what surprised me was that we haven’t seen a virus/botnet/attack that just goes around and locks everyone’s account continuously.</p><p>Instead of locking the account, we could gradually increase the time it takes to verify a password by introducing a random delay. Random delays already play a valuable role in password verification, because, without them, an attacker could use the certain timing techniques to guess at the password (although modern salting + hashing techniques mostly solved this). The first login attempt would be basically instant, but after the first bad attempt, the second one would add a 1-second delay, then the 3rd would add a 5-second delay, 4th would be a 15-second delay, and so on. If the user really mistyped or forgot their password, they would still have an ok experience. The delay would still be there for the good password attempt as well, and the delay would go down in time as there are fewer attempts. This could make guessing passwords quite expensive for the attacker, and a better experience for the user.</p><p>Another option could be to borrow from bitcoin and use proof-of-work. The server could publish a pattern the hash needs to match, which dictates the difficulty, then generate a hash based on the password that matches the pattern, and send it along with the password. I’m also exploring a technique using POP (Proof of Key Possession) as a way to avoid sending the password or a fixed hash over the wire at all.</p><h3>Password Frequency and Topology</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/489/1*g-IFuR0Fic5nPFtAfZRi7A.png" /></figure><p>Password topologies are basically the (geographic) topology of the password and common substitutions. The most common one being a password that starts with a 6–7 letter dictionary word, the first character uppercase and has a 1 at the end. If special characters are also required, o becomes 0, a becomes @, or an ! is added to the end. My suggestion is to keep a running counter of the most used topologies over time (these will be ever-growing) and show the user where their password sits on a standard distribution bar chart of the top 50 topologies.</p><p>Another enhancement would be to compare the password against public leaked credential databases like <a href="https://haveibeenpwned.com/">https://haveibeenpwned.com/</a> and warn the user if they’re using a common password or one that has been found in a leaked database. Basically another graph indicating how common or how easy their password would be to crack, and suggestions for making it stronger. My suggestion is usually to stay away from character replacements in short passwords, and instead use a sentence. Sentences are easy for people to remember and natural to type while being quite a challenge for anyone to crack.</p><h3>Account Pin instead of Password</h3><p>The less time the user has to type their password, the fewer chances there are of it being intercepted. From key loggers to MITM (man-in-the-middle) attacks to shoulder surfing, there are plenty of threats. Instead, Microsoft came up with a great solution for Windows 10: use a pin to unlock the computer. If you enter the pin incorrectly too many times, you now need to enter your password. The pin could work on the web as well, and we might even be able to make the browser itself a second-factor authentication device.</p><p>During initial or new device auth, the user could be prompted to MFA as well, and enroll their browser in PIN authentication. On the server, some cryptographic material would associate the pin with the password (still working on the details), and the browser would keep a public/private key pair. When the PIN is entered, it’s signed and sent to the server for validation. If a bad PIN was entered enough times (maybe 5), then the associated browser becomes disassociated with the account, and now needs to prompt the user for a password.</p><h3>A Network of Services</h3><p>Send the user around some partner services, or describe the user (email, headers hash, IP address, etc) in a standard format, which other partner services could vouch for having seen normal activity from the user recently. If the user trying to log into your super-sensitive system has recently logged into their bank account from the same computer and posted a tweet recently from that same computer, chances are higher of them being who they say they are, as opposed to a brand new computer popping up in a random location trying to transfer funds out of the account on the first login.</p><h3>Reverse Brute-Force and Credential Stuffing Prevention</h3><p>Techniques like account locking are also not effective against attacks like brute-force when the password used across multiple submissions is the same, but the username changes. One technique I originally came up with involved keeping a counter in a short-lived cache with a password hash using a different algorithm than the one used in the password store for extra measure. However, other similar attacks like credential stuffing get around that. In credential stuffing, a hacker has a database of username + password combinations that they stole from another site, and will just try combinations in hopes that a user reused the same password on multiple sites. Over a 17-month period, from November 2017 through the end of March 2019, security and content delivery company Akamai detected 55 billion credential stuffing attacks across dozens of verticals.</p><p><a href="https://www.akamai.com/us/en/multimedia/documents/state-of-the-internet/soti-security-web-attacks-and-gaming-abuse-report-2019.pdf">https://www.akamai.com/us/en/multimedia/documents/state-of-the-internet/soti-security-web-attacks-and-gaming-abuse-report-2019.pdf</a></p><p>As with any cybersecurity defense, it’s a battle of wits and time. The first thing we need to do is to detect the attack. We can get an idea of an attack happening by monitoring failed password attempts. Then we can use multiple fingerprinting techniques at the same time, and track attempts per fingerprint vector, and flag each fingerprint vector as a potential attack spot. We can link fingerprint hashes to each other, and if we detect an attack pattern on one, use the associated ones to block across all of them. This way, if the attacker is stealthy and continuously uses a different IP, or presents a random user-agent or list of headers, we can still identify them.</p><p>Additionally, a captcha, sequence of requests (user has to GET the login page before they can submit it), and multi-factor authentication are really good defenses.</p><p>Blocking accounts with leaked passwords and forcing users to change their passwords is an expensive solution, but depending on what we’re protecting, might be worthwhile.</p><h3>More Resources</h3><p><a href="https://www.csoonline.com/article/3237827/ready-for-more-secure-authentication-try-these-password-alternatives-and-enhancements.html">https://www.csoonline.com/article/3237827/ready-for-more-secure-authentication-try-these-password-alternatives-and-enhancements.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3653a6a7d7b6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Parallel Foreach async in C#]]></title>
            <link>https://medium.com/@alex.puiu/parallel-foreach-async-in-c-36756f8ebe62?source=rss-d658781ec9e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/36756f8ebe62</guid>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[parallel-processing]]></category>
            <category><![CDATA[benchmark]]></category>
            <dc:creator><![CDATA[Alexandru Puiu]]></dc:creator>
            <pubDate>Mon, 06 Jan 2020 13:34:44 GMT</pubDate>
            <atom:updated>2020-06-22T15:48:54.748Z</atom:updated>
            <content:encoded><![CDATA[<p>Foreach itself is very useful and efficient for most operations. Sometimes special situations arise where high latency in getting data to iterate over, or processing data inside the foreach depends on an operation with very high latency or long processing. This is the case for example with getting paged data from a database to iterate over. The goal is to start getting data from the database, but a chunk of data at a time, since getting one record at a time introduces its own overhead. As the data becomes available, we’d start processing it, while in the background we get more data and feed it into the processor. The processing part would itself be parallel as well, and start processing the next iterator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*pmYbJeZxwVu836PBx8ftBQ.jpeg" /></figure><h4>ForEachAsync</h4><p>My favorite way to do this is with an extension method Stephen Toub wrote many years ago, that accepts a data generator and breaks the data source into partitions allowing for specifying the degree of parallelism and accepts a lambda to execute for each item</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c0ee28b2a2b129f8454742e8b722a2d/href">https://medium.com/media/2c0ee28b2a2b129f8454742e8b722a2d/href</a></iframe><p>The history of it and previous versions are available here: <a href="https://devblogs.microsoft.com/pfxteam/implementing-a-simple-foreachasync/">https://devblogs.microsoft.com/pfxteam/implementing-a-simple-foreachasync/</a></p><p>The cool part is when we combine the generator pattern as the IEnumerable source.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/84475260fc2f0c1810df5f8be8aa209e/href">https://medium.com/media/84475260fc2f0c1810df5f8be8aa209e/href</a></iframe><p>When we combine the two, we’re fetching 20 pages from the database in parallel, then iterating over the results from each. Pausing execution of the thread on each result and yielding that item to the async lambda we have going on in the other thread:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e7937846844f52ded610322ec355f796/href">https://medium.com/media/e7937846844f52ded610322ec355f796/href</a></iframe><h3>Modernizing Async Foreach</h3><p>Thanks to houseofcat we can actually improve on the above a bit by using some newer language features</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/301de1c41070eaa4f7ee4dc722c8f85b/href">https://medium.com/media/301de1c41070eaa4f7ee4dc722c8f85b/href</a></iframe><p><a href="https://houseofcat.io/tutorials/csharp/async/parallelforeachasync">source: https://houseofcat.io/tutorials/csharp/async/parallelforeachasync</a></p><h3>C# 8.0 and Async Streams</h3><p>From using this extensively whenever I need to work on really large data sets, I can vouch for its performance, but I’ve been looking for ways to push it even further. Once C# 8.0 announced async foreach, my interest was peaked. And it turns out that we can do better. Yielding on each item causes a lot of context switches, so want to yield one page at a time, but then we have to deal with nested foreach statements, and it’s just not as cool as the one-liner above.</p><p>The first thing we have new in C# 8 is IAsyncEnumerable, so our query can now look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/abb9f6e2ac8cc617e11a1af94b707ac9/href">https://medium.com/media/abb9f6e2ac8cc617e11a1af94b707ac9/href</a></iframe><p>And using the new await foreach we would expect the following to get close in at least optimizing the query part</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/88ba3c276f9144707ea2c1ed218532bd/href">https://medium.com/media/88ba3c276f9144707ea2c1ed218532bd/href</a></iframe><p>The above actually is pretty bad in execution time, but it’ll come in handy soon.</p><h3>Optimizing Parallel Foreach Further</h3><p>Our next iteration comes from Stackoverflow. We instead use the TaskScheduler class with ActionBlock, and so far this is quite a bit faster than all the previous solutions</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a5e292e17a43b1ff33bfc7e753bb997/href">https://medium.com/media/4a5e292e17a43b1ff33bfc7e753bb997/href</a></iframe><p>Source: <a href="https://stackoverflow.com/questions/14673728/run-async-method-8-times-in-parallel">https://stackoverflow.com/questions/14673728/run-async-method-8-times-in-parallel</a></p><p>Using it looks like this now</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f77e0644aba9a295fdf9833ef232187/href">https://medium.com/media/4f77e0644aba9a295fdf9833ef232187/href</a></iframe><h3>Optimizing Parallel async Foreach with C# 8.0 async streams</h3><p>Fortunately, we can take advantage of the C# 8.0 async streams feature, and optimize this even more:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5a200577f477d554ac568e64b720a798/href">https://medium.com/media/5a200577f477d554ac568e64b720a798/href</a></iframe><p>Simulating a really slow connection to the database, and slow processing using Thread.Sleep(100) for both querying after each page, and during each foreach iteration, we get the following performance numbers:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/92458440b1ee5d5f71ab90af1be5cd7a/href">https://medium.com/media/92458440b1ee5d5f71ab90af1be5cd7a/href</a></iframe><p>Then I decided to turn it into a real benchmark project and test on some different size datasets.</p><h4>Using 913 Order records</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/daa2f4e74a38c81735435566d558c12e/href">https://medium.com/media/daa2f4e74a38c81735435566d558c12e/href</a></iframe><h4>Using 9130 Order records</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/34fd57b53ba2827df775b114d8de27aa/href">https://medium.com/media/34fd57b53ba2827df775b114d8de27aa/href</a></iframe><p>DotNetBenchmark project, results and source code are available on my github</p><p><a href="https://github.com/scattered-code/experiments">scattered-code/experiments</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36756f8ebe62" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>