Friday, May 31, 2024

What is BGP

Border Gateway Protocol (BGP) is the postal service of the Internet. When someone drops a letter into a mailbox, the Postal Service processes that piece of mail and chooses a fast, efficient route to deliver that letter to its recipient. Similarly, when someone submits data via the Internet, BGP is responsible for looking at all of the available paths that data could travel and picking the best route, which usually means hopping between autonomous systems.


The Internet is a network of networks. It is broken up into hundreds of thousands of smaller networks known as autonomous systems (ASes). Each of these networks is essentially a large pool of routers run by a single organization.





If we continue to think of BGP as the Postal Service of the Internet, ASes are like individual post office branches. A town may have hundreds of mailboxes, but the mail in those boxes must go through the local postal branch before being routed to another destination. The internal routers within an AS are like mailboxes. They forward their outbound transmissions to the AS, which then uses BGP routing to get these transmissions to their destinations.



The diagram above illustrates a simplified version of BGP. In this version there are only six ASes on the Internet. If AS1 needs to route a packet to AS3, it has two different options:

Hopping to AS2 and then to AS3:

AS2 → AS3

Or hopping to AS6, then to AS5, AS4, and finally to AS3:

AS6 → AS5 → AS4 → AS3

In this simplified model, the decision seems straightforward. The AS2 route requires fewer hops than the AS6 route, and therefore it is the quickest, most efficient route. Now imagine that there are hundreds of thousands of ASes and that hop count is only one part of a complex route selection algorithm. That is the reality of BGP routing on the Internet.

The structure of the Internet is constantly changing, with new systems popping up and existing systems becoming unavailable. Because of this, every AS must be kept up to date with information regarding new routes as well as obsolete routes. This is done through peering sessions where each AS connects to neighboring ASes with a TCP/IP connection for the purpose of sharing routing information. Using this information, each AS is equipped to properly route outbound data transmissions coming from within.

Here is where part of our analogy falls apart. Unlike post office branches, autonomous systems are not all part of the same organization. In fact, they often belong to competing businesses. For this reason, BGP routes sometimes take business considerations into account. ASes often charge each other to carry traffic across their networks, and the price of access can be factored into which route is ultimately selected.

Who operates BGP autonomous systems?

ASes typically belong to Internet service providers (ISPs) or other large organizations, such as tech companies, universities, government agencies, and scientific institutions. Each AS wishing to exchange routing information must have a registered autonomous system number (ASN). Internet Assigned Numbers Authority (IANA) assigns ASNs to Regional Internet Registries (RIRs), which then assigns them to ISPs and networks. ASNs are 16 bit numbers between one and 65534 and 32 bit numbers between 131072 and 4294967294. As of 2018, there are approximately 64,000 ASNs in use worldwide. These ASNs are only required for external BGP.

How to secure BGP

Fortunately, some progress has been made in securing BGP. Most notably, a security framework for routing called Resource Public Key Infrastructure (RPKI) was introduced in 2008. RPKI uses cryptographically signed records called Route Origin Authorization (ROAs) to validate which network operator is allowed to announce an organization’s IP addresses using BGP. This ensures that only authorized parties are announcing an organization’s prefixes.

But RPKI’s existence alone is not enough. If large networks do not follow BGP security best practices, they can spread large-scale hijacking attacks. Currently, over 50% of the top Internet providers support RPKI to some extent, but a larger majority is needed to fully secure BGP. Network operators can protect their networks by implementing RPKI and using network alerting technology like Cloudflare Route Leak Detection. This feature helps prevent BGP hijacking attacks by letting customers know when unauthorized parties are advertising their prefixes.

Monday, May 20, 2024

Neo4J connecting from python, APOC installation, Database creation

 The screenshot below shows the Installation of APOC







the Project view appears by selecting add files to project and canceling that popup 

the python code to connect to the database is as below 

import os
from uuid import uuid4

from langchain.graphs import Neo4jGraph
import requests

url = "bolt://localhost:7687"
username = "neo4j"
password = "knowledgegraph123*"

graph = Neo4jGraph(
url=url,
username=username,
password=password
)

print("Constructed Graph Object")

url = "https://gist.githubusercontent.com/tomasonjo/08dc8ba0e19d592c4c3cde40dd6abcc3/raw/da8882249af3e819a80debf3160ebbb3513ee962/microservices.json"
import_query = requests.get(url).json()['query']
print("import_query is ",import_query)
graph.query(
import_query
)


What is NJRAT malware

 NJRat has the ability to spread itself in a few different ways. While its primary infection vectors are phishing attacks and drive-by downloads, it also has the ability to spread itself via infected USB drives. The choice of propagation method can be set using the malware’s command and control (C2) software.


Once installed on a target system, the malware is designed to allow the attacker to remotely access and control that system.


NJRat boasts various capabilities, including:


Keylogging

Webcam Access

Theft of credentials stored in browsers

File uploads and downloads

Process and file manipulations

Shell command execution

Registry modification

Screen captures

Viewing the desktop of the infected computer

Theft of cryptocurrency and payment data from crypto wallet apps

