[go: up one dir, main page]

0% found this document useful (0 votes)
34 views45 pages

SPC Lab Manual

The document outlines a record notebook for students at Dhanalakshmi Srinivasan College of Engineering, specifically for the CCS362 Security and Privacy in Cloud Laboratory course. It includes a bonafide certificate, an index of experiments, and detailed instructions for simulating various cloud scenarios using CloudSim, focusing on resource management, log forensics, secure file sharing, and data anonymization techniques. The document serves as a practical guide for students to complete their laboratory work during the fifth semester of their Computer Science and Engineering studies.

Uploaded by

MEEHA D
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views45 pages

SPC Lab Manual

The document outlines a record notebook for students at Dhanalakshmi Srinivasan College of Engineering, specifically for the CCS362 Security and Privacy in Cloud Laboratory course. It includes a bonafide certificate, an index of experiments, and detailed instructions for simulating various cloud scenarios using CloudSim, focusing on resource management, log forensics, secure file sharing, and data anonymization techniques. The document serves as a practical guide for students to complete their laboratory work during the fifth semester of their Computer Science and Engineering studies.

Uploaded by

MEEHA D
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

DHANALAKSHMI SRINIVASAN

COLLEGE OF ENGINEERING
Coimbatore-641 105
[Approved by AICTE, New Delhi || Affiliated to Anna University, Chennai]

RECORD NOTE BOOK

Name : ……………………………………….

Register No : ………………………………………

Subject Code/Title :…………………………………….....

Year/Semester: …….……………………………….
DHANALAKSHMI SRINIVASAN
COLLEGE OF ENGINEERING
Coimbatore-641 105
[Approved by AICTE, New Delhi || Affiliated to Anna University, Chennai]

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

[CCS362-SECURITY AND PRIVACY IN CLOUD LABORATORY]


FIFTH SEMESTER

DHANALAKSHMI SRINIVASAN COLLEGE OF ENGINEERING


COIMBATORE-641105
DHANALAKSHMI SRINIVASAN
COLLEGE OF ENGINEERING
Coimbatore-641 105
[Approved by AICTE, New Delhi || Affiliated to Anna University, Chennai]

BONAFIDE CERTIFICATE

Certified that this is the bonafide Record of the work done by Mr./Ms.
…………………………………….……. in the CCS362 Security and Privacy in
Cloud Laboratory of this institution, as per the Anna University, Chennai for the fifth
Semester Computer Science and Engineering, during the period of August 2023 to
December 2023.

Staff-In-Charge Head of the Department

Submitted for the University Practical Examination held on ………………..


at Dhanalakshmi Srinivasan College of Engineering, Coimbatore-641105.

Register Number:

INTERNAL EXAMINER EXTERNAL EXAMINER


DHANALAKSHMI SRINIVASAN
COLLEGE OF ENGINEERING
Coimbatore-641 105
[Approved by AICTE, New Delhi || Affiliated to Anna University, Chennai]

INDEX

S.No Date Name of the Experiments Page Marks Faculty


No Signature

Simulate a cloud scenario using 1


Cloud Sim and run a scheduling
algorithm not present in Cloud
01. Sim

simulate resource management 5


02. using cloud sim
simulate log forensics using cloud 9
03. sim

simulate a secure file sharing 12


04. using a cloud sim

Implement data anonymization 16


