├── AWS_Security_Questions.md
├── Coding
├── Basic_python.md
├── README.md
├── Sorts.py
└── binary_search.py
├── Common_Security_Questions.md
├── LICENSE
├── Leadership_Questions.md
├── README.md
├── code_review
├── Code_Review_Java.md
├── Code_Review_PHP.md
├── Code_Review_dotnet.md
├── Code_Review_javascript.md
├── Code_Review_python.md
└── README.md
└── manual_mysqli.md
/AWS_Security_Questions.md:
--------------------------------------------------------------------------------
1 | ### Why Cloud Computing:
2 | On demand access to shared pool of resources such as applications, servers, storage and network security. Benefits include economies of scale, cost-saving and uniform security standards.
3 |
4 | #### Well Architected Framework:
5 | 5 Pillars:
6 | 1. Operational Excellence
7 | 2. Security
8 | 3. Reliability
9 | 4. Performance Efficiency
10 | 5. Cost-Optimization
11 |
12 |
13 | #### Shared responsibility model:
14 | AWS: Security 'of' the cloud
15 | Customer: Security 'in' the cloud.
16 |
17 | AWS Security framework/ Security in the Cloud composed of 5 areas:
18 | 1. Identity and Access Management
19 | 2. Detective Controls
20 | 3. Infrastructure protection
21 | 4. Data Protection
22 | 5. Incident Response
23 |
24 | #### Identity and Access Management
25 |
26 | Protection of AWS Credentials:
27 | 1. Use federation if possible
28 | 2. If federation not possible for service to service interaction then protect using the AWS Security token service to generate and manage temporary access tokens.
29 | 3. Fine grained authorisation: create roles using principle of least privilege
30 |
31 | #### Detective Controls:
32 | 1. Capture and Analyze Logs: Use AWS CloudTrail to continously log and monitor and retain account activity related to actions across AWS infrastructure.
33 | 2. Integration Auditing controls with notification and workflow.
34 | 3. Use AWS Inspector
35 | 4. AWS Security Hub
36 |
37 | #### Infrastructure Protection
38 | 1. Protecting Network and Host level boundaries
39 | AWS VPC Security Groups provides a per host stateful firewall
40 | AWS Direct connect
41 | AWS NACL
42 |
43 | 2. System security configuration and Maintenance
44 | AWS System manager, patch manager, inventory,etc.
45 |
46 | 3. Enforcing Service level protection:
47 | Use AWS IAM policy to restrict who can have access to what AWS services
48 |
49 | #### Data Protection
50 | 1. Data Classification -> use tags
51 | 2. Encryption/Tokenization -> AWS KMS, CloudHSM
52 | 3. Protecting data at rest
53 | 3. Protecting data in transit
54 | 4. Data backup, replication, recovery
55 |
56 | #### Incident Response
57 | Incident response plan.
58 | The foundation of a successful incident response program in the cloud is to Educate, Prepare, Simulate, and Iterate.
59 | 1. Educate your security operations and incident response staff about cloud technologies and how your organization intends to use them.
60 | 2. Prepare your incident response team to detect and respond to incidents in the cloud, enabling detective capabilities, and ensuring appropriate access to the necessary tools and cloud services. Additionally, prepare the necessary runbooks, both manual and automated, to ensure reliable and consistent responses. Work with other teams to establish expected baseline operations, and use that knowledge to identify deviations from those normal operations.
61 | 3. Simulate both expected and unexpected security events within your cloud environment to understand the effectiveness of your preparation.
62 | 4. Iterate on the outcome of your simulation to improve the scale of your response posture, reduce time to value, and further reduce risk
63 |
64 |
65 | AWS IAM (continued):
66 | Identity and access management in cloud manages who has access and who can access what resources on AWS.
67 | Access Control: AWS administrators use policies to control access to AWS resources.
68 | Resources: AWS Services such as RDS, S3.
69 |
70 | IAM resources include: Users, Groups, Roles
71 | Policies - JSON policy documents that define the permissions for the object to which they are attached. Two types of policies:
72 |
73 | Identity based policies: Identity-based policies are attached to an IAM user, group, or role. These policies let you specify what that identity can do (its permissions). For example, you can attach the policy to the IAM user named John, stating that he is allowed to perform the Amazon EC2 RunInstances action. The policy could further state that John is allowed to get items from an Amazon DynamoDB table named MyCompany. You can also allow John to manage his own IAM security credentials. Identity-based policies can be managed or inline.
74 |
75 | Resource based policies: Defines particular resources (for example: particular S3) can be controlled by a principal. Resource-based policies are inline only, not managed.
76 |
77 | Identity-based policies and resource-based policies are both permissions policies and are evaluated together. For a request to which only permissions policies apply, AWS first checks all policies for a Deny. If one exists, then the request is denied. Then AWS checks for each Allow. If at least one policy statement allows the action in the request, the request is allowed. It doesn't matter whether the Allow is in the identity-based policy or the resource-based policy.
78 |
79 |
80 | Different sets of policy: AWS Managed policies, Customer Managed policies, Inline policies.
81 | https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_managed-vs-inline.html
82 |
83 | AWS Managed policies: An AWS managed policy is a standalone policy that is created and administered by AWS.
84 |
85 | Customer managed policies: You can create standalone policies that you administer in your own AWS account, which we refer to as customer managed policies.
86 |
87 | Inline Policies: An inline policy is a policy that's embedded in a principal entity (a user, group, or role)—that is, the policy is an inherent part of the principal entity. You can create a policy and embed it in a principal entity, either when you create the principal entity or later.
88 |
89 |
90 | we recommend that you use managed policies instead of inline policies.
91 |
92 | The AWS Security Token Service (STS) is a web service that enables you to request temporary, limited-privilege credentials for AWS Identity and Access Management (IAM) users or for users that you authenticate (federated users).
93 |
94 | AssumeRole:
95 | Returns a set of temporary security credentials that you can use to access AWS resources that you might not normally have access to. These temporary credentials consist of an access key ID, a secret access key, and a security token. Typically, you use AssumeRole within your account or for cross-account access.
96 |
97 | Identity and Access Management:
98 | SEC 1: How do you manage credentials and authentication?
99 | IAM policy and roles, principle of least privilege.
100 | MFA
101 | AWS organization
102 | SEC 2: How do you control human access?
103 | Active directory federation service tied with
104 | SEC 3: How do you control programmatic access?
105 | AWS Secret manager
106 |
107 | AWS provides the service AWS Secrets Manager for easier management of secrets. Secrets can be database credentials, passwords, third-party API keys, and even arbitrary text. You can store and control access to these secrets centrally by using the Secrets Manager console, the Secrets Manager command line interface (CLI), or the Secrets Manager API and SDKs.
108 |
109 | 1. The database administrator creates a set of credentials on the Personnel database for use by an application called MyCustomApp. The administrator also configures those credentials with the permissions required for the application to access the Personnel database.
110 | 2. The database administrator stores the credentials as a secret in Secrets Manager named MyCustomAppCreds. Then, Secrets Manager encrypts and stores the credentials within the secret as the protected secret text.
111 | 3. Then MyCustomApp accesses the database, the application queries Secrets Manager for the secret named MyCustomAppCreds.
112 | 4. Secrets Manager retrieves the secret, decrypts the protected secret text, and returns the secret to the client app over a secured (HTTPS with TLS) channel.
113 | 5. The client application parses the credentials, connection string, and any other required information from the response and then uses the information to access the database server.
114 |
115 |
116 | Detective control:
117 | SEC 4: How do you detect and investigate security events?
118 | CloudTrail
119 | SEC 5: How do you defend against emerging security threats?
120 | Amazon GuardDuty is a managed threat detection service that continuously monitors for malicious or unauthorized behavior to help you protect your AWS accounts and workloads.
121 |
122 | Infrastructure Protection
123 | SEC 6: How do you protect your networks?
124 | VPC, NACL, Security group
125 | AWS shield, WAF
126 |
127 |
128 | SEC 7: How do you protect your compute resources?
129 | Amazon Inspector
130 |
131 | Data Protection
132 | SEC 8: How do you classify your data?
133 | Custom tag
134 | SEC 9: How do you protect your data at rest?
135 | Encryption while at rest
136 | AWS KMS
137 | SEC 10: How do you protect your data in transit?
138 | Encryption ssl, etc
139 |
140 |
141 | AWS Cognito:
142 | Cognito Identity enables you to authenticate users through an external identity provider and provides temporary security credentials to access your app’s backend resources in AWS or any service behind Amazon API Gateway. Amazon Cognito works with external identity providers that support SAML or OpenID Connect, social identity providers (such as Facebook, Twitter, Amazon) and you can also integrate your own identity provider.
143 | Q: How does the login flow work with public identity providers?
144 | Your mobile app authenticates with an Identity Provider (IdP) using the provider’s SDK. Once the end user is authenticated with the IdP, the OAuth or OpenID Connect token or the SAML assertion returned from the IdP is passed by your app to Cognito Identity, which returns a new Cognito ID for the user and a set of temporary, limited-privilege AWS credentials.
145 |
146 | Q: How does Cognito Identity help me control permissions and access AWS services securely?
147 | Cognito Identity assigns your users a set of temporary, limited privilege credentials to access your AWS resources so you do not have to use your AWS account credentials. The permissions for each user are controlled through AWS IAM roles that you create. You can define rules to choose the IAM role for each user, or if you are using groups in a Cognito user pool, you can assign IAM roles based on groups. Cognito Identity also allows you to define a separate IAM role with limited permissions for guest users who are not authenticated. In addition, you can use the unique identifier that Cognito generates for your users to control access to specific resources. For example you can create a policy for an S3 bucket that only allows each user access to their own folder within the bucket.
148 |
--------------------------------------------------------------------------------
/Coding/Basic_python.md:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 |
3 | If __name__=='__main__'
4 | main()
5 |
6 | def main():
7 |
8 | Write a function: def function():
9 |
10 | One line if else:
11 | product = "iphone" if var == 'iphone X' else False
12 |
13 | For loop: for i in range (1,len(list),1):
14 | For each loop: for item in dict/list/set/etc
15 |
16 | one line for loop: for line in lines: adding_list.append(line)
17 |
18 | From random import randint
19 | Int x = randint(1,100)
20 |
21 | Strings:
22 | Str = * I am a string "
23 | print(Str[2:5])
24 | am
25 | Print(Str.strip())
26 | I am a string
27 |
28 | Reverse a string array:
29 |
30 | Str_array=Str_array[::-1]
31 |
32 | String to char list:
33 | List_of_chars=list("I am a string")
34 |
35 | Convert str to int:
36 | Int(string)
37 |
38 | List
39 |
40 | Lists and tuples are standard Python data types that store values in a sequence.
41 |
42 | List = ["a","b","c","d"]
43 | List.sort()
44 | List.sort(reverse=True)
45 | List.append("e") -> append add element end of array
46 | List.remove("e")
47 | Insert at position 0
48 | list.insert(0/1/len(list),element)
49 |
50 | Delete item at index 0
51 | Del list[0]
52 |
53 | List.count("e") --> Return if item exists
54 | If "e" in list:
55 | print e
56 | List.index('element') -- returns index of the element TBC
57 | Max(list)
58 | Min(list)
59 |
60 |
61 | Convert a list to string
62 | Join:
63 | test = {'Python', 'Java', 'Ruby'}
64 | s = '->->'
65 | print(s.join(test))
66 | Python->->Ruby->->Java
67 |
68 | 1. string = "".join(test)
69 | 2. string = "".join(str(element) for element in test)
70 | 3. string = "".join(str(element) for element in test if str(element)='a')
71 |
72 |
73 | Arrays
74 | Numbers_array=[1,2,3,4,5,6,7]
75 | print(numbers_array[2:5]) # 3rd to 5th
76 | [3, 4, 5]
77 | print(numbers_array[:5]) # beginning to 4th [until 5 element doesn’t include 5th element]
78 | [1, 2, 3, 4, 5]
79 | print(numbers_array[5:]) # 6th to end (including 5th element)
80 | [6, 7]
81 | print(numbers_array[:]) # beginning to end
82 |
83 | Dictionary:
84 | Dict ={'a':1,'b':2,'c':3,'d':4}
85 |
86 | If a in Dict:
87 | Print(True)
88 |
89 | Add element: dict['key']=value
90 | Remove element: dict.pop('key')
91 |
92 | Return keys: keys=dict.keys()
93 | Return values: values=dict.values()
94 |
95 |
96 | Copy by value dict1 = dict.copy()
97 | Sets
98 | Sets, unlike lists or tuples, cannot have multiple occurrences of the same element and store unordered values. Because sets cannot have multiple occurrences of the same element, it makes sets highly useful to efficiently remove duplicate values from a list or tuple and to perform common math operations like unions and intersections.
99 |
100 | Set = set()
101 | Set = {'InDesign', 'Photoshop', 'Acrobat', 'Premiere', 'Bridge'}
102 | Set.add('Illustrator')
103 | Set.remove('Illustrator')
104 |
105 | Set = set(list) ->> converting list to set
106 |
107 |
108 | # initialize A and B
109 | A = {1, 2, 3, 4, 5}
110 | B = {4, 5, 6, 7, 8}
111 |
112 | Union operation: A | B Intersection: A & B Set difference: A - B Difference between A and B: A ^B
113 | # Output: {1, 2, 3, 4, 5, 6, 7, 8} print(A & B) print(A - B) print(A ^ B)
114 | print(A | B) # Output: {4, 5} # Output: {1, 2, 3} # Output: {1, 2, 3, 6, 7, 8}
115 | {1, 2, 3, 4, 5, 6, 7, 8}
116 |
117 |
118 | Map
119 | map() function returns a map object(which is an iterator) of the results after applying the given function to each item of a given iterable (list, tuple etc.)
120 |
121 | # Return double of n
122 | def addition(n):
123 | return n + n
124 |
125 | # We double all numbers using map()
126 | numbers = (1, 2, 3, 4)
127 | result = map(addition, numbers)
128 | print(list(result))
129 |
130 | Collections counter:
131 | collections.Counter()
132 | A counter is a container that stores elements as dictionary keys, and their counts are stored as dictionary values.
133 |
134 | from collections import Counter
135 |
136 | >>> myList = [1,1,2,3,4,5,3,2,3,4,2,1,2,3]
137 | >>> print Counter(myList)
138 | Counter({2: 4, 3: 4, 1: 3, 4: 2, 5: 1})
139 |
140 | >>> print Counter(myList).items()
141 | [(1, 3), (2, 4), (3, 4), (4, 2), (5, 1)]
142 |
143 | >>> print Counter(myList).keys()
144 | [1, 2, 3, 4, 5]
145 |
146 | >>> print Counter(myList).values()
147 | [3, 4, 4, 2, 1]
148 |
149 |
150 | Sorted function:
151 | The sorted() function returns a sorted list of the specified iterable object.
152 | You can specify ascending or descending order. Strings are sorted alphabetically, and numbers are sorted numerically.
153 |
154 | Def func(num):
155 | Return num*2
156 |
157 | sorted(list/arr/dict.items(), key=func, reverse=False)
158 |
159 | To sort a dictionary using it's value:
160 | dict = {'a':68, 'b': 67, 'c': 66, 'd': 65}]
161 | Here x -> is the tuple ('a':68)
162 | sorted_dict=sorted(dict.items(),key=lambda x:x[1])
163 |
164 | print(sorted_dict)
165 | [('d', 65), ('c', 66), ('b', 67), ('a', 68)]
166 | Check if we can filter like
167 | string="".join(str(element)>b for
168 |
169 |
170 | Python lambda:
171 | lambda arguments : expression
172 |
173 | lambda a, b : a * b
174 |
175 | Convert a list to dictionary: res_dct = {lst[i]: lst[i + 1] for i in range(0, len(lst), 2)}
176 |
177 | Object comparison:
178 | object.__lt__(self, other) # For x < y
179 | object.__le__(self, other) # For x <= y
180 | object.__eq__(self, other) # For x == y
181 | object.__ne__(self, other) # For x != y OR x <> y
182 | object.__gt__(self, other) # For x > y
183 | object.__ge__(self, other) # For x >= y
184 |
185 | From
186 | Class xxxx:
187 |
188 | def __init__(self, color, size):
189 | self.color = color
190 | self.size = size
191 |
192 | def __eq__(self, other):
193 | """Override the default Equals behavior"""
194 | return self.color == other.color and self.size == other.size
195 |
196 | swap an element in list
197 | i[b], i[a] = i[a], i[b]
198 |
199 | Big(O) n:
200 |
201 | Algorithm Time Space
202 | Binary search O(log n) O(1)
203 | Insert/Bubble sort O(n^2) O(1)
204 | Merge/Heap sort O(nlog n) O(1)
205 | Quick sort O(nlog n) O(1)
206 |
207 |
208 | To determine a type: type(a_string)
209 | Read a file:lines = open(file_path,'r').readlines()
210 | For line in lines:
211 | Print(line)
212 |
213 | Write a file
214 | Writer=open(file_path,'w'):
215 | Writer.write("Hello world")
216 | Writer.close()
217 |
218 | Regex:import re
219 | Words = re.split(r'-',string_to_be_evaluated)
220 | Word=word[0]
221 |
222 |
223 | File system operation:
224 | Os.remove(file)
225 | Os.listdir(path)
226 | os.path.exists('output.txt')
227 |
228 | Dump a dict to json: json_dump = json.dump(dict)
229 |
230 | Convert json to dict: json_dump = json.loads(json_text)
231 |
232 | removed_new_lines_set = set([line.rstrip() for line in open('input.txt')])
233 |
234 | Set Environment variable in python:
235 | os.environ['variable']="anything"
236 |
237 | Get Environment variable in python:
238 | print(os.environ['variable'])
239 |
240 | Timestamp in: 2022_Jan_05_07_09_00_output.csv
241 | import datetime
242 | timestamp = datetime.datetime.now().strftime("%Y_%b_%d_%H_%M_%S_")
243 |
244 | Requests:
245 | import requests
246 |
247 | r = requests.get('https://api.github.com/events')
248 |
249 | r = requests.post('https://httpbin.org/post', data = {'key':'value'})
250 |
251 | headers = {'user-agent': 'my-app/0.0.1'}
252 |
253 | r = requests.get(url, headers=headers)
254 |
255 |
256 |
--------------------------------------------------------------------------------
/Coding/README.md:
--------------------------------------------------------------------------------
1 | ## Basic coding skills
2 |
3 | Learn atleast one popular scripting language like: Python, ruby, Go, etc.
4 |
5 | Practice popular questions around Object oriented programming, Data structures and algorithms like sorting, searching,etc.
6 | Popular websites to practice coding includes the below:
7 | 1. leetcode
8 | 2. HackerRank
9 |
10 | My python revision notes are [here](https://github.com/tahmed11/appsec_interview/blob/master/Coding/Basic_python.md).
11 |
12 | Binary Search example: [Binary Search](https://github.com/tahmed11/appsec_interview/blob/master/Coding/binary_search.py).
13 |
14 | Insertion and Bubble sort example: [Sorts](https://github.com/tahmed11/appsec_interview/blob/master/Coding/Sorts.py).
15 |
--------------------------------------------------------------------------------
/Coding/Sorts.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | import sys
3 | from random import randint
4 |
5 | def ran_gen_list():
6 | list = []
7 | for i in range(0,10,1):
8 | list.append(randint(1,1000))
9 | return list
10 |
11 | def bubblesort(list):
12 | sort=True
13 | ## ...,5,3... => ...,3,5....
14 | ## ...,6,7.... => ....6,7..... (index)
15 | ## swap(6,7) => list[6]=5, list[7]=3 => list[6]=3, list[7]=5
16 | ## index_small = 6, index_large = 7
17 | def swap(index_small,index_large):
18 | temp = list[index_small] #temp=5
19 | list[index_small] = list[index_large] #list[6]= list[7]/3
20 | list[index_large] = temp #list[7] = 5
21 | while(sort):
22 | #start of the function define a sort to be false so we dont keep looping in infinity loop until no more sort is required. Assume this is the last sort.
23 | sort=False
24 | #iterate from 1st element until the end at each sort call.
25 | for i in range(0,len(list)-1,1):
26 | if(list[i]>list[i+1]):
27 | swap(i,i+1)
28 | #print(list)
29 | sort=True
30 | return list
31 |
32 | def insertion_sort(list):
33 | for i in range(len(list)):
34 | cursor = list[i]
35 | pos = i
36 |
37 | while pos > 0 and list[pos - 1] > cursor:
38 | # Swap the number down the list
39 | list[pos] = list[pos - 1]
40 | pos = pos - 1
41 | # Break and do the final swap
42 | list[pos] = cursor
43 | print(str(i)+":"+ str(list))
44 |
45 | return list
46 |
47 |
48 | list = ran_gen_list()
49 | print("Unsorted list:")
50 | print(list)
51 | #print("Bubble Sorting...")
52 | #list=bubblesort(list)
53 | #print("Bubble sorted list:")
54 | #print(list)
55 | list=insertion_sort(list)
56 | print("Insertion sorted list:")
57 | print(list)
--------------------------------------------------------------------------------
/Coding/binary_search.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | import generate_list
3 | from random import randint
4 | #index: 0,1,2,3,4, 5, 6
5 | #list: 1,2,5,6,8,10,12
6 | #search = 2, l=0,h=5, mid=2,list[mid/2]=5
7 | def binary_search(search,list):
8 |
9 | low = 0
10 | high = len(list)-1
11 | found = False
12 | while (low <= high and found is False):
13 | mid=int((low+high)/2)
14 | if(search== list[mid]):
15 | found = True
16 | #shift left
17 | elif(search < list[mid]):
18 | high=mid-1
19 | else:
20 | low=mid+1
21 | return found
22 |
23 | def check_if_exists(search,list):
24 | if search in list:
25 | return True
26 | else:
27 | return False
28 |
29 |
30 | def regression_test():
31 | for i in range(100):
32 | list=generate_list.generate(100)
33 | list.sort()
34 | x=randint(0,200)
35 | if(binary_search(x,list)==check_if_exists(x,list)):
36 | print("Pass")
37 | else:
38 | print("Fail")
39 |
40 | def main():
41 | regression_test()
42 |
43 |
44 | if __name__ == '__main__':
45 | main()
--------------------------------------------------------------------------------
/Common_Security_Questions.md:
--------------------------------------------------------------------------------
1 |
2 | ### Basic networking question:
3 | #### OSI model
4 | All People Seems To Need Data Processing
5 |
6 | | # | Layer | Protocol |
7 | | --- | --- | --- |
8 | | 1 | Physical| Ethernet, 802.11 a/b/g/n|
9 | | 2 | Data | Ethernet, 802.11 a/b/g/n |
10 | | 3 | Network | IP, ICMP, IGM, OSPF, RIP, IPSEC |
11 | | 4 | Transport | TCP, UDP |
12 | | 5 | Session | Sockets, SOCKS, RPC, NetBIOS, Named pipes |
13 | | 6 | Presentation | SSL, TLS, MIME |
14 | | 7 | Application | HTTP, Websockets |
15 |
16 | #### TCP
17 | TCP Flags: SYN, ACK, RST, FIN, PSH, URG
18 | TCP handshake
19 | host A:SYN
20 | host B: SYN-ACK
21 | host C: SYN
22 | End TCP connection:
23 | host A: FIN
24 | host B: FIN-ACK
25 | host C: ACK
26 | | TCP | UDP |
27 | |--- | --- |
28 | |Connection oriented | Connection less |
29 | |Guaranteed transmission| No Guarantee |
30 | |Error checking and out of order | NO error checking and no order of data received |
31 |
32 | #### Port numbers:
33 | Kerberos - 88, syslogin- 514, FTP-20/21, SMTP-25, RDP-3389, IMAP-143, POP3-110, Telnet-23, SSH-22, SNMP-161, LDAP-389,
34 | DNS-53, SMB-445, 135-139
35 |
36 | #### Ipv4 number of address: 2^32
37 | 8.8.8.8 => 8 bits 4*8 = 32
38 |
39 | #### Ipv6 number of address: 2^128
40 |
41 | #### Subnet calculate:
42 | /22 or how many hosts in /22
43 | 2^32-22 = 2^10 (1024) hosts
44 | 192.x.x.x/22 => 1024 hosts
45 |
46 | Private address range
47 | 10.0.0.0 - 10.255.255.255
48 | 172.16.0.0 - 172.31.255.255
49 | 192.168.0.0 - 192.168.255.255
50 |
51 | #### DNS
52 | * How does dns works
53 | * Cname – canonical name ex: example.com, www.example.com
54 | * A and AAAA record – A and AAAA are type of address record map. Host to an IP address. A is ipv4 and AAAA is for ipv6.
55 | * PTR record – reverse of an A record.
56 | * DNS SOA record
57 | * DNS use TCP for zone transfer, UDP for name queries.
58 | * How to do a DNS zone transfer:
59 | dig dns1.target.org -t axfr
60 | dnsrecon.py -a -d dns1.target.org
61 |
62 | 
63 |
64 | #### Traceroute
65 | Sends ICMP echo request packets with increasing TTL values. First packet will be of TTL value 1, so first host will return unreachable. Second packet will be of TTL value of 2 so second host will return unreachable. This process continue until destination is reached.
66 |
67 | #### Ping
68 | Sends ICMP echo messages to the host. Once the host received the packets, the host responds. This way total round trip time is calculated.
69 |
70 | #### Unix vs linux
71 | | Unix | Linux |
72 | |--- | --- |
73 | |Proprietary | Open Source |
74 | |Ex: MacOs, HP-UX, AIS, BSD, etc | Ubuntu, Fedora, CentOS, RedHat |
75 | |Unix is not portable | Can be booted from USB stick |
76 | |Unix is complete OS | Linux is mainly the kernel, everything else GUI + Utilities comes from distribution such as ubuntu, redhat, etc|
77 |
78 | #### Redhat vs debian
79 | Main difference package manager.
80 | Redhat yum -> rpm package manager
81 | Debian apt -> deb package manager
82 |
83 | ### Encryption
84 | #### Symmetric vs Asymmetric
85 | #### Diffie Hellman
86 | Generate a shared secret in public for later symmetric encryption
87 | #### RSA
88 | Pre-generated public/private key pair to agree on a symmetric encryption
89 |
90 | #### SSL handshake [One-way]
91 | 1. SSL Client sends "client hello" to server.
92 | 2. SSL Server responds with "Server hello" with list of cipher suites and server certificate
93 | 3. Client verify server certificate and chose the stronger cipher suite supported
94 | 4. Client key exchange: Send secret key encrypted with server public key.
95 | 5. Exchange message with encrypted shared secret key.
96 |
97 | #### Digital signature
98 | Sign with private key, receiver verifies with public key.
99 |
100 | #### HMAC (Hashed based Message Authentication Code)
101 | MAC = hash(Key | Message)
102 | We don’t only use MAC because it is weak and subject to length extension attack, hence HMAC is used.
103 |
104 | HMAC Secret key => k shared between two parties.
105 | k => k1 and k2
106 | two subkeys (k1 and k2) are derived from k.
107 | HMAC = hash(k2 | hash(k1|message))
108 | HMAC is used for data integrity and authenticity of messages.
109 |
110 |
111 | #### Linux command:
112 | * Show logged in user - w
113 | * Change password - passwd
114 | * List of all open files and processes that opened them - lsof -i
115 | * Show firewall config in Linux - cat /etc/iptables
116 | * How to switch user - su
117 | * What is sudo -
118 | * Show cpuinfo, meminfo - cat /etc/cpuinfo, cat /etc/meminfo
119 | * Find a file in Linux - find /home -name "search.txt"
120 | * Search for a string in linux - grep -r -n "search_string" /home
121 | * Show list of openports - netstat -abno
122 | * Nohup
123 | * Count the number of lines returned - wc -l
124 | * Parse string with delimiters - cut -d ":" -f1:f2
125 |
126 | #### Windows commands:
127 | * Show current logged in user – query user
128 | * Show windows system information - systeminfo
129 | * Show list of all running processes – tasklist /SVC
130 | * Show list of all local users in the computer – net users
131 | * Show info about a user – net user bob
132 | * Find out all processes names and ports – netstat -abno
133 | * Search for a file with name "proof.txt" – dir /S /P “proof.txt”
134 | * Search for a string in a file – findstr /s /c:”search_string”
135 | * Run a program as another user – runas /noprofile /user:Administrator cmd.exe
136 | * Find file/folder permissions - icacls.exe
137 | * Show list of current installed patches = wmic qfe
138 | * Find the name of the current domain – wmic computersystem get domain
139 |
140 | * Process Vs thread
141 | * Process:
142 | Process means any program in execution. A process can create other child processes. Process run on their own memory hence they run on isolation. Each process start with single thread but can create multiple threads.
143 | * Thread:
144 | A thread is an entity within a process. All threads of a process share it's virtual address space and system resources.
145 |
146 | #### HTTP status codes:
147 | * Client error -4xx
148 | * Client success -2xx
149 | * Informational -1xx
150 | * Redirection – 3xx
151 | * Server error -5xx
152 |
153 |
154 | ### Authentication and Authorisation protocols
155 | #### SAML
156 | SAML SSO works by transferring the user’s identity from one place (the identity provider) to another (the service provider). This is done through an exchange of digitally signed XML documents.
157 |
158 | Consider the following scenario: A user is logged into a system that acts as an identity provider. The user wants to log in to a remote application, such as a support or accounting application (the service provider). The following happens:
159 | 
160 | 1. The user accesses the remote application using a link on an intranet, a bookmark, or similar and the application loads.
161 | 2. The application identifies the user’s origin (by application subdomain, user IP address, or similar) and redirects the user back to the identity provider, asking for authentication. This is the authentication request.
162 | 3. The user either has an existing active browser session with the identity provider or establishes one by logging into the identity provider.
163 | 4. The identity provider builds the authentication response in the form of an XML-document containing the user’s username or email address, signs it using an X.509 certificate, and posts this information to the service provider.
164 | 5. The service provider, which already knows the identity provider and has a certificate fingerprint, retrieves the authentication response and validates it using the certificate fingerprint.
165 | 6. The identity of the user is established and the user is provided with app access.
166 |
167 | #### OpenID connect
168 |
169 | 
170 |
171 | 
172 | 1. End user wants to login to your application via “Login with Google” and send the request to your application.
173 | 2. Client application redirects the user to Google login page.
174 | 3. This is where the user is presented with Login page or if already logged in then ask for consent.
175 | 4. User grants their consent or reject.
176 | 5. If the user grants access then the authorization server will send an authorization code to the client.
177 | 6. With the authorization code, the Client requests for an access token and ID token. ID token is a unique identifier of the end user.
178 | 7. With the access token, the application asks the resource server to ask for specific resources such as user’s contact details from Google contacts, etc.
179 |
180 | For full OpenID connect you can visit my other blog post [here](https://medium.com/faun/threat-modeling-openid-connect-oauth-2-0-for-beginners-using-owasp-threat-dragon-part-1-b9e396fd7af9)
181 |
182 | #### Kerberos
183 | #### NTLM
184 | 
185 | The following steps present an outline of NTLM noninteractive authentication. The first step provides the user's NTLM credentials and occurs only as part of the interactive authentication (logon) process.
186 | 1. (Interactive authentication only) A user accesses a client computer and provides a domain name, user name, and password. The client computes a cryptographic hash of the password and discards the actual password.
187 | 2. The client sends the user name to the server (in plaintext).
188 | 3. The server generates a 16-byte random number, called a challenge or nonce, and sends it to the client.
189 | 4. The client encrypts this challenge with the hash of the user's password and returns the result to the server. This is called the response.
190 | 5. The server sends the following three items to the domain controller:
191 | User name
192 | Challenge sent to the client
193 | Response received from the client
194 | 6. The domain controller uses the user name to retrieve the hash of the user's password from the Security Account Manager database. It uses this password hash to encrypt the challenge.
195 | 7. The domain controller compares the encrypted challenge it computed (in step 6) to the response computed by the client (in step 4). If they are identical, authentication is successful.
196 |
197 | Ref: https://docs.microsoft.com/en-us/windows/win32/secauthn/microsoft-ntlm
198 |
199 | #### Threat Modeling
200 | There are five major threat modeling steps:
201 | 1. Defining security requirements.
202 | a. For example, “The application shall not allow any customer to access the account information of any other customer"
203 | 2. Creating an DFD application diagram.
204 | 3. Identifying threats. (STRIDE)
205 | ○ Spoofing
206 | ○ Tampering
207 | ○ Repudiation
208 | ○ Information Disclosure
209 | ○ Denial of service
210 | ○ Elevation of privilege
211 | 4. Mitigating threats.
212 | 5. Validating that threats have been mitigated.
213 |
214 | #### Google dorks:
215 | * How to narrow search to a site
216 | Specifically searches that particular site and lists all the results for that site. site:"www.google.com"
217 | * How to find specific string in URL
218 | Searches for a URL matching one of the keywords. inurl:"keyword"
219 | * How to return only certain specific file format
220 | Searches for a particular filetype mentioned in the query. filetype:"pdf"
221 | * How to return text found in body
222 | Searches for the occurrences of keywords all at once or one at a time. intext:"keyword"
223 |
224 | #### Buffer overflow:
225 | There are different kind of buffer overflow vulnerabilities like stack based, heap based. Stack based are the most simplistic ones. As the name suggests stack based buffer overflow occurs due to overwrite of buffer space in memory. The below C program is vulnerable to buffer overflow. The main function call a vulnerable function. The vulnerable function takes 10 character strings as input parameter. Inside the function we use a vulnerable function(strcpy) to a fixed size buffer of 10 character size. When the main function calls the vulnerable function few things happen to the stack. First the parameter of the vulnerable function will be pushed to the stack, then the return address of the main function will be saved on the stack. Once the function finish executing, stack pointer will return to this address to continue program execution. Now if we send a parameter with more than 10 characters say 100 character, then the return address will overwrite the buffer. Strcpy will copy the extra 90 characters beyond the allocated space. Since we control the buffer we can control arbitary memory address as the return address. Then the program execution will jump to the arbitary address where we can put our shellcode.
226 |
227 | Vulnerable program:
228 | ```
229 | void main(int argc, char *argv[]):
230 | {
231 | vuln_function(argv[1])
232 | return 0
233 | }
234 | void vuln_function(char *str):
235 | {
236 | char buff[10];
237 | strcpy(buff,str);
238 | }
239 | ```
240 | Mitigation of buffer overflow:
241 | 1. Dont use vulnerable functions such as strcpy, etc.
242 | 2. Always do bound checking
243 | 3. Enabled by default ASLR -> Address space layout randomization
244 | 4. DEP -> Dynamic execution prevention
245 | bypass DEP -> ROP gadget
246 | 5. Stack canaries
247 |
248 |
249 | ### Risk
250 | #### Vulnerability
251 | A weakness in a system or asset that makes a threat potentially more likely to occur.
252 |
253 | #### Threat
254 | Any circumstance that may have a negatic impact to an asset.
255 |
256 | #### Risk
257 | Risk is combination of threat probability and loss/impact to business.
258 | Risk = Impact x Likelihood
259 |
260 | #### Control
261 | Mechanism used to restrain, regulate or reduce vulnerabilities. Controls can be corrective, detective, preventive or deterrent.
262 |
263 | ### NIST Cyber security framework:
264 | 1. Identify
265 | 2. Protect
266 | 3. Detect
267 | 4. Respond
268 | 5. Recover
269 |
270 | #### Web Security related questions
271 | ##### SQL injection
272 | Types of SQL injection
273 | 1. Inband or inline: Output directly visible
274 | 2. Blind based injection: cannot see output
275 | 3. Second order SQL injection: Injection get triggered after another function is called.
276 |
277 | Manual exploitation of SQL injection [here](https://github.com/tahmed11/appsec_interview/blob/master/manual_mysqli.md)
278 | Do take the time to learn how to manually exploit SQL injection.
279 |
280 | ##### Cross site scripting
281 | Types of XSS
282 | 1. Reflected XSS: Requests get bounced back from the server.
283 | 2. Stored XSS: Requests are stored and sent back from the server.
284 | 3. Dom based XSS: XSS payload is executed as a result of modifying the DOM environment in the victim’s browser. The payload never gets sent to the server. Example:
285 | ```
286 | Vulnerable code:
287 | Attack payload: http://example.com/test.html#
288 | ```
289 | Mitigation of DOM based XSS:
290 | * Don’t use vulnerable function for untrusted input such as eval(), element.innerHTML , element.outerHTML, document.write(), document.writeln()
291 | * Use safer javascript functions such as: textContent or innerText:
292 |
293 | Generic mitigation against XSS:
294 | 1. Do output encoding, see language specific guides.
295 | 2. Set HTTPOnly flag so cookies are not accessible by client side JavaScript.
296 | 3. The HTTP Content-Security-Policy response header allows website administrator to control resources the user agent is allowed to load for a given page. Policies can be tailored to only allow scripts to be loaded from specific domain to avoid loading malicious scripts.
297 | Content-Security-Policy: default-src: ‘self’, script-src: http://example.com
298 |
299 | Also CSP header automatically disable unsafe_inline and unsafe_eval functions which further restricts XSS.
300 | ‘unsafe_inline’: Allow resources embedded in the page, such as inline