NJRat also uses various techniques to evade detection on an infected system. For example, the malware will disguise itself as a critical process, making users less likely to kill it for fear of rendering their system unusable. It also actively defends itself by deactivating endpoint security software and detecting if it is running in a virtualized environment, making it more difficult for security researchers to analyze.


NJRat is also a modular malware variant with the ability to download additional code from Pastebin and similar sites. This enables the malware to expand its capabilities or to act as a dropper for other types of malware once it has established a foothold on an infected device.


Target Industries

NJRat does not target any industry in particular, attacking a wide variety of individuals and organizations. However, it was developed by Arabic speakers and is primarily used to target Arabic-speaking countries in the Middle East.


How to Protect Against NJRat Malware

Malware like NJRat can use various methods to gain access to an organization’s systems and can have a wide range of potential impacts. Some of the ways that organizations can protect themselves against NJRat and other malware include the following:


Employee Cyberawareness Training: Malware commonly uses trickery and deception to get users to install malware on their systems. Employee cybersecurity awareness training can help users to spot the warning signs of a phishing attack and respond correctly to it.

Endpoint Security: NJRat is a known and established malware variant. An endpoint security solution should be able to identify and prevent a malware infection before it poses a real risk to an organization’s systems, data, and users.

Patches and Updates: Malware commonly spreads by exploiting vulnerabilities in users’ browsers or other systems. Promptly applying patches and updates can help close these holes before the malware can exploit them.

Email Scanning: Phishing emails are one of the primary methods that NJRat uses to propagate itself. Email scanning solutions can help to identify and block emails with malicious content before they reach users’ inboxes.

Web Security: NJRat spreads via drive-by downloads, which exploit poor web security. A web security solution can identify and block malicious content before it can be downloaded to a user’s device.

Removable Media Security: NJRat is also capable of spreading itself via USB drives. Endpoint security solutions should be able to identify and block malicious content on removable media before it can infect another device.

Data Backups: NJRat can be used as a dropper for ransomware and other malware. Data backups can help to reduce the ransomware threat by ensuring that the organization can restore normal operations after the malware encrypts files.

Account Security: NJRat has the ability to perform keystroke logging and steal user credentials cached by the browser. Implementing account security best practices — such as the use of multi-factor authentication (MFA) and least privilege access controls — can make it more difficult for attackers to use these compromised credentials to achieve their goals.

What is WebGoat

WebGoat is a deliberately insecure application that allows interested developers just like you to test vulnerabilities commonly found in Java-based applications that use common and popular open source components.

WebGoat is a deliberately insecure web application developed by the Open Web Application Security Project (OWASP). It's designed for educational purposes to help developers and security professionals:

Understand common web application vulnerabilities: WebGoat exhibits a variety of security flaws commonly found in real-world web applications. By exploring these vulnerabilities in a controlled environment, users can learn how attackers exploit them.

Practice penetration testing techniques: WebGoat provides a safe platform to experiment with penetration testing tools and methodologies. Users can identify and exploit the vulnerabilities within the application, learning how to find and potentially fix similar issues in real deployments.

Learn about web application security principles: By understanding how WebGoat's vulnerabilities work, users gain valuable knowledge about secure coding practices, secure configuration, and other key aspects of web application security.

Key Features of WebGoat:

Variety of Vulnerabilities: WebGoat includes a wide range of vulnerabilities, such as SQL injection, cross-site scripting (XSS), insecure direct object references (IDOR), session hijacking, and more.

Interactive Exercises: Each vulnerability in WebGoat is accompanied by guided exercises that help users understand its impact and how to exploit it.

Hints and Solutions: The exercises provide hints and solutions, allowing users to learn at their own pace. However, it's recommended to try to solve the exercises independently first for maximum learning benefit.

Customization: WebGoat is open-source and can be customized to include additional vulnerabilities or tailor the learning experience.

Benefits of Using WebGoat:

Hands-on Learning: WebGoat offers a practical approach to learning about web application security vulnerabilities.

Safe Environment: By practicing in a controlled environment, users can experiment with vulnerabilities without causing damage to real systems.

Improved Security Awareness: By understanding how attackers exploit vulnerabilities, developers and security professionals can take steps to prevent them in their own applications.

Who Should Use WebGoat?

Web Developers: WebGoat can help developers understand how their coding practices can introduce security vulnerabilities.

Security Professionals: Security professionals can use WebGoat to learn about penetration testing techniques and stay up-to-date on the latest web application threats.

Anyone Interested in Web Application Security: WebGoat is a valuable resource for anyone who wants to learn more about how web applications can be attacked and how to protect them.

In summary, WebGoat is a valuable tool for anyone interested in learning about web application security. By providing a safe and interactive environment to experiment with vulnerabilities, WebGoat helps users develop the knowledge and skills they need to build secure web applications.


references:

https://owasp.org/www-project-webgoat/#:~:text=WebGoat%20is%20a%20deliberately%20insecure,and%20popular%20open%20source%20components.



Wednesday, May 15, 2024