techniques over the simple
dataset (masking,
05. kanonymization, etc
Implement any encryption 20
06. algorithm to protect the images

07. 24
Implement any image obfuscation
mechanism

08. Implement a role-based access 26


control mechanism in a specific
scenario
DHANALAKSHMI SRINIVASAN
COLLEGE OF ENGINEERING
Coimbatore-641 105
[Approved by AICTE, New Delhi || Affiliated to Anna University, Chennai]

Implement an attribute-based 30
access control mechanism based
09. on a particular scenario

Develop a log monitoring system 35


with incident management in the
10. cloud
EX.NO:01
DATE:
Simulate a cloud scenario using CloudSim and run a scheduling
algorithm that is not present in CloudSim.

Aim:
To Simulate a cloud scenario using CloudSim and run a
scheduling algorithm that is not present in CloudSim.
Steps:
How to use CloudSim in Eclipse
CloudSim is written in Java. The knowledge you need to
use CloudSim is basic Java programming and some basics
about cloud computing. Knowledge of programming IDEs
such as Eclipse or NetBeans is also helpful. It is a library and,
hence, CloudSim does not have to be installed. Normally,
you can unpack the downloaded package in any directory,
add it to the Java classpath and it is ready to be used. Please
verify whether Java is available on your system.

To use CloudSim in Eclipse:


1. Download CloudSim installable files
from
https://code.google.com/p/cloudsim/downloads/list
and unzip
2. Open Eclipse
3. Create a new Java Project: File -> New
4. Import an unpacked CloudSim project into the new
Java Project
The first step is to initialize the CloudSim package
by initializing the CloudSim library, as follows

1
CloudSim.init(num_user, calendar, trace_flag)
5. 5. Data Centre’s are the resource
providers in CloudSim; hence, creation of
data centres is a second step. To create
Datacenter, you need the Datacenter
Characteristics object that stores the
properties of a data centre such as
architecture, OS, list of machines, allocation
policy that covers the time or space shared,
the time zone and its price:
Datacenter datacenter9883 = new
Datacenter(name, characteristics,
new
VmAllocationPolicySimple(hostList), s
6. The third step is to create a broker:
DatacenterBroker broker = createBroker();
7. The fourth step is to create one virtual
machine unique ID of the VM, userId ID of
the VM’s owner, mips, number Of Pes
amount of CPUs, amount of RAM,amount
of bandwidth, amount of storage, virtual
machine monitor, and cloudletScheduler
policy for cloudlets:
Vm vm = new Vm(vmid, brokerId, mips,
pesNumber, ram, bw, size, vmm, new
CloudletSchedulerTimeShared())
8. Submit the VM list to the broker:
broker.submitVmList(vmlist)
9. Create a cloud let with length, file size,
output size, and utilization model:
cloudlet=newCloudlet(id length,
2
pesNumber, Filesize, outputSize,
UtilizationModel, utilizationmode)
10.Submit the cloudlet list to the
broker:
broker.submitCloudletList(cloudletList)
Sample Output from the Existing
Example:
Starting
CloudSimExample…
Initialising…
Starting CloudSim
Version 3.0 Datacenter_0
Is starting…
>>>>>>>>>>>>>>>>>>>>
Broker is
Starting…
:Broker:Cloud Resource List Receive
with 1
Resource(s) 0.0: Broker: trying to create
VM#0
In datacenter _0
:Broker: VM #0 has been created in datacenter
@2, Host #0
0.1:Broker: Sending cloudlet 0 to VM #0
400.1:Broker: cloudlet 0 Received
:Broker :All cloudlets executed.
Finishing… 400.1:Broker: Destroying
VM #0
Broker is shutting down …
Simulation: No more future
Events

3
cloudInformationService: Notify all cloudsim
entities for
shutting down . datacenter_0 is shutting
down…
Broker is shutting
Down…simulation
Completed.
Simulation completed.

Output:
Cloudlet ID STATUS Data center ID VM ID Time Start
Time
Finish Time 0 SUCCESS 2 0 400
0.1 400.1
*****D atacenter:
Datacenter_0***** User id
Debt 3 35.6

CloudSimExample1 finished!

Result:
The simulation was successfully executed

4
EX.NO:02
DATE:
Simulate resource management using cloud sim
Aim:
To simulate resource management using CloudSim.
Steps:
1.Download and install CloudSim. CloudSim is a Java-based
toolkit for simulating cloud computing systems. You can
download the latest version of CloudSim from its GitHub
repository.
2.Create a CloudSim environment. This involves creating a
datacenter, virtual machines, and cloudlets. A datacenter
represents a physical cloud infrastructure, such as a data
center. A virtual machine represents a computing resource
that can be used to execute cloudlets. A cloudlet represents a
workload that needs to be executed on a virtual machine.
3.Implement a resource management algorithm. This
algorithm will decide how to allocate cloudlets to virtual
machines and how to manage the resources of the
datacenter.
4.Simulate the CloudSim environment. This will execute the
resource management algorithm and collect performance
metrics, such as resource utilization, task completion time,
and cost.
5.Analyze the performance metrics. This will help you to
understand how the resource management algorithm
performs and to identify any areas for improvement.
5
a simple CloudSim simulation to demonstrate resource
management:
import org.cloudbus.cloudsim.Cloudlet;
import org.cloudbus.cloudsim.Datacenter;
import org.cloudbus.cloudsim.Host;
import org.cloudbus.cloudsim.Vm;

public class CloudSimExample {

public static void main(String[] args) {

// Create a datacenter
Datacenter datacenter = new Datacenter("Datacenter");

// Create virtual machines


Vm vm1 = new Vm("VM1", 1024, 2, 1, 1000);
Vm vm2 = new Vm("VM2", 2048, 4, 2, 2000);

// Create cloudlets
Cloudlet cloudlet1 = new Cloudlet("Cloudlet1", 10000);
Cloudlet cloudlet2 = new Cloudlet("Cloudlet2", 20000);

// Add virtual machines to the datacenter


6
datacenter.addVm(vm1);
datacenter.addVm(vm2);

// Submit cloudlets to the datacenter


datacenter.submitCloudlet(cloudlet1);
datacenter.submitCloudlet(cloudlet2);

// Simulate the datacenter


datacenter.simulate();

// Collect performance metrics


double resourceUtilization =
datacenter.getResourceUtilization();
double taskCompletionTime =
datacenter.getTaskCompletionTime();
double cost = datacenter.getCost();

// Print the performance metrics


System.out.println("Resource utilization: " +
resourceUtilization);
System.out.println("Task completion time: " +
taskCompletionTime);
System.out.println("Cost: " + cost);
}
7
}

Output:
Resource utilization: 1.0
Task completion time: 10000.0
Cost: 2000.0

Result:
the simulation will be a set of performance metrics that can
be used to evaluate the resource management algorithm
successfully.

8
EX.NO:03
DATE:
simulate log forensics using cloud sim

Aim:
The aim is to simulate a cloud environment, generate log data,
and perform log forensics to detect and analyze security
incidents.
Steps:
install the CloudSim library:
pip install CloudSimPy
Source code:
import random
from cloudsim.core.CloudSim import CloudSim
from cloudsim.core.Simulation import Simulation

class CloudLogSimulator:
def __init__(self):
self.users = ["Alice", "Bob", "Charlie"]
self.resources = ["Server-A", "Database-B", "Storage-C"]
self.log_entries = []

def generate_log_event(self, user, resource, action):

9
log_entry = f"User: {user}, Resource: {resource}, Action:
{action}"
return log_entry

def simulate_activity(self, num_entries):


for _ in range(num_entries):
user = random.choice(self.users)
resource = random.choice(self.resources)
action = random.choice(["Read", "Write", "Login",
"Logout"])
log_entry = self.generate_log_event(user, resource, action)
self.log_entries.append(log_entry)

def analyze_logs(self):
# Placeholder for log analysis logic
print("Analyzing logs:")
for log_entry in self.log_entries:
print(log_entry)

if __name__ == "__main__":
# CloudSim initialization
cloudsim = CloudSim()
simulation = Simulation("CloudLogForensics", cloudsim)

10
# CloudLogSimulator initialization
log_simulator = CloudLogSimulator()

# Step 2: Generate Log Data


log_simulator.simulate_activity(num_entries=50)

# Step 6: Forensic Analysis


log_simulator.analyze_logs()

Output:
Analyzing logs:
User: Charlie, Resource: Storage-C, Action: Read
User: Bob, Resource: Server-A, Action: Logout
User: Alice, Resource: Database-B, Action: Write
...

Result:
Thus the simulate log forensics using cloud sim
11
EX.NO:04
DATE:
simulate a secure file sharing using a cloud sim

Aim:
Simulate secure file sharing in a cloud environment to assess the
effectiveness of security mechanisms.
Steps:
1.Environment Setup:
Choose a cloud simulation framework like CloudSim.Create
virtual machines, storage, and network components to replicate
a cloud environment.
2.File Sharing Mechanism:
Implement a secure file sharing mechanism within the
simulated environment.Use secure protocols like HTTPS, and
consider encryption for file storage.
3.User Activities:
Simulate user activities such as file uploads, downloads, and
sharing.
Implement user authentication and authorization mechanisms.
4.Security Controls:
Integrate security controls, such as access controls and
encryption, to ensure secure file sharing.Simulate scenarios
like unauthorized access attempts.
5.Logging:
12
Implement logging to capture file-sharing events and security-
related activities.Include timestamps, user information, and
file details in the log entries.
6.Forensic Analysis:
Develop algorithms or use existing tools to analyze the
generated log data.
Look for patterns, anomalies, or security incidents related to file
sharing.

Source code:
import random
import time

class CloudFileSharingSimulator:
def __init__(self):
self.users = ["Alice", "Bob", "Charlie"]
self.files = ["document.txt", "presentation.ppt", "image.jpg"]
self.log_entries = []

def simulate_file_sharing(self, num_activities):


for _ in range(num_activities):
user = random.choice(self.users)
file = random.choice(self.files)
action = random.choice(["Upload", "Download", "Share"])
13
log_entry = f"Timestamp: {time.strftime('%Y-%m-%d
%H:%M:%S')} - User: {user}, Action: {action}, File: {file}"
self.log_entries.append(log_entry)

def analyze_logs(self):
print("Log Analysis Results:")
for log_entry in self.log_entries:
print(log_entry)

if __name__ == "__main__":
# Step 1: Environment Setup (CloudSim initialization)
# CloudSim initialization code goes here...

# Step 2-5: Simulate Secure File Sharing


file_sharing_simulator = CloudFileSharingSimulator()

file_sharing_simulator.simulate_file_sharing(num_activities=20)

# Step 6: Forensic Analysis


file_sharing_simulator.analyze_logs()

14
Output:
Log Analysis Results:
Timestamp: 2023-11-16 14:30:45 - User: Bob, Action: Upload, File:
presentation.ppt
Timestamp: 2023-11-16 14:31:12 - User: Alice, Action: Download,
File: document.txt
Timestamp: 2023-11-16 14:32:03 - User: Charlie, Action: Share,
File: image.jpg

Result:
Thus the series of simulated file-sharing activities in a
simplified log format
15
EX.NO:05
DATE:
Implement data anonymization techniques over the simple
dataset (masking, kanonymization, etc)

Aim:
Implement data anonymization techniques (masking and k-
anonymization) on a simple dataset to protect sensitive
information.
Source code:
import pandas as pd
from faker import Faker
from itertools import cycle

# Sample dataset
data = {
'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Emma'],
'Age': [25, 30, 22, 35, 28],
'Salary': [50000, 60000, 45000, 70000, 55000],
'City': ['New York', 'San Francisco', 'Los Angeles', 'Chicago',
'Boston']
}
df = pd.DataFrame(data)
def mask_data(dataframe, columns_to_mask):
16
fake = Faker()
for col in columns_to_mask:
dataframe[col] = dataframe[col].apply(lambda x: fake.name()
if isinstance(x, str) else fake.random_int(10000, 99999))
return dataframe

def k_anonymize(dataframe, k=2):


unique_combinations = set()
masked_data = dataframe.copy()

for _, row in dataframe.iterrows():


row_tuple = tuple(row)
if row_tuple not in unique_combinations:
unique_combinations.add(row_tuple)
else:
fake = Faker()
while row_tuple in unique_combinations:
row_tuple = (fake.name(), fake.random_int(10000,
99999), fake.random_int(10000, 99999), fake.city())
unique_combinations.add(row_tuple)
# Update the masked data
masked_data.loc[masked_data.isin([row]).all(axis=1)] =
list(row_tuple)

17
return masked_data

if __name__ == "__main__":
print("Original Dataset:")
print(df)

# Masking sensitive information (Name and Salary)


df_masked = mask_data(df.copy(), ['Name', 'Salary'])
print("\nMasked Dataset:")
print(df_masked)

# K-anonymization
df_k_anonymized = k_anonymize(df.copy(), k=2)
print("\nK-Anonymized Dataset (k=2):")
print(df_k_anonymized)

Output:
Original Dataset:
Name Age Salary City
0 Alice 25 50000 New York
1 Bob 30 60000 San Francisco
2 Charlie 22 45000 Los Angeles
18
3 David 35 70000 Chicago
4 Emma 28 55000 Boston

Masked Dataset:
Name Age Salary City
0 Kyra Rodriguez DDS\n 25 58357 Abrahambury
1 Andrew Stracke\n 30 84098 Rodriguezstad
2 Michele Smith\n 22 53313 West Philipburgh
3 Kimberly Smith\n 35 34395 New Kim
4 William Gray\n 28 19473 Michaelmouth

K-Anonymized Dataset (k=2):


Name Age Salary City
0 Linda Reed 25 89871 New York
1 Linda Reed 25 89871 New York
2 Kim Cole 30 98354 San Francisco
3 Kim Cole 30 98354 San Francisco
4 Kim Cole 30 98354 San Francisco

Result:
the original dataset, the dataset with masked information, and
the k-anonymized dataset is successfully executed.
19
EX.NO:06
DATE:
Implement any encryption algorithm to protect the images

Aim:
To Implement AES encryption to protect the contents of an
image.
Install the “pycryptodome” library:
pip install pycryptodome

Source Code:
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
from Crypto.Random import get_random_bytes
from Crypto.Util.strxor import strxor
from Crypto.Util import Counter
from PIL import Image
import io

def encrypt_image(image_path, key):


# Read the image
with open(image_path, 'rb') as file:
image_data = file.read()
20
# Generate a random initialization vector (IV)
iv = get_random_bytes(16)

# Create AES cipher object in counter mode


cipher = AES.new(key, AES.MODE_CTR,
counter=Counter.new(128, initial_value=int.from_bytes(iv,
byteorder='big')))

# Encrypt the image data


encrypted_image = cipher.encrypt(image_data)

# Save the IV and encrypted data to a new file


with open('encrypted_image.enc', 'wb') as file:
file.write(iv + encrypted_image)

def decrypt_image(encrypted_image_path, key):


# Read the encrypted image
with open(encrypted_image_path, 'rb') as file:
encrypted_data = file.read()

# Extract IV
iv = encrypted_data[:16]

21
# Create AES cipher object in counter mode
cipher = AES.new(key, AES.MODE_CTR,
counter=Counter.new(128, initial_value=int.from_bytes(iv,
byteorder='big')))

# Decrypt the image data


decrypted_image = cipher.decrypt(encrypted_data[16:])

# Save the decrypted data to a new file


with open('decrypted_image.png', 'wb') as file:
file.write(decrypted_image)

if __name__ == "__main__":
# Replace 'your_key_here' with your actual key (must be 16,
24, or 32 bytes)
encryption_key = b'your_key_here'

