# Symlink Attack

**Example 1: C**

**Vulnerable Code:**

```c
cCopy codeint fd = open("/tmp/myfile", O_RDWR);
write(fd, "data", strlen("data"));
close(fd);
```

**Reason for vulnerability:** The file can be replaced with a symlink, leading to a symlink attack.

**Fixed Code:**

```c
cCopy codeint fd = open("/tmp/myfile", O_RDWR | O_NOFOLLOW);
if (fd == -1) {
    perror("open");
    exit(EXIT_FAILURE);
}
write(fd, "data", strlen("data"));
close(fd);
```

**Reason for fix:** Use `O_NOFOLLOW` to prevent following symlinks.

**Example 2: Python**

**Vulnerable Code:**

```python
pythonCopy codewith open('/tmp/myfile', 'w') as f:
    f.write('data')
```

**Reason for vulnerability:** The file can be replaced with a symlink, leading to a symlink attack.

**Fixed Code:**

```python
pythonCopy codefd = os.open('/tmp/myfile', os.O_WRONLY | os.O_NOFOLLOW)
with os.fdopen(fd, 'w') as f:
    f.write('data')
```

**Reason for fix:** Use `os.O_NOFOLLOW` to prevent following symlinks.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://playbook.sidthoviti.com/devsecops/secure-coding/code-review-examples/symlink-attack.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
