Guide to AI and Data Courses · Lecture Notes
Chapter 38: AI in Cybersecurity
A million connections pass through an organization's gateway every day, and only a few hundred of them are attacks. No person can look at every connection, so a model looks and sends what seems suspicious to an analyst. If the model raises too many false alarms the analyst stops reading them, and an attacker who learns what the model looks at can behave so as to slip past it. These notes introduce the course and work through its three core ideas with small examples you can compute by hand: the arithmetic of searching for rare events, anomaly-based detection, and the fact that a model can be fooled on purpose. The treatment is defensive throughout: detecting attacks and measuring robustness.
Learning outcomes
- The threat setting
- Say what makes a model different in this field: with an adapting attacker on the other side, the data distribution does not stay fixed.
- Base rate
- Compute the probability that an alarm is a real attack (precision) from the attack rate, the recall and the false alarm rate.
- Anomaly detection
- Extract a mean and standard deviation from normal behavior and find the z-score of a new observation; explain that the threshold trades false alarms against misses.
- Robustness
- Compute how a small, bounded change flips the decision of a linear classifier, and read the distance to the decision boundary as a measure of robustness.
- Place of the course
- State what separates AI in cybersecurity from machine learning, explainable AI, biometrics and data mining.
38.1What question does the course ask?
How does AI catch attacks, and how is it attacked itself?
AI in cybersecurity asks two questions together: how can machine learning catch intrusions, malware and phishing, and how can AI systems themselves be fooled? What sets the field apart is the adversarial setting: on the other side is an attacker trying to evade the model.
Machine learning courses start from an assumption: the training data and tomorrow's data come from the same distribution. In security this assumption is broken directly. On the other side is someone who tries to understand how the model works, to behave so that it will not catch them and, if necessary, to fool it. So every model in security faces two exams: how well does it work under ordinary conditions, and how well does it hold up against an attacker?
The second feature is that attacks are rare. In a network the vast majority of connections are harmless. This makes the measures we learned early on (such as accuracy) useless and pushes us toward precision, recall and the false alarm rate. The first core section of this note builds that arithmetic.
38.1.1Two separate questions
The course looks in two directions. The first is AI for security: using models as a defensive tool in intrusion detection, malware classification, phishing and fraud detection. The second is the security of AI: the possibility that a model itself is corrupted by adversarial examples, data poisoning or prompt injection. Of the three core sections of this note the first two belong to the first direction and the third to the second. In all of them the aim is to measure and improve from the defender's point of view; attack methods are treated only to test how sturdy a defense is, in an isolated, authorized lab.
38.1.2At a glance
| Criterion | AI in Cybersecurity |
|---|---|
| Approach | security knowledge plus ML |
| Input | network traffic, logs, files |
| Output | alert, class, risk score |
| Success measure | detection rate, false alarm rate |
| Math load | medium |
| Data needs | imbalanced and constantly changing |
38.2A short history
| Year | Milestone |
|---|---|
| 1987 | Denning defines intrusion detection as a model that catches abnormal behavior. |
| 1999 | The KDD Cup 1999 intrusion detection dataset is released; it serves as a benchmark for many years. |
| 2002 | Paul Graham popularizes the Bayesian spam filter with "A Plan for Spam". |
| 2014 | Szegedy et al. show adversarial examples: an invisible change fools a classifier. |
| 2016 | DARPA Cyber Grand Challenge: machines find and patch vulnerabilities with no human help. |
| 2023 | OWASP publishes its first Top 10 for LLM applications, led by prompt injection. |
38.3Core concepts
The rest of the course is built on the concepts below. The following sections work through the most important ones with examples.
| Concept | Meaning |
|---|---|
| Intrusion detection | Signature-based and anomaly-based approaches. |
| Malware | Classifying files by static or behavioral features. |
| Phishing detection | Telling fake emails, domains and web pages apart. |
| Imbalanced data | Attacks are very rare next to normal traffic. |
| False alarms | Precision, recall; analyst fatigue. |
| Adversarial examples | Inputs carefully perturbed to fool a model. |
| Data poisoning | Slipping malicious samples into training data. |
| Prompt injection | Hidden instructions that change a language model's goal. |
38.4Searching for rare events: base rate and false alarms
In intrusion detection the positive class (attack) is very rare. On such data accuracy is useless: a model that calls every connection "normal" is almost always right. Instead three numbers are read together: the attack rate (the base rate), the recall (what share of attacks is caught) and the false alarm rate (what share of normal connections raises an alarm by mistake). From these three comes the probability that an alarm is a real attack, that is, the precision.
False alarm rate = FP / (FP + TN): the share of normal events that raise an alarm. Precision = TP / (TP + FP): the share of alarms that are real attacks. When the base rate is low, even a seemingly small false alarm rate makes most alarms false. By Bayes' rule: P(attack | alarm) = R·p / (R·p + F·(1 − p)), where p is the base rate, R the recall and F the false alarm rate.
1,000,000 connections pass through a gateway per day; 0.1% of them, 1000, are attacks. A detector has recall 99% and false alarm rate 1%. At first sight it looks excellent.
- Attacks. TP = 0.99 · 1000 = 990; FN = 1000 − 990 = 10.
- Normal connections. 1,000,000 − 1000 = 999,000. FP = 0.01 · 999,000 = 9990; TN = 989,010.
- Number of alarms. 990 + 9990 = 10,980 alarms.
- Precision. 990 / 10,980 ≈ 0.09. About nine of every ten alarms are false.
- Accuracy. (990 + 989,010) / 1,000,000 = 99%. A model that does nothing and calls everything "normal" has accuracy 99.9%: this detector is behind it on accuracy.
If the false alarm rate is cut tenfold to 0.1%, FP = 999, the number of alarms falls to 1989 and precision becomes 990 / 1989 ≈ 0.50. The detector's power to find attacks did not change; only the false alarm rate fell, and trust in the alarms doubled.
The practical consequence of this arithmetic is that an analyst can look at only so many alarms per day. At five minutes per alarm, 1989 alarms is about 166 hours of work; 10,980 alarms is a pile no one can get through. That is why security teams choose a model not only by its recall but also by the alarm load it produces, and rank alarms by score and look only at the top.
Reading "99% recall and 1% false alarms" as "99% of the alarms are correct". The two numbers have different denominators: recall is over the attacks, the false alarm rate is over the normal connections. What share of alarms is correct is decided by the base rate; with the 0.1% base rate above it came out at only 9%.
38.5Anomaly-based detection
Intrusion detection has two classic approaches. Signature-based detection looks for the traces of known attacks (a particular byte sequence, a known domain name): it has few false alarms but cannot see a new attack. Anomaly-based detection learns normal behavior and flags whatever deviates strongly from it: it can catch an attack never seen before, but it also flags everything unusual, harmless things included.
| Signature-based | Anomaly-based | |
|---|---|---|
| What it knows | known attacks | normal behavior |
| New attack | misses it | may catch it |
| False alarms | few | can be many |
| Needs labels? | yes, attack samples | no, only normal data |
The simplest anomaly model extracts a mean and a standard deviation from normal behavior and checks how many standard deviations a new observation lies from the mean. This distance is called the z-score.
z = (x − μ) / σ, where μ is the mean and σ the standard deviation of the normal data. A threshold T is chosen and an alarm is raised when |z| > T. If the data are roughly bell-shaped, |z| > 3 occurs in about 0.27% of normal observations.
Eight hourly counts, in hundreds of connections, are taken from a normal day of a server: 4, 6, 5, 7, 5, 6, 4, 5. New hours arrive with the values 6, 8, 9 and 12. The threshold is T = 3.
- Mean. μ = 42 / 8 = 5.25.
- Standard deviation. The sum of squares is Σ(x − μ)2 = 7.5; σ = √(7.5 / 8) = √0.9375 ≈ 0.97.
- z-scores. Observation 6: (6 − 5.25)/0.97 ≈ 0.77. Observation 8: ≈ 2.84. Observation 9: ≈ 3.87. Observation 12: ≈ 6.97.
- Decision. With T = 3 only 9 and 12 raise an alarm. If the threshold is lowered to 2.5, 8 raises one too: more deviations are caught, but more normal fluctuation also turns into alarms.
The threshold is the dial that sets the trade between false alarms and misses. This calculation shows the size of the load: with |z| > 3 about 0.0027 · 8760 ≈ 24 false alarms per year are expected on one series; if 1000 series are watched, that is about 65 false alarms a day.
Because the model is simple, its limits are easy to see. If the distribution of normal behavior is not bell-shaped, or changes during the day (day and night differ), the z-score misleads. An attacker can also pick a "low and slow" behavior inside the normal range; in the example above, activity that stays below 8 per hour raises no alarm at all. So real systems add context such as the hour of the day to the model, work with many features, and refresh the model regularly with new data (concept drift).
Treating an anomaly as malicious. A software update, a new campaign or a busy workday is also unusual. An anomaly model answers "how unusual is this?", not "how harmful is this?"; the gap between the two questions is closed by an analyst or a second model.
38.6Adversarial examples and robustness
The second direction is that the model itself becomes the target. An adversarial example is a small, carefully chosen change to an input that alters the model's decision. In images the change can be invisible; in areas such as malware or email the input must still be a valid file or message that keeps its function, which narrows the attacker's room to move. The defender asks: how much change is needed to push an input across to another class? The answer is the model's robustness.
The idea is clearest in a linear classifier. The model computes a score s = w · x + b and says "malicious" if s > 0. Under a bound that lets each feature move by at most ε (an L∞ bound), the change that lowers the score most is to step each feature against the sign of its weight; the score changes by at most ε · Σ|wj|.
A malware classifier with three features: w = (2, −1, 3), b = −4. A file has features x = (2, 1, 1). (The values are illustrative.)
- Score. s = 2·2 + (−1)·1 + 3·1 − 4 = 2; positive, the file is flagged "malicious".
- Largest effect. Σ|wj| = 2 + 1 + 3 = 6. Moving every feature by at most ε changes the score by at most 6ε.
- Smallest ε that flips the decision. 6ε = 2 gives ε = 1/3 ≈ 0.33. This is the L∞ distance from the example to the decision boundary.
- Check. For ε = 0.5 the worst-case change is x' = (1.5, 1.5, 0.5): s = 3 − 1.5 + 1.5 − 4 = −1. The decision turns to "harmless". For ε = 1/3 the score is exactly zero.
The lesson for the defender: if an example lies 0.33 from the boundary, a change that small can flip the decision. Robustness is measured by how large these distances are across a dataset.
One defense is adversarial training: during training, altered examples generated from the model's own weak spots are added to the training set with their correct labels, and the model learns to be stable against such changes. The price is longer training and often slightly lower accuracy on clean data. To say that a defense is sturdy it must be tested against an adapting attacker; showing a result against one known attack is not enough.
Counting accuracy on the test set as robustness. A model that is 99% correct on clean examples can be badly wrong after a small shift in each feature; in the example above the distance to the boundary is only 0.33. Robustness is measured separately: reported as accuracy on altered inputs or as distance to the boundary.
38.7How is the course taught?
38.7.1A typical workflow
An organization's gateway collects connection logs; features such as duration, byte count and port are extracted for each connection. A model scores suspicious flows and only the highest-scoring ones go to an analyst. The analyst's decisions become new labels and the model is updated.
38.7.2Topics over the semester
- Threat models and the limits of ML in security
- Feature extraction from network traffic and logs
- Signature- and anomaly-based intrusion detection
- Imbalanced data, false alarms and suitable metrics
- Malware: static and behavioral analysis
- Phishing, spam and malicious URL detection
- Fraud and account takeover detection
- Concept drift and attacker adaptation
- Adversarial examples and evasion attacks
- Data poisoning and backdoors
- Model stealing, membership inference, privacy
- Language model security: prompt injection
This is a typical semester; the order and coverage vary between universities.
38.7.3Skills you will gain
- reading traffic with Wireshark and Zeek
- an attack classifier in scikit-learn
- writing YARA rules
- choosing metrics for imbalanced data
- adversarial attacks with ART
38.7.4Try it yourself
The Try It: Catch Suspicious Logins slide in the presentation lets you solve a typical problem of this course yourself: Password-guessing attacks are mixed in with normal logins in the company's login records. The model gives each login an anomaly score. Move the threshold or click the chart; what happens when the attacker adapts?
38.8Are you ready for this course?
38.8.1Prerequisites
| Course | Why it is needed |
|---|---|
| Machine Learning | intrusion detection, malware classification |
| Operating Systems | processes, file systems and permissions: the layer attacks target |
| Computer Networks | TCP/IP, ports and packets: being able to read network traffic |
| Programming with C | memory and pointers: seeing how overflow vulnerabilities arise |
38.8.2Ask yourself
For every "no", the right-hand column shows where to start. If you can say "yes" to most of them, you are ready.
| Question | If not, start with |
|---|---|
| Can you interpret precision and recall on an imbalanced dataset? | Machine Learning |
| Can you explain how a TCP connection is set up and what a port is? | TCP/IP from a computer networks course |
| Can you inspect processes, file permissions and system logs on Linux? | An operating systems course and the Linux shell |
| Can you explain how a buffer overflow happens in memory? | Pointers and arrays from a C programming course |
38.9Neighboring courses
38.9.1Where it overlaps
| Relation | Course | Shared ground |
|---|---|---|
| application | This course applies the methods of Machine Learning | intrusion detection, malware classification |
| shares methods | Shares methods with Explainable AI and AI Ethics | robustness, adversarial examples |
| shares methods | Shares methods with Biometric Systems | authentication, spoof detection |
38.9.2Where it differs
- Machine Learning: ML assumes the data distribution stays fixed; here the other side deliberately changes the input to evade the model.
- Explainable AI and AI Ethics: Explainable AI treats trustworthiness in general; this course focuses on robustness against attackers and on catching attacks.
- Biometric Systems: Biometrics verifies identity by recognizing a person; this course covers a wide attack surface, from networks and files to email and models.
- Data Mining: Data mining looks for unusual patterns to discover them; this course interprets them as attacks and turns them into alerts.
38.10In practice
38.10.1Applications
| Area | What is done |
|---|---|
| Intrusion detection | Finding unusual connections in network traffic. |
| Malware | Judging whether a file is malicious without running it. |
| Phishing and spam | Filtering out fake emails and web pages. |
| Fraud | Detecting suspicious transactions and account takeover. |
| Security operations | Prioritizing and triaging thousands of alerts. |
| Protecting AI | Adversarial examples, poisoning, prompt injection. |
38.10.2Risks and ethics
| Risk | Explanation |
|---|---|
| Dual use | Techniques learned for detection can also produce malware that evades it, or convincing phishing emails. |
| Unauthorized testing | Scanning another party's network without permission is a crime; experiments belong in an isolated lab, with written consent. |
| Employee surveillance | Insider threat detection watches employees' email and behavior; proportionality, GDPR and similar laws set limits. |
| Automated response | Cutting a connection or locking an account on the model's word alone stops legitimate users on a false alarm. |
These issues are discussed in depth in Explainable AI and AI Ethics.
38.10.3Tools and datasets
Tools: scikit-learn, Zeek, Suricata, Wireshark, YARA, Elastic Stack, Adversarial Robustness Toolbox.
Well-known datasets: KDD Cup 1999 / NSL-KDD, CICIDS2017, UNSW-NB15, EMBER (malware), Enron-Spam, PhishTank.
Old datasets (KDD Cup 1999) are still widely used but do not reflect today's traffic; results should also be tested on recent datasets.
38.11Common misconceptions
99% accuracy means good intrusion detection.
If attacks are very rare, a model that calls everything normal is also 99% accurate; look at precision and false alarm rate.
Once trained, a model keeps catching attacks.
Attackers change tactics; the model must be updated continuously with new samples.
AI replaces the security analyst.
AI filters and prioritizes alerts; decisions and investigation still rest with people.
Deep networks are robust to attacks.
Small, invisible changes (adversarial examples) can easily flip a model's decision.
38.12Summary
- What sets AI in cybersecurity apart is the adversarial setting: with an adapting attacker on the other side the data distribution does not stay fixed, and a model faces two exams, ordinary conditions and an attacker.
- Because attacks are rare, accuracy misleads; the base rate, recall and false alarm rate together decide how trustworthy the alarms are (in the example, 99% recall gave only 9% precision).
- Signature-based detection catches the known with few false alarms; anomaly-based detection can catch the new but may raise many false alarms; the threshold is the dial of that trade.
- A simple anomaly model computes z-scores from the mean and standard deviation of normal data; it must allow for normal behavior changing and for an attacker staying below the threshold.
- Adversarial examples target inputs near the decision boundary; robustness is measured by the distance to the boundary or by accuracy on altered inputs, and adversarial training is one defense.
38.13Test Yourself
On a network carrying 100,000 connections a day, the attack rate is 0.5%, the detector's recall is 90% and its false alarm rate 2%. How many alarms are raised and what is the precision?
Answer
There are 500 attacks, TP = 0.90 · 500 = 450, FN = 50. There are 99,500 normal connections; FP = 0.02 · 99,500 = 1990. The number of alarms is 450 + 1990 = 2440. Precision is 450 / 2440 ≈ 0.18: about 18% of the alarms are real attacks.
The normal hourly counts of a server are 10, 12, 14, 12. New hours bring 15 and 17. Which raises an alarm at threshold T = 3?
Answer
μ = 12, Σ(x − μ)2 = 8, σ = √(8/4) = √2 ≈ 1.41. For 15, z = 3 / 1.41 ≈ 2.12: no alarm. For 17, z = 5 / 1.41 ≈ 3.54: an alarm.
A linear classifier has w = (1, −2, 2), b = −1, x = (3, 1, 1). What is the score? How large an ε flips the decision?
Answer
s = 3 − 2 + 2 − 1 = 2, positive. Σ|wj| = 1 + 2 + 2 = 5. Flipping the decision needs 5ε ≥ 2: ε = 0.4. With ε = 0.2 the score drops by at most 1, to 1, and the decision stays.
A team says "our model is 99.9% accurate"; the attack rate is 0.1%. Why should this number not impress us?
Answer
A model that calls every connection "normal" is just as accurate (99.9%) yet catches no attack (recall 0). A reliable evaluation gives precision, recall and the false alarm rate together.
An anomaly detection system works well on the network it was trained on, but a year later false alarms rise. Give two possible causes and remedies.
Answer
First, concept drift: network behavior changed (new applications, working hours) and the old "normal" is no longer normal; the remedy is to retrain on new data and monitor the drift. Second, the feature distribution has shifted because the attacker or the environment changed; the remedy is again refreshing the model and using contextual features.
An analyst spends 5 minutes per alarm and has 6 hours a day for reviewing alarms. Up to what alarm volume can they look at every alarm? What can be done for the detector above with 1% false alarms (10,980 alarms)?
Answer
6 hours = 360 minutes; 360 / 5 = 72 alarms. 10,980 alarms is far beyond that. Remedies: lower the false alarm rate, rank alarms by score and look only at the top, group similar alarms, and filter low-risk ones automatically.
38.14After this course
This course opens in two directions: on the security side, network security, digital forensics and malware analysis; on the AI side, adversarial robustness, privacy-preserving learning and LLM security. Explainable AI and AI Ethics is the natural neighbor on the second path.
Related careers: Security analyst (SOC), Threat hunter, Malware analyst, Security data scientist, AI security specialist.
38.15Further reading
- C. Chio and D. Freeman, Machine Learning and Security (O'Reilly, 2018): shows machine learning for intrusion detection, malware and phishing with code examples.
- R. Sommer and V. Paxson, "Outside the Closed World: On Using Machine Learning for Network Intrusion Detection" (IEEE Symposium on Security and Privacy, 2010): discusses why anomaly-based detection is hard and what false alarms cost.
- I. Goodfellow, J. Shlens and C. Szegedy, "Explaining and Harnessing Adversarial Examples" (ICLR, 2015): explains adversarial examples through linear models.
38.16References
- Chio and Freeman, Machine Learning and Security, O'Reilly, 2018.
- Denning, "An Intrusion-Detection Model", IEEE Transactions on Software Engineering 13(2), 1987.
- Sommer and Paxson, "Outside the Closed World: On Using Machine Learning for Network Intrusion Detection", IEEE Symposium on Security and Privacy, 2010.
- Goodfellow, Shlens and Szegedy, "Explaining and Harnessing Adversarial Examples", ICLR, 2015.
Related pages: Slides · Slides (PDF) · Course page