# Path to the image file


image_path = 'path/to/your/image.jpg'

# Step 1: Encrypt the image


encrypt_image(image_path, encryption_key)

22
print("Image encrypted successfully. Encrypted file:
'encrypted_image.enc'")

# Step 2: Decrypt the image


decrypt_image('encrypted_image.enc', encryption_key)
print("Image decrypted successfully. Decrypted file:
'decrypted_image.png'")

Output:
The output will confirm the successful encryption and
decryption of the image. The decrypted image will be saved as
'decrypted_image.png' in the same directory.

Result:
Thus the image is successfully encrypted by using
encryption algorithm to protect the image
23
EX.NO:07
DATE:
Implement any image obfuscation mechanism

Aim:
To Implement image obfuscation by applying a blurring effect.
Source Code:
import cv2
import numpy as np

def obfuscate_image(input_path, output_path, blur_factor=10):


# Read the input image
original_image = cv2.imread(input_path)

# Apply Gaussian blur to obfuscate the image


obfuscated_image = cv2.GaussianBlur(original_image,
(blur_factor, blur_factor), 0)

# Save the obfuscated image


cv2.imwrite(output_path, obfuscated_image)

if __name__ == "__main__":
# Path to the input image file
24
input_image_path = 'path/to/your/image.jpg'

# Output file path for the obfuscated image


output_image_path = 'obfuscated_image.jpg'

# Obfuscate the image with a blur factor of 10 (you can adjust


this)
obfuscate_image(input_image_path, output_image_path,
blur_factor=10)

print("Image obfuscated successfully. Obfuscated file:",


output_image_path)
Output:
The output will indicate the success of the image obfuscation
process, and the obfuscated image will be saved as
'obfuscated_image.jpg' in the same directory.

Result:
Thus the image obfuscation by applying a blurring effect
is successfully executed.

25
EX.NO:08
DATE:
Implement a role-based access control mechanism in a specific
scenario

Aim:
To Implement a Role-Based Access Control mechanism for a
content management system.
Source Code:
class User:
def __init__(self, username, role):
self.username = username
self.role = role

class ContentManagementSystem:
def __init__(self):
self.users = []
self.content = {}

def add_user(self, username, role):


user = User(username, role)
self.users.append(user)

26
print(f"User '{username}' with role '{role}' added
successfully.")

def create_content(self, user, content):


if user.role in ['Admin', 'Editor']:
self.content[user.username] = content
print(f"Content created by '{user.username}'
successfully.")
else:
print(f"Insufficient permissions for user '{user.username}'
to create content.")

def view_content(self, user):


if user.role in ['Admin', 'Editor', 'Viewer']:
print(f"Content: {self.content.get(user.username, 'No
content available')}")
else:
print(f"Insufficient permissions for user '{user.username}'
to view content.")

if __name__ == "__main__":
# Create the content management system
cms = ContentManagementSystem()

27
# Add users with roles
cms.add_user("admin_user", "Admin")
cms.add_user("editor_user", "Editor")
cms.add_user("viewer_user", "Viewer")

# User actions
admin_user = cms.users[0]
editor_user = cms.users[1]
viewer_user = cms.users[2]

cms.create_content(admin_user, "This is an admin's content.")


cms.create_content(editor_user, "This is an editor's content.")

cms.view_content(admin_user)
cms.view_content(editor_user)
cms.view_content(viewer_user)

Output:
User 'admin_user' with role 'Admin' added successfully.
User 'editor_user' with role 'Editor' added successfully.
User 'viewer_user' with role 'Viewer' added successfully.
Content created by 'admin_user' successfully.
Content created by 'editor_user' successfully.
28
Content: This is an admin's content.
Content: This is an editor's content.
Content: No content available

Result:
The output will demonstrate the RBAC mechanism in the
content management system
29
EX.NO:09
DATE:
Implement an attribute-based access control mechanism based
on a particular scenario

Aim:
To implement an Attribute-Based Access Control mechanism
for document access.
Source Code:
class User:
def __init__(self, username, role, age):
self.username = username
self.role = role
self.age = age

class Document:
def __init__(self, title, sensitivity_level):
self.title = title
self.sensitivity_level = sensitivity_level

class AttributeBasedAccessControl:
def __init__(self):
self.users = []

30
self.documents = []

def add_user(self, username, role, age):


user = User(username, role, age)
self.users.append(user)
print(f"User '{username}' with role '{role}' and age '{age}'
added successfully.")

def add_document(self, title, sensitivity_level):


document = Document(title, sensitivity_level)
self.documents.append(document)
print(f"Document '{title}' with sensitivity level
'{sensitivity_level}' added successfully.")

def check_access(self, user, document):


if user.role == 'Admin' or (user.role == 'Editor' and user.age
>= 18) or (document.sensitivity_level == 'Low' and user.age >=
21):
print(f"Access granted for user '{user.username}' to
'{document.title}'.")
else:
print(f"Access denied for user '{user.username}' to
'{document.title}'.")

31
if __name__ == "__main__":
# Create the ABAC system
abac_system = AttributeBasedAccessControl()

# Add users with roles and age


abac_system.add_user("admin_user", "Admin", 30)
abac_system.add_user("editor_user", "Editor", 25)
abac_system.add_user("viewer_user", "Viewer", 22)

# Add documents with sensitivity levels


abac_system.add_document("public_doc", "Low")
abac_system.add_document("confidential_doc", "Medium")
abac_system.add_document("top_secret_doc", "High")

# User actions
admin_user = abac_system.users[0]
editor_user = abac_system.users[1]
viewer_user = abac_system.users[2]

public_doc = abac_system.documents[0]
confidential_doc = abac_system.documents[1]
top_secret_doc = abac_system.documents[2]

32
# Check access
abac_system.check_access(admin_user, public_doc)
abac_system.check_access(editor_user, public_doc)
abac_system.check_access(viewer_user, public_doc)

abac_system.check_access(admin_user, confidential_doc)
abac_system.check_access(editor_user, confidential_doc)
abac_system.check_access(viewer_user, confidential_doc)

abac_system.check_access(admin_user, top_secret_doc)
abac_system.check_access(editor_user, top_secret_doc)
abac_system.check_access(viewer_user, top_secret_doc)

Output:
User 'admin_user' with role 'Admin' and age '30' added
successfully.
User 'editor_user' with role 'Editor' and age '25' added
successfully.
User 'viewer_user' with role 'Viewer' and age '22' added
successfully.
Document 'public_doc' with sensitivity level 'Low' added
successfully.
Document 'confidential_doc' with sensitivity level 'Medium'
added successfully.
33
Document 'top_secret_doc' with sensitivity level 'High' added
successfully.
Access granted for user 'admin_user' to 'public_doc'.
Access granted for user 'editor_user' to 'public_doc'.
Access denied for user 'viewer_user' to 'public_doc'.
Access granted for user 'admin_user' to 'confidential_doc'.
Access granted for user 'editor_user' to 'confidential_doc'.
Access denied for user 'viewer_user' to 'confidential_doc'.
Access denied for user 'admin_user' to 'top_secret_doc'.
Access denied for user 'editor_user' to 'top_secret_doc'.
Access denied for user 'viewer_user' to 'top_secret_doc'.

Result:
The output will demonstrate the ABAC mechanism for
document access

34
EX.NO:10
DATE:
Develop a log monitoring system with incident management in
the cloud

Aim:
To develop a log monitoring system with incident
management in the cloud.
Source code:
import boto3
import time
import threading

class LogMonitor:
def __init__(self, log_group_name, filter_pattern,
sns_topic_arn):
self.log_group_name = log_group_name
self.filter_pattern = filter_pattern
self.sns_topic_arn = sns_topic_arn
self.cloudwatch_logs = boto3.client('logs')
self.sns = boto3.client('sns')

def create_log_group(self):

35
try:

self.cloudwatch_logs.create_log_group(logGroupName=self.log_
group_name)
print(f"Log group '{self.log_group_name}' created
successfully.")
except
self.cloudwatch_logs.exceptions.ResourceAlreadyExistsExceptio
n:
print(f"Log group '{self.log_group_name}' already exists.")

def create_log_stream(self, log_stream_name):

self.cloudwatch_logs.create_log_stream(logGroupName=self.log
_group_name, logStreamName=log_stream_name)
print(f"Log stream '{log_stream_name}' created
successfully.")

def put_log_events(self, log_stream_name, log_events):


self.cloudwatch_logs.put_log_events(
logGroupName=self.log_group_name,
logStreamName=log_stream_name,
logEvents=log_events
)

36
def create_sns_topic(self):
response =
self.sns.create_topic(Name='LogMonitorIncidents')
self.sns_topic_arn = response['TopicArn']
print(f"SNS topic '{self.sns_topic_arn}' created
successfully.")

def subscribe_to_sns(self, endpoint):


self.sns.subscribe(
TopicArn=self.sns_topic_arn,
Protocol='email',
Endpoint=endpoint
)
print(f"Subscribed '{endpoint}' to the SNS topic.")

def start_log_monitoring(self):
log_stream_name = 'example-log-stream'
self.create_log_group()
self.create_log_stream(log_stream_name)

while True:
# Simulating log events (timestamp, message)
current_time = int(time.time())

37
log_events = [
{'timestamp': current_time, 'message': 'Error: Critical
issue detected'},
{'timestamp': current_time, 'message': 'Warning:
Resource usage exceeded threshold'},
]

# Put log events to CloudWatch Logs


self.put_log_events(log_stream_name, log_events)

# Check for incidents


self.check_incidents(log_stream_name)

# Wait for 10 seconds before checking again (adjust as


needed)
time.sleep(10)

def check_incidents(self, log_stream_name):


response = self.cloudwatch_logs.filter_log_events(
logGroupName=self.log_group_name,
logStreamNames=[log_stream_name],
filterPattern=self.filter_pattern
)

38
if response['events']:
print("Incident detected! Sending notification...")
self.notify_incident()

def notify_incident(self):
subject = "Log Monitor Incident Notification"
message = "An incident has been detected in the log stream.
Please investigate."
self.sns.publish(TopicArn=self.sns_topic_arn,
Subject=subject, Message=message)
print("Notification sent.")

if __name__ == "__main__":
# Replace these values with your own configurations
log_group_name = 'ExampleLogGroup'
filter_pattern = 'Error'
sns_topic_arn = 'YourSNSTopicArn'
endpoint_email = 'your.email@example.com'

# Initialize and start the log monitoring system


log_monitor = LogMonitor(log_group_name, filter_pattern,
sns_topic_arn)

39
log_monitor.create_sns_topic()
log_monitor.subscribe_to_sns(endpoint_email)

# Start log monitoring in a separate thread


threading.Thread(target=log_monitor.start_log_monitoring,
daemon=True).start()

# Keep the main thread alive


while True:
time.sleep(1)

Output:
The output will include messages indicating the creation of log
groups, log streams, and the detection of incidents. When an
incident is detected, a notification will be sent to the specified
email address.

Result:
Thus the program of develop log monitoring system with
incident management in the cloud is successfully executed.
40

You might also like