What does astream method in Langchain do?

 The astream method in LangChain Workflow is used for asynchronous streaming of data throughout the workflow execution. It allows you to process and potentially modify data incrementally as it becomes available, rather than waiting for the entire data to be processed at once. This can be particularly beneficial for:


Large datasets: When dealing with large datasets, waiting for the entire data to be processed before starting the next step can be inefficient. Astream allows you to process data in chunks, improving performance and memory usage.

Real-time processing: In scenarios where data is generated or received continuously (e.g., chatbots, sensor data streams), astream enables real-time processing of the data as it arrives.

Intermediate results: If your workflow involves generating intermediate results that can be used by subsequent steps, astream allows you to make these results available as soon as they are computed.

Here's a breakdown of the two primary implementations of astream in LangChain workflows:


async for loop (asynchronous iterator):


This approach utilizes an async for loop to iterate over an asynchronous iterable object (like a generator function or an object with an async iterator).

Within the loop, you can process each element of the data stream as it becomes available.

Promises:


You can chain promises together to handle asynchronous operations and data processing in a sequential manner. Each promise in the chain represents the processing of a data chunk.

Here are some key points to remember about astream:


It's primarily used with asynchronous agents within LangChain workflows. These agents are designed to handle asynchronous tasks and data streams.

The astream method returns an asynchronous iterator, allowing you to iterate over the data stream element by element.

LangChain provides helper functions like stream (synchronous) and astream_events (for richer event information) alongside astream for different streaming use cases.

Benefits of using astream:


Improved performance, especially for large datasets or real-time processing.

Efficient memory usage by avoiding loading the entire data at once.

Ability to leverage intermediate results for further processing.


What are various types of Graphs other than StateGraph in langchain

LangChain offers several other graph types besides StateGraph, each suited for different use cases:

MessageGraph:

Purpose: Designed specifically for working with chatbots and conversational interfaces.

Characteristics:

Nodes represent conversation states or message processing steps.

Edges connect states based on user input or system actions.

Often used with LangChain chat models that handle user interactions and generate responses.

DependencyGraph:


Purpose: Represents tasks or actions with dependencies between them.

Characteristics:

Nodes represent individual tasks or actions.

Edges define dependencies, where one task must be completed before another can start.

Useful for modeling workflows, task execution sequences, or processes with pre-requisites.

DataFlowGraph:


Purpose: Captures the flow of data between processing steps.

Characteristics:

Nodes represent data processing steps or functions.

Edges represent the flow of data between nodes, specifying how data is transformed or passed along.

Useful for building data pipelines, machine learning workflows, or any scenario where data is processed and transformed across multiple steps.


EnumGraph:

Purpose: Represents a set of possible states or options.

Characteristics:

Nodes represent individual states or options within the enumeration.

Edges can be used to define relationships between states (e.g., transitions, hierarchies).

Useful for modeling choices, decision points, or state machines with a finite set of options.


Customizable Graph Types:

Concept: LangChain allows you to define custom graph types tailored to your specific needs.

Implementation: You can create custom node and edge types along with their functionalities to model complex relationships and behaviors within your LangChain application.

Choosing the Right Graph Type:


The selection of the appropriate graph type depends on your application's requirements. Here's a quick guide:

State-based interactions: Use StateGraph or EnumGraph for applications that involve navigating through different states based on user input or conditions.

Conversational interfaces: MessageGraph is ideal for building chatbots and conversational experiences.

Task dependencies: DependencyGraph is suitable for modeling workflows or task execution sequences with pre-requisites.

Data processing pipelines: DataFlowGraph helps visualize and manage the flow of data between processing steps.

Complex scenarios: Explore custom graph types for unique requirements where existing options don't perfectly fit your needs.

Remember to consult the LangChain documentation for detailed information on each graph type, its functionalities, and code examples to help you get started with building your LangChain applications.


What would be a simple tool

from langchain_core.messages import HumanMessage, ToolMessage

from langchain_openai import ChatOpenAI

llm = ChatOpenAI(model="gpt-3.5-turbo-0125")

from langchain_core.tools import tool


@tool

def add(a: int, b: int) -> int:

    """Adds a and b.


    Args:

        a: first int

        b: second int

    """

    return a + b



@tool

def multiply(a: int, b: int) -> int:

    """Multiplies a and b.


    Args:

        a: first int

        b: second int

    """

    return a * b



@tool

def ssh_tool(un:str, pwd:str) -> 


print ("About to add the tools")

tools = [add, multiply]

llm_with_tools = llm.bind_tools(tools)

print("Tools are bound with the LLM")


messages = [HumanMessage("How much is 3 & 300 added upto?")]

print("Message created invoking LLM with the tools")

ai_msg = llm_with_tools.invoke(messages)

print("Tool invoked and got the response as ai")

messages.append(ai_msg)


for tool_call in ai_msg.tool_calls:

    selected_tool = {"add": add, "multiply": multiply}[tool_call["name"].lower()]

    tool_output = selected_tool.invoke(tool_call["args"])

    print("tool_output is ",tool_output)

    messages.append(ToolMessage(tool_output, tool_call_id=tool_call["id"]))

print("Total messages retrieved are ", messages)


references: