# 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.
