Randall Munroe’s XKCD ‘UK Coal’
via the comic humor & dry wit of Randall Munroe, creator of XKCD
The post Randall Munroe’s XKCD ‘UK Coal’ appeared first on Security Boulevard.
via the comic humor & dry wit of Randall Munroe, creator of XKCD
The post Randall Munroe’s XKCD ‘UK Coal’ appeared first on Security Boulevard.
Silver Spring, MD, Oct. 2, 2024, CyberNewswire — Aembit, the non-human IAM company, today announced the appointment of Mario Duarte as chief information security officer (CISO). Duarte, formerly head of security at Snowflake, joins Aembit with a deep commitment … (more…)
The post News alert: Aembit appoints former Snowflake security director Mario Duarte as its new CISO first appeared on The Last Watchdog.
The post News alert: Aembit appoints former Snowflake security director Mario Duarte as its new CISO appeared first on Security Boulevard.
Exponential growth in code, an unmanageable attack surface as a result of Cloud + DevOps, accelerated development cycles...
The post Why ASPM Requires an Independent Approach: Exploring the Role of ASPM vs. CNAPP | Part 1 appeared first on Cycode.
The post Why ASPM Requires an Independent Approach: Exploring the Role of ASPM vs. CNAPP | Part 1 appeared first on Security Boulevard.
Authors/Presenters:Jiaqi Gao, Jiamin Cao, Yifan Li, Mengqi Liu, Ming Tang, Dennis Cai, Ennan Zhai
Our sincere thanks to USENIX, and the Presenters & Authors for publishing their superb 21st USENIX Symposium on Networked Systems Design and Implementation (NSDI '24) content, placing the organizations enduring commitment to Open Access front and center. Originating from the conference’s events situated at the Hyatt Regency Santa Clara; and via the organizations YouTube channel.
The post USENIX NSDI ’24 – Sirius: Composing Network Function Chains into P4-Capable Edge Gateways appeared first on Security Boulevard.
In conversation: Pete McKernan & Luke Luckett
As organizations seek to wrap their arms around potential cybersecurity exposures, CIOs and CISOs are increasingly pushing their vulnerability management teams to widen scope. With such a focus, the growing concept of continuous threat exposure management (CTEM) aims to prioritize whatever most threatens the enterprise, whether or not such threats come with a known CVE or are even an unclassified vector for a ransomware attack.
Wherever an organization ranks on the path to CTEM and vulnerability management maturity, IT and cyber leaders are rapidly reducing business risk by adding attack path management (APM) to their programs. The following is a condensed version of a conversation on the topic between Luke Luckett, Director of Product Marketing, and Pete McKernan, Strategic Partner Engineer, who collaborate on Attack Path Management education at SpecterOps.
Luke Luckett: Good morning, Pete. Great to be with you today. In a recent conversation with one of our enterprise customers, you mentioned that Attack Path Management should be a critical part of every organization’s vulnerability management process. That got me curious and I wanted to learn more. So let’s start from the top: what are the key elements of a robust vulnerability management program?
Pete McKernan: Sure. The key elements of any security program start with having a security operations center (SOC) that’s responsible for both maintaining the security baseline of systems and monitoring the environment for any security events. Vulnerability management falls under that umbrella, and it’s about ensuring that systems run as they should. This ties in directly with Attack Path Management, which aligns with vulnerability management in terms of maintaining security over time.
Then, you have SOC analysts using various event monitoring tools to correlate different events and identify risks before things go haywire. Essentially, vulnerability management and Attack Path Management are like twin pillars of a defensive operation — each one is critical to ensuring that systems remain secure.
Luke Luckett: That makes sense. How does Attack Path Management (or APM, as it’s commonly known) fit into that structure?
Pete McKernan: APM complements vulnerability management. Think of vulnerability management as handling patching and configuration of the organization’s software and networks, but it only covers a portion of the environment. APM, particularly with tools like Bloodhound Enterprise, goes deeper by focusing on identity-related risks that traditional vulnerability management tools don’t handle. For example, vulnerability management is great for securing software and checking network configurations, but it doesn’t address how an attacker could exploit an identity system like Active Directory or Entra ID to move laterally across the network.
APM fills this gap by identifying hidden relationships within the environment — using graph theory, for instance — to find weak spots that aren’t immediately visible. This approach supports a “better together” strategy, where traditional vulnerability management tools work hand-in-hand with APM to provide a more complete security picture.
Identity Attack Path Management is a critical part of a robust CTEM and Vulnerability Management strategy. APM helps solve the problem of attack paths, which are often attackers’ quickest path to lateral movement, unauthorized escalations and domain takeovers.Luke Luckett: That’s really interesting. So how are you seeing security leaders go about integrating Attack Path Management into an existing CTEM or vulnerability management process?
Pete McKernan: The first step is education. The CISO needs to understand what Attack Path Management is and how it fits within the organization’s broader security landscape. Once they grasp the basics, they should engage their vulnerability management team to start a conversation about identity security. Many organizations already have tools (and even separate identity teams) that monitor identity-related risks, but they may not be leveraging them effectively.
I recommend starting with BloodHound’s Community Edition, running it in their environment, and letting the data speak for itself. BloodHound helps blue teams and red teams better understand privileged relationships (attack paths) in Active Directory, Entra, and hybrid environments — so they can eliminate those attack paths. Once teams see the results and the risks highlighted, they can take the next steps to engage further with tools like BloodHound Enterprise. From there, it’s about fusing the data from APM and vulnerability management to get a full picture of the organization’s security posture. You don’t need to build an entirely new program — just empower your current team to see the other half of the picture.
Luke Luckett: It sounds like Attack Path Management provides that extra layer of visibility.
Pete McKernan: Exactly. Vulnerability management typically focuses on the software and network side of things, ensuring that patches are applied, configurations are secure, and no known vulnerabilities are present. But APM looks at how attackers could exploit identities within the organization. For example, if an attacker exploits a vulnerable application on the perimeter, they can use the application’s identity in Active Directory to move laterally and escalate privileges. This is why securing identity is so crucial — it’s often the preferred method of attack in today’s environment.
Luke Luckett: So, how does APM help in real-world scenarios?
Pete McKernan: With APM platforms like Bloodhound Enterprise, we see everything that traditional vulnerability management tools don’t. For example, vulnerability management tools don’t track identities or monitor how they interact across the network. Attackers often weave in and out of both identity and technology silos, meaning they’ll exploit a vulnerable technology and then leverage compromised identities to move through the network.
APM can map out these hidden pathways that attackers might use to gain access to sensitive areas, providing a level of visibility that’s just not available through traditional means. It helps organizations take proactive measures by identifying the vulnerabilities in their identity infrastructure — like dormant accounts with excessive permissions or forgotten groups nested deep within the network.
Luke Luckett: That brings us to the integration process. It sounds like the SOC and vulnerability management teams can easily add APM into their existing workflows.
Pete McKernan: Absolutely. APM integrates almost seamlessly with vulnerability management workflows. Both processes involve scanning systems, analyzing data and taking action based on the findings. Where APM really shines is in the fusion of identity data with the results of vulnerability scans. Once you have that complete picture, you can make far more informed decisions about the security of your environment. Integrating APM data becomes very simple for organizations utilizing data lakes and SIEMs to orchestrate action.
The key is to enable the teams you already have. They’re likely trained and capable of doing this work, but they need the right tools to see both the technological and identity-related risks. Once they have that, you don’t need to build a new program — just add the data and leverage the expertise you already have in place.
Luke Luckett: That makes a lot of sense. Really appreciate your time and expertise on this important topic, Pete! Thank you.
Closing the Gaps: How Attack Path Management Improves Vulnerability Management Programs was originally published in Posts By SpecterOps Team Members on Medium, where people are continuing the conversation by highlighting and responding to this story.
The post Closing the Gaps: How Attack Path Management Improves Vulnerability Management Programs appeared first on Security Boulevard.
Virtual CISO services can help managed service providers (MSPs) harden their attack surface management strategy and unlock growth. Read on to learn how.
The post Leverage vCISO Services to Unlock Managed Service Provider (MSP) Success appeared first on Security Boulevard.
In the world of managed service providers (MSPs), staying ahead of the curve requires constant innovation, particularly in data management and operational efficiency. I recently had the opportunity to interview Callen Sapien, President and acting Chief Security Officer (CSO) of MSPBots on the show floor of the Build IT event in Orlando, FL, to explore
The post Unlocking New Potential with MSPBots: A Conversation with Callen Sapien appeared first on Seceon Inc.
The post Unlocking New Potential with MSPBots: A Conversation with Callen Sapien appeared first on Security Boulevard.
4 min read Just when I thought I was out, they (non-human identities and a young startup named Aembit) pulled me back in.
The post Why I Came Out of (Pseudo) Retirement to Help Solve the Non-Human Identity Challenge as Aembit’s CISO appeared first on Aembit.
The post Why I Came Out of (Pseudo) Retirement to Help Solve the Non-Human Identity Challenge as Aembit’s CISO appeared first on Security Boulevard.
Despite slower hiring trends and tighter budgets, chief information security officer (CISO) compensation continues to rise, with the average U.S.-based CISO earning $565K, and top earners exceeding $1 million.
The post Average CISO Compensation Tops $500K appeared first on Security Boulevard.
MEDIA ADVISORY Leading experts to share insights on using orchestration to protect legacy identity systems with modern cloud identity platforms without code rewriting BOULDER, Colo., Oct. 2, 2024 – Strata Identity, the Identity Orchestration company, today announced it will host a free webinar on October 3rd with CyberArk on how to eliminate the costly, time-consuming...
The post Strata Identity and CyberArk to Host Webinar on Transforming Legacy Identity by Embracing Modern IAM appeared first on Strata.io.
The post Strata Identity and CyberArk to Host Webinar on Transforming Legacy Identity by Embracing Modern IAM appeared first on Security Boulevard.
Silver Spring, Maryland, 2nd October 2024, CyberNewsWire
The post Mario Duarte, Former Snowflake Cybersecurity Leader, Joins Aembit as CISO to Tackle Non-Human Identities appeared first on Security Boulevard.
Canonical has released security updates for Ubuntu 16.04 ESM and Ubuntu 18.04 ESM to address multiple vulnerabilities in Git, a powerful and widely-used distributed version control system. These vulnerabilities may allow malicious attackers to overwrite files outside the repository, inject arbitrary configuration, or even execute arbitrary code. In this article, we’ll explore the details of […]
The post Addressing Git Vulnerabilities in Ubuntu 18.04 and 16.04 appeared first on TuxCare.
The post Addressing Git Vulnerabilities in Ubuntu 18.04 and 16.04 appeared first on Security Boulevard.
Reaching p=reject does not mean your DMARC management ...
The post What Happens After p=Reject: Beyond the DMARC Golden Standard appeared first on EasyDMARC.
The post What Happens After p=Reject: Beyond the DMARC Golden Standard appeared first on Security Boulevard.
As of June 30, 2024, the CentOS Project ceased all updates and releases for CentOS Linux. CentOS Stream serves as the upstream development platform for future RHEL releases. CentOS Stream 9 will continue to receive regular updates, providing users with the latest features and security patches. In December 2020, Red Hat announced a significant shift […]
The post Future of CentOS Stream 9: The Road Ahead appeared first on TuxCare.
The post Future of CentOS Stream 9: The Road Ahead appeared first on Security Boulevard.
Cybersecurity professionals are facing increasing levels of stress, with 66% reporting that their roles have become more demanding over the past five years, according to a report from ISACA.
The post Cybersecurity Professionals Operate Under Increased Stress Levels appeared first on Security Boulevard.
As per a recent Microsoft alert, a threat actor with malicious financial motives has been observed leveraging a new INC ransomware strain to target the health sector in the United States (US). In this article, we’ll dive into the details and determine who the threat actor is and how such attacks are carried out. Let’s […]
The post Microsoft Alert: New INC Ransomware Targets US Healthcare appeared first on TuxCare.
The post Microsoft Alert: New INC Ransomware Targets US Healthcare appeared first on Security Boulevard.
Simplify SOAR playbook development with an artifact-based approach. Learn to integrate tools, categorize commands, map key artifacts, and build effective playbook stages.
The post How to Build a SOAR Playbook: Start with the Artifacts appeared first on D3 Security.
The post How to Build a SOAR Playbook: Start with the Artifacts appeared first on Security Boulevard.
Authors/Presenters:Nirav Atre, Hugo Sadok, Justine Sherry
Our sincere thanks to USENIX, and the Presenters & Authors for publishing their superb 21st USENIX Symposium on Networked Systems Design and Implementation (NSDI '24) content, placing the organizations enduring commitment to Open Access front and center. Originating from the conference’s events situated at the Hyatt Regency Santa Clara; and via the organizations YouTube channel.
The post USENIX NSDI ’24 – BBQ: A Fast and Scalable Integer Priority Queue for Hardware Packet Scheduling appeared first on Security Boulevard.
In this blog post, we will cover the basics of a source generator, the major types involved, some common issues you might encounter, how to properly log those issues, and how to fix them.
Source Generators have existed since .NET 5 was first introduced in late 2020. They have seen numerous improvements since that initial release, including the creation of newer Incremental Source Generators.
TLDR: Source generators in .NET enable you to inspect user code and generate additional code on the fly based on that analysis. The example in this blog post may seem a bit redundant, but as you use more advanced patterns, you can generate hundreds of lines of code, helping to reduce boilerplate and repetitive code across your projects. Source generators are also great for lowering runtime reflection use, which can be expensive and slow down your applications.
Skip to the real content.
While developing a C# library to perform messaging between various process components or between processes, I encountered an issue where client programs using this new messaging library would need to add a list of all the “Messenger types.” I had heard of source generators and experimented with them a small amount before encountering this problem, so I figured I could dive in and devise a working solution to handle this and inject the list of “Messenger types” as a property automagically.
I have also been learning various programming paradigms and interesting practices. Vertical Slice architecture and aspect-oriented programming (AOP) are the two relevant to this blog. Vertical slices focus on grouping things that will change together, typically by the feature they represent, regardless of the layer they belong to. The goal of the slices is to minimize coupling between slices and maximize coupling in a slice (i.e., things in a feature depend on each other while trying not to rely on other slice features). This keeps the code base modular and makes it easy to update, remove, or add new slices, as the changes shouldn’t directly affect existing slices. [You can read more on vertical slices here]
AOP is a programming paradigm that aims to increase modularity by allowing the separation of cross-cutting concerns. Typically, in C#, this is implemented by creating attributes that are then placed on classes, methods, etc., to introduce or modify the decorated code. So, with these things in mind, I wanted to look at creating a feature that worked with vertical slices using AOP, and given my newfound challenge of automatically injecting a list of objects into my messenger app at build time, I had just the target goal in mind to combine all of it together.
With that brief overview of why I started messing with source generators, let’s take a quick step back and cover the basics of what a source generator is, what it lets you do, and what it doesn’t.
What is a Source Generator?According to Microsoft: “Source generators aim to enable compile-time metaprogramming, that is, code that can be created at compile time and added to the compilation. Source generators will be able to read the contents of the compilation before running, as well as access any additional files, enabling generators to introspect both user C# code and generator-specific files. Generators create a pipeline, starting from base input sources and mapping them to the output they wish to produce. The more exposed, properly equatable states exist, the earlier the compiler will be able to cut off changes and reuse the same output.”
Figure 1 — Source Generator dataflow, MicrosoftSimply put, source generators in .NET are library projects that you can add to a solution or include in existing NuGet packages. They are meant to be utilized only during the build process to add new code to a project.
[Read more about common source generator use cases here].
What Are Source Generators Not Meant to DoMicrosoft calls out two main concepts as areas where generators are not meant to be used. The first area is adding language features. Microsoft states: “Source generators are not designed to replace new language features: for instance, one could imagine records being implemented as a source generator that converts the specified syntax to a compilable C# representation. We explicitly consider this to be an anti-pattern; the language will continue to evolve and add new features, and we don’t expect source generators to be a way to enable this. Doing so would create new ‘dialects’ of C# that are incompatible with the compiler without generators.”
In this regard, I agree with the team that allowing any .NET developer to start adding new features to the language opens up the possibility of competing features, confusing requirements, and incompatibility with the .NET compiler; which will only serve to confuse and push developers away from source generators altogether.
The second is in code modification; the Microsoft documentation also states, “There are many post-processing tasks that users perform on their assemblies today, which here we define broadly as ‘code rewriting’. These include, but are not limited to:
While these techniques have many valuable use cases, they do not fit into the idea of source generation. They are, by definition, code altering operations which are explicitly ruled out by the source generator’s proposal.”
While technically accurate, this feels more like a semantic line in the sand for the team not wanting a “generator” to perform replacement and not a language-breaking functionality to have access to. With that said, I will show a workaround for code rewriting that I’ve used recently if that is part of your goal for using a source generator.
A source generator is also not an Analyzer. While often used together and sharing many of the exact same requirements to utilize one in a project, a generator’s job is to produce code and an analyzer’s job is to produce warnings or errors based on various rules such as code formatting or, as we will see in source generators, to block access to specific functions/code bases that the analyzer’s author deemed unwelcome.
The Primary Type of Source Generator in Modern .NETAt the time of writing this (September 2024), the .NET team has decided to deprecate source generators implementing “ISourceGenerator” in favor of incremental generators. This change will be enforced, seemingly blocking access to older “ISourceGenerator” APIs with versions of the Roslyn API after version 4.10.0 / .NET 9. (Old Generator Deprecated). In light of that, this blog post series will only cover “IncrementalGenerator” usage.
What Is an Incremental Source Generator?An incremental generator is a source generator that performs its evaluation and execution on items only after they pass some filtering requirements, significantly increasing performance.
Typically, source generators try to execute during design time and compile time. While nice, this incurs an execution of any classes marked as a source generator every time something changes in the project (i.e., delete a line of code, add a line of code, make a new file, etc.). As you can imagine, having something running every time you type is not ideal for performance; thus, Microsoft created these incremental generators to help solve that performance problem.
Adding an Incremental Source Generator to Your ProjectSource generators must target .NET standard 2.0. This allows them to be used in .NET framework 4.6+ or .NET core 5+ projects or other .NET standard 2.0+ projects. By the end of this section, we will have a solution containing three projects.
You can use the dotnet command in a terminal or your IDE of choice to create these projects. I will use the dotnet tool since it is IDE/platform agnostic. The following commands will produce the required projects.
Before creating the source generator, adding a few Nuget packages and changes to the .csproj files are required. Open the SourceGenerator.csproj file and ensure it matches the following content.
https://medium.com/media/dd367dc0ae1158c23a5b82cf17ba07f5/href
The version numbers of the package references will likely be different, which is fine as long as they are valid for the .NET standard 2.0 target.
The three configuration settings added are the following
1. <EnforceExtendedAnalyzerRules>true</EnforceExtendedAnalyzerRules>
2. <IsRoslynComponent>true</IsRoslynComponent>
3. <IncludeBuildOutput>false</IncludeBuildOutput>
The other odd configuration in this .csproj file is the OutputItemType=”Analyzer” added to the project reference for the shared library. Even though the shared library is not an analyzer, this is required so the generator can access it during generation.
The final bit of configuration required is for the webproject.csproj file.
Add the following lines to the project.
<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>Lastly, add the following item group also to the webproject.csproj file.
<ItemGroup>In this first part, we will generate something relatively simple; however, later posts go deeper into using source generators and we will create a small AOP framework to achieve the goal outlined at the start of this blog.
Open the WebProject and add a new class called Calculator.cs with the following source.
https://medium.com/media/30ebc82f45a40769bd16d812efb22e7a/href
We will then generate functions for this class to add, subtract, multiply, and divide. We must mark the class as partial to stick with the intended functionality of only adding content to existing classes. This indicates that more of the class’s source code may be in a different file.
Starting on the Incremental Source GeneratorCongratulations; we finally made it through the required setup.
Finally, with that configuration done, we can start writing the source generator. In the SourceGenerator project, add a class named CalculatorGenerator with the following content.
https://medium.com/media/10d010241aa9280c31d8b38892d66486/href
This gives the bare-bones starting point. To be a valid Incremental source generator, the class must inherit from `IIncrementalGenerator` and be decorated with the [Generator] attribute. The interface requires our generator to implement only the’ Initialize’ function.
The ProvidersThe IncrementalGeneratorInitializationContext argument it provides in the Initialize method will give access to the underlying source.
The context object does this via several different “providers.”
Different Provides for Accessing Various ContextsThe ones we care about are CompilationProvider and SyntaxProvider.
Access the context.SyntaxProvider.CreateSyntaxProvider() method call.
This method takes two arguments. The first is called thepredicate, a super lightweight filter that reduces everything in the codebase to only the items we care about. The second is called thetransform, which ingests what we care about from the filter and makes any additional changes, property access, additional filtering, etc., as desired before returning the objects we want to work with later.
An example of using this syntaxProvider method is as follows.
The names of the arguments (predicate, transform) do not have to be supplied. I included them to make it easier to understand which is which.
https://medium.com/media/b0ad897bf84ad2327a80bf198b4c2f86/href
The PredicateThe predicate code’s first argument is a SyntaxNode , and the second is a CancellationToken. The token allows any asynchronous tasking performed in this method to be gracefully stopped if needed. In this example, it is unnecessary, so we will focus on the SyntaxNode.
(SyntaxNode node, _) =>The preceding code can seem daunting initially, as you are quickly bombarded with terms not typically seen by C# developers (e.g., SyntaxNode, ClassDeclerationSyntax, identifier, etc.). If you are anything like me, you are wondering what they mean, what they are used for, and why you need to use them.
Source generators work alongside / utilize the Roslyn compiler. Roslyn is a set of compilers and code analysis APIs. Roslyn understands your code and projects by breaking down almost everything into SyntaxNodes and SyntaxTokens.
Some examples of syntax tokens include access modifiers like public or private, modifiers like static, abstract, and partial. Names of items like a class name, namespace, method name, etc.
Tokens also include grammar items in the language, like semicolons, brackets, etc.
Example of a SyntaxToken ItemExamples of syntax nodes include class declarations, method declarations, bodies of methods, and individual lines of code, including assignments, expressions, and using statements.
Example of a Syntax Node in this case a Class Declaration Syntax NodeThis programmatic code breakdown is then used to analyze code, write new classes, modify methods, etc. While this can feel daunting, something to remember is that syntax is ultimately still text, and syntax objects can be cast into a string if required. This is precisely what we do in the predicate to convert this SyntaxToken into a string with the .ToString() method to compare it to our target name.
There are various syntax nodes and token types, which I plan to break down and provide examples of in later posts in the series.
In summary, the predicate says if this piece of code represents declaring a class like public partial class Calculator, then check if its identifier (i.e., class name) is “Calculator,” and if so, pass it to the transform. This way, when the generator sees a node like public static void Main(), it knows to skip it.
The Transform transform: (GeneratorSyntaxContext ctx, _) =>The transform takes in the item that passed the filter and a cancellation token again to help cancel it if needed. The GeneratorSyntaxContext item is basically the node and some extra metadata. We then cast the context node item to a ClassDeclarationSyntax. This is required because even though the filter only passed us nodes of that type, the SyntaxContext does not understand that; however, we can cast it and safely know we are getting what we expect.
The transform is where we could extract members of the class, bodies of methods, etc.; whatever item we want to work on. In this example, we want to work on a class, so we get the item as a ClassDeclarationSyntax.
Finally, we add a where statement to filter out any null items that may have made it through. This is optional, but ensuring we aren’t getting some weird invalid item does not hurt.
The CreateSyntaxProvider returns an IncrementalValuesProvider<T> where T is whatever item type we are trying to return from the method call.
An `IncrementalValuesProvider` is a fancy word for the object holding our returned items. There is also an IncrementalValueProvider<T>, which is similar but is meant to have one object instead.
For example, our code’s ValuesProvider contains class declarations from the ClassDeclarationSyntax type.
This then leaves us with an initialization method like this:
https://medium.com/media/c00809482473b3d19c0697bf6cb5a90d/href
The last central part of using a source generator is telling it what to do with the items we got back. Go ahead and add the context. RegisterSourceOutput() line to your project. This tells the generator what to do with the returned items. Next, we will go over the content of this Execute method.
The Execute MethodAlright, so we have our target type; we are filtering out everything we don’t care about, so let’s send it to the execute method and generate our source code.
The execute method is typically defined as follows:
public void Execute(ClassDeclarationSyntax calculatorClass, SourceProductionContext context)The first argument will vary depending on the work you are trying to perform and the method can be modified to take extra arguments as needed. The SourceProductionContext object gives us essential information about the project/solution and enables us to add code to the compilation to include it in the final build.
Since our goal is to generate some simple calculator functions, we will first check all the members of the class we are working on to see if they already have a method with the same name so we don’t accidentally override an existing version. Next, we will gather some metadata, like the namespace, any modifiers, and any using statements, to ensure the code compiles correctly. Lastly, we will insert the code we want into the source file and save it to the compilation.
https://medium.com/media/f854aa10ea2e8c34783650948971019f/href
So the final generator code should look like the following:
https://medium.com/media/448789dddc2b13f03024903d2085d840/href
Alright, all the pieces are in place. Let’s build the solution and check out the generated code.
Example Error Messages When Source Generation FailsWell, that’s not what we hoped for; however, as with many development projects, errors are bound to happen. Don’t panic yet; that is intended to show off some important things when working with source generators. First, source generators will only present a warning when they fail to generate code, so watch for warning messages like this when compiling the code.
Warning CS8785 : Generator ‘CalculatorGenerator’ failed to generate source. It will not contribute to the output and compilation errors may occur as a result. Exception was of type ‘NullReferenceException’ with message ‘Object reference not set to an instance of an object.’.
Second, source generators execute at compile time, making capturing extra context from the exception challenging as you might typically do with a try-catch where you can print info to the console.
If you try something like the following, you will notice no additional information is sent to the console.
public void Execute(ClassDeclarationSyntax calculatorClass, SourceProductionContext context)OK, no problem. Instead, Let’s save the message to a file in the catch statement.
File API Blocked in Source GeneratorsOK, maybe not. If we can’t log to a file in the generator and we can’t log to the console, how will we get the details we need to figure out what is going wrong?
Logging in Source GeneratorsThis brings us to logging in source generators, which I wanted to include in this first part because it is by far the most accessible means of troubleshooting issues when using source generators.
To enable logging in the source generator, open the shared library we made at the start. It should have a single class named class1. Rename that to GeneratorLogging. While the File API is blocked inside the source generator itself, adding that functionality to a secondary library and having it write the content in a file for you is possible.
A simple logging class would be something like the following
https://medium.com/media/d2ee7383cf66da2e79d4042bf2ab6d95/href
There are a few key parts I will quickly explain.
Using the logging class is very straightforward; if you haven’t already, ensure the shared library is added as a dependency of the generator project so it can access it. So, let’s add some logging calls to our current code and see what the log shows.
https://medium.com/media/385cf2859d0c6be2ccde8d9ce079a1f7/href
If needed, perform dotnet clean to clean up any previous logs or generated files. Then, build the solution and check the log file.
The log then will contain output like the following:
[+] Generated Log FileFrom this log output, we can see the generator is running into this Null Reference Exception right after the using statement code, so let’s take a more in-depth look at that.
GeneratorLogging.LogMessage(“[+] Added using statements to generated class”);Here, we see the calcClassNamespace enumerates through the parents of the class object until it finds something. However, we did not add any null checks to ensure we had a namespace before continuing. Let’s modify this section of code to handle the nulls and perform a check against the nodes ancestors as well.
GeneratorLogging.LogMessage(“[+] Added using statements to generated class”);This updated version will now search through all of the child and ancestor nodes to see if the previous checks were null and update them as needed. If they are still null, we should get a log entry to keep troubleshooting issues.
This then gives us a final working source generator of:
https://medium.com/media/50b108415f0110617e43ced6881796e5/href
We can test this by modifying the WebApi project we created at the start.
Open the WebApi program.cs file and modify it to look like this:
https://medium.com/media/673f0284e8b3088d36d3531400658f7b/href
When we run this project and send a get request to the / URL, we will get back a message with the results from the source-generated methods.
API Call Showing the Generated Code Compiled and Executed Correctly Conclusion for Part 1I would like to cover many other capabilities of source generators in future parts that help showcase the real power behind them. So, if you enjoyed this first installment, stick around for more in-depth looks at C# source generators.
Dotnet Source Generators in 2024 Part 1: Getting Started was originally published in Posts By SpecterOps Team Members on Medium, where people are continuing the conversation by highlighting and responding to this story.
The post Dotnet Source Generators in 2024 Part 1: Getting Started appeared first on Security Boulevard.
Pittsburgh, PA, Oct. 1, 2024 — ForAllSecure, the world’s most advanced application security testing company, today announced it is changing its corporate name to Mayhem Security (“Mayhem”), signaling a new era of growth and opportunity aligned with its award-winning … (more…)
The post News alert: Introducing Mayhem Security — ForAllSecure unveils name change, fresh focus first appeared on The Last Watchdog.
The post News alert: Introducing Mayhem Security — ForAllSecure unveils name change, fresh focus appeared first on Security Boulevard.