The Hive
GitHubLinkedInEmail
  • 🏠Home
  • 🌐RECON
    • 📡Passive (OSINT)
      • ⏩Metadata
      • ⏩Social Platforms
        • Email
        • Tumbler
        • Redit
        • Github
        • Tinder
        • TikTok
        • Snapchat
        • Instagram
        • Facebook
        • Twitter
        • Google
        • LinkedIn
    • 📡Active
      • ⏩Host Discovery / Network Mapping
      • ⏩nmap cheat sheet
      • ⏩masscan cheat sheet
    • 📡Web Recon
      • ⏩Web Server Discovery
      • ⏩Hidden Hosts
      • ⏩Directories & Subdomains
      • ⏩SSL Certs
      • ⏩CMS
      • ⏩WAF Detection
    • 📡Firewall Evasion
  • 📗Web Attacks
    • 🟢Server Side
      • 🟩Authentication Mechanisms
      • 🟩Access Control (Authorization)
      • 🟩Directory Traversal
      • 🟩OS Command Injection
      • 🟩Server-Side Request Forgery (SSRF)
      • 🟩XML External Entity (XXE) Injection
      • 🟩File Upload
      • 🔧SQL Injection
      • 🟩Information Disclosure
      • 🟩Business Logic
    • 🟢Client Side
      • 🟩Cross-site request forgery (CSRF)
      • 🔧Cross-site scripting (XSS)
  • 📒Network attacks
    • 🟡Network Services
      • 🟨Brute Force
      • 🟨DNS
      • 🟨IPv6
      • 🟨FTP
      • 🟨SSH
      • 🟨SMB
      • 🟨SNMP
      • 🟨SMTP
      • 🟨POP3
      • 🟨IMAP
      • 🟨MSSQL
      • 🟨MySQL
      • 🟨MSRPC / RPCbind
      • 🟨LDAP
      • 🟨NTP
      • 🟨NFS
      • 🟨Telnet
      • 🟨WebDAV
      • 🟨RDP
      • 🟨RSIP
      • 🟨Rlogin
      • 🟨VPNs
      • 🟨Echo
      • 🔧RTP
      • 🔧VOIP
        • SIP
    • 🟡Network Devices
      • 🟨IPv6 Attacks
        • Neighbor Impersonation
        • Router Advertisement Flooding
      • 🟨Switch Attacks
        • Cisco Exploitation
        • STP Spoofing
        • VLAN Hopping
        • MAC Flood
      • 🟨Router Attacks
        • Router Exploitation
        • HSRP Hijacking
        • 🔧RIP Spoofing
        • 🔧OSPF Attacks
        • 🔧VRRP MitM
      • 🟨NAC Bypass
        • Captive Portal
        • 802.1X / EAP Bypass
      • 🟨Printer Exploitation
    • 🟡MITM & Poisoning
      • 🟨Bettercap
      • 🟨HTTPS Downgrade / HSTS Bypass
      • 🟨Session Hijackings
      • 🟨Malicious Update
      • 🟨RDP Downgrade
      • 🟨DNS Spoofing
      • 🟨NTP Spoofing
      • 🟨ARP Spoofing
      • 🟨DHCP Poisoning
      • 🟨DHCPv6 Spoofing
      • 🟨SSDP Spoofing
      • 🟨WSUS Spoofing
      • 🟨ADIDNS Poisoning
      • 🟨WPAD Abuse
    • 🟡Wireless Attacks
      • 🟨Protocol Concepts
      • 🟨Basics
      • 🟨Attacks
    • 🟡Sniffing
      • 🟨Wireshark
      • 🟨tcpdump
    • 🟡Denial of Service
  • 📕Red Team
    • 🔴Windows
      • ⭕Security Concepts
        • Windows Security Components
        • Active Directory Components
        • Kerberos
        • Loggon Sessions and Access Tokens
        • Permissions and Access Control
        • Windows Registry
        • Object Management
      • ⭕Physical Attack
      • ⭕Enumeration
      • ⭕Privilege Escalation
        • DLL Hijacking
          • Phantom DLL Hijacking / Replacement
          • Search Order Hijacking ( Preloading )
          • DLL Side-Loading
        • Service Misconfigurations
          • Weak Registry Permissions
          • Insecure Service Executables
          • Insecure Permission
          • Unquoted Service Path
        • Creating a New Service (admin to system)
        • Registry
          • AlwaysInstallElevated
          • AutoRuns
        • Scheduled Tasks
        • Mass Roll-outs
        • Startup Apps
        • Installed Applications
        • Loopback Services
        • Insecure GUI APPs
        • Potatos
        • Printspoofer / SEImpersonate
        • PSEXEC (admin to system)
      • ⭕Credential Dumping
      • ⭕Persistence
        • Invisible Account Forger
        • Add User
        • Scheduled Tasks
        • Run Registry Keys
        • Logon Scripts
        • Screensavers Hijack
        • Powershell Profiles & Modules
        • Service Creation/Modification
        • Shortcut Modification
        • Startup Folder
        • RDP backdoors
        • COM Hijacking
    • 🔴Active Directory
      • ⭕Domain Enumeration
      • ⭕Tools & Frameworks
        • Evil-WinRM
        • CME cheat sheet
        • SharpSploit
        • impacket cheat sheet
        • DeathStar
      • ⭕Exploitation
        • LLMNR Poisoning
        • SMB/NTLM Relay
        • DNS Takeover + LDAP Relay
        • Cracking Hashes
        • Password spraying
        • ADCS + PetitPotam NTLM Relay
        • EternalBlue
        • ZeroLogon
        • MS Exchange ProxyShell
        • MS Exchange ProxyLogon
        • Java JBOSS
      • ⭕Privilege Escalation
        • Token Impersonation
        • DNS Admins
        • AD CS Abuse
        • ACL Abuse
          • GenericAll
          • Write Property
          • Self-membership
          • ForceChangePassword
          • Managed Security Groups
          • Exchange Windows Permissions
        • Group Policy Objects (GPOs)
        • Custom SSPs
        • PrintNightmare
      • ⭕Lateral Movement
        • RDP Password Decryption
        • RDP Session Hijacking
        • headless RDP with SharpRDP
        • Domain Shares
        • SCF File Attacks
        • Pass the Hash / Password
        • Overpass the Hash / Pass the Key
        • Pass The Ticket
        • Kerberosting / AS-REP Rosting
        • Kerberos Delegation
      • ⭕Credential Dumping
        • CredSSP / TSPKG
        • Wdigest Clear Text
        • DPAPI secrets
        • SAM & Registry
        • NTDS.dit & vshadow
        • comsvcs.dll
        • Meterpreter
        • Procdump & LSASS
        • AD User Comments
        • SYSVOL & Group Policy Preferences
        • LAPS Passwords
        • GSMA Passwords
        • HiveNightmare
        • Mimikatz Cheat sheet
        • Other Tools / Techniques
      • ⭕Persistence
        • Certificates
        • DCSync
        • DCShadow
        • Silver Ticket
        • Golden Ticket
        • Skeleton Key
        • WMI
        • PowerShell Remoting
        • Remote Registry
        • Rights Abuse
        • AdminSDHolder
        • DSRM
        • Kerberos Checksum Validation ( MS14-068 )
    • 🔴Linux
      • ⭕Physical Attacks
      • ⭕Enumeration
      • ⭕Privilege Escalation
        • SUID / SGID abuse
        • /etc/shadow & /etc/passwd
        • cron/crontab abuse
        • Sudo Abuse
        • Capabilities Abuse
        • Environment Variables
          • LD_LIBRARY_PATH
          • LD_PRELOAD
        • Shared Object Injection
        • NFS
        • man CE Pager Argument
        • MySQL UDF
        • UDEVD
        • STDIN/STDOUT
        • Unix Socket Exploitation
        • Dirty Pipe
        • Docker
          • SUID Docker
      • ⭕Lateral Movement
        • Infecting Running Processes
        • VIM Config File Keylogger
        • SSH Hijacking
        • Samba Secrets to Domain Admin
        • Hiding Processes
        • Simple User-mode Rootkits
        • Vino VNC Server
      • ⭕Credential Dumping
        • Swap Dump
        • mimipinguin
        • unshadow
        • 3snake
      • ⭕Persistence
        • Startup User File Backdoor
        • PHP Backdoor
        • Apache mod_rootme
        • Startup Service Backdoor
        • xdg Backdoor
        • rootbash SUID
        • apt Backdoor
        • Driver Backdoor
        • Core Pattern
        • dash Backdoor
        • Creating an SUID Binary
        • Systemd netcat bind shell
        • Xinetd UDP portnock
        • openSSL reverse shell
        • motd Backdoor
        • Auth Log Backdoor
        • RSYSLOG Backdoor
        • sshd Backdoor
        • VIM Config Backdoor
        • .bashrc Backdoor
        • Adding a Root user
        • Crontab Reverse Shell
        • SSH persistence password-less
      • ⭕Covering Tracks
    • 🔴Command & Control (C2)
      • ⭕Cobalt Strike
      • ⭕Metasploit
      • ⭕Empire & Starkiller
      • ⭕Covenant
    • 🔴Shells and Payloads
      • ⭕Shell Escape / Interactive Shell
      • ⭕LOL Binaries
      • ⭕msfvenom
      • ⭕SharpShooter & Ivy
      • ⭕Other Payloads
    • 🔴Payload Delivery
      • ⭕Powershell Reflective DLL Load
      • ⭕HTML Smuggling
      • ⭕Office Macros
      • ⭕DDE Auto - Word/Excel
      • ⭕.SLK Excel
      • ⭕XLM Macro 4.0
      • ⭕LNK
      • ⭕embedded OLE + LNK objects
      • ⭕JScript
      • ⭕HTA
      • ⭕VBS
      • ⭕VBA
      • ⭕RTF
      • ⭕REG
      • ⭕MSI / MSIEXEC
      • ⭕IQY
      • ⭕CHM / HHC
      • ⭕SCR
    • 🔴Pivoting
      • ⭕SSH Forwarding
      • ⭕Socat Stealth Port Forward
      • ⭕Socat Reverse Shell Relay
      • ⭕HTTP Tunneling
      • ⭕ICMP Tunneling
      • ⭕DNS Tunneling
      • ⭕Metasploit Pivoting
      • ⭕Cobalt Strike Pivoteing
      • ⭕VPN Tunneling
      • ⭕Other Tools
    • 🔴Exfiltration / File Transfer
      • ⭕Encode / Decode Files
      • ⭕TCP / UDP
      • ⭕DNS
      • ⭕SSH
      • ⭕ICMP
      • ⭕SMB
      • ⭕FTP
      • ⭕HTTP
      • ⭕Other Methods
    • 🔴Password Attacks
      • ⭕Online Attacks
      • ⭕Offline Attack
      • ⭕Word List
      • ⭕Cheat Sheet
    • 🔴Defense Evasion
      • ⭕Basic Tricks
      • 🔧Powershell Tricks
      • ⭕Disabling Defenses
      • ⭕UAC Bypass
      • ⭕Process Migration
      • ⭕Dechaining Macros
      • ⭕VBA Sandbox Evasion
      • ⭕AMSI Bypass
      • ⭕SRP & AppLocker Bypass
      • ⭕GPO Bypass
  • 📘Blue Team
    • 🔵Threat Modeling / Hunting / Intelligence
    • 🔵Linux Hardening
      • 🔹OS Security
        • Update Strategy
        • Service Management
        • Physical Security
        • Grub Hardening
        • Kernel Parameters
        • Process Isolation
      • 🔹Accounts & Passwords
        • Users & Groups
        • Password Security & Sudoers
      • 🔹Access Control & Ownership
      • 🔹File System Security
      • 🔹Integrity Check
      • 🔹Sandboxing
      • 🔹Network
      • 🔹iptables
        • Rule Sets
      • 🔹Service Hardening
        • BIND9
        • vsftpd
        • Nginx
        • Apache
        • SSH
      • 🔹System Audit
      • 🔹Logging
        • auditd
      • 🔹Encryption
    • 🔵Security Architecture
      • 🔹Layered Security
  • 🟪Purple Teaming
    • 🟣Adversary Emulation
  • 🟧programming
    • 🟠C Programming
      • 🔸Basic Structure
      • 🔸GCC Compiler
      • 🔸Preprocessors
      • 🔸Data Types
      • 🔸Type Qualifiers
      • 🔸Pointers
      • 🔸Dynamic Memory Allocation
      • 🔸Loops
      • 🔸Conditional Statements
      • 🔸Functions
      • 🔸Input / Output
      • 🔸Macros
      • 🔸Files
      • 🔸Strings Manipulation
      • 🔸Bit Manipulation
      • 🔸Data Structures
        • Arrays
        • Structures
        • Unions
      • 🔸Abstract Data Types
        • Stack
        • Queue
        • Linked List
          • Singly Linked List
          • Doubly Linked List
      • 🔸Libraries & Linking
      • 🔸Error Recovery
    • 🔧Assembly ( NASM )
      • Intel IA-32 Environment
      • Basic Structure
      • Variables and Data Types
      • Most-used Instructions
      • input / output
  • 🟫Miscellaneous
    • 🟤GNU Screen / tmux
    • 🟤SSH Tricks
    • 🟤Cats
      • netcat
      • ncat
      • pwncat
      • socat
      • 🔧powercat
    • 🟤Curl
    • 🟤Cross-compiling Binaries
Powered by GitBook
On this page
  • Summary
  • String representation
  • String functions
  • Reversing a string
  • Analyzing strings
  • Finding mixed character strings (without string.h)
  1. programming
  2. C Programming

Strings Manipulation

Summary

strlen(a)                      → get the length of a

strncat(a,b,sizeOfA)     → append b to a 

strchr(a,'a')          → search for first occurence of 'a' in  string a

strrchr(a,'a')          → search for last occurence of 'a' in string a

strstr(a,b)             → search for string b in a

strncmp(a,b,sizeOfA)    → compare strings a and b

strncpy(a,b,sizeOfA)       → copy b to a (overwrite a)

memcmp(a,b,FirstNBytesToCompare) → compare first n bytes

memchr(a,'a',sizeOfA)  → search array a for character 'a'

strtok(a,t)         → tokenize string a by string t

String representation

char word[7] = {"hellow"}; → always use double quotes and char type

or

char word[7] = "hellow"; → can remove brakets

or

char word[] = "hellow"; → this one is better

String functions

#include <string.h>

the functions with an extra "n" in their names are safer to use because they check for size and can prevent errors or buffer overflow.

strlen() → get the length of a string: strlen(mystring)

strcpy(s1,s2) / strncpy(s1,s2,n) → copy one character string to another (replace)

n is usually the length of first variable replace first variable content with second one

char src[20], dest[20]; → defines two empty strings
strcpy(src, "this is source"); → appends to strings
strcpy(dest, "this is destination");

strcat(s1,s2) / strncat(s1,s2,n) → combining two character strings together and puts the result in the first one: n is usually the length of first variable

strcat(first,second); → a copy of second string is appended to the first string and the result is saved to the first string, second one is not altered

printf("string: %s", (strncat(var1,var2,__size_t 100)));

char var1[]="A",var2[] = "B";
printf("cat: %s",strcat(var1,var2));

strcmp(s1,s2) / strncomp(s1,s2,n) → determing if two strings are equal n is usually the length of first variable this function does for string what relational operators do for numbers: if it returns 0, the strings are same and none-zero if it returns < 0 (negative value) then string1 is less than string2 if it returns > 0 (posetive value) then string2 is less than string1

the "less than" here means in alphabetic order for example:

 printf("%d\n",strcmp("A","B")); → returns -1, A is less than B
  printf("%d\n",strcmp("B","A")); → returns 1, B is greater than A

memchr() → searches an array for the first occurrence of a character

example:

#include <stdio.h>
#include <string.h>

int main(void)
{
    char str[] = "ABCDEFG";
    char *ps = memchr(str,'D',strlen(str));
    if (ps != NULL)
        printf ("search character found:  %s\n", ps);
    else
        printf ("search character not found\n");
    return 0;
} 

Output:

search character found: DEFG

memcmp() → compare the first n bytes of two strings if equal, returns 0 if var1 > var2 returns positive if var2 > var1 returns negative n is the number of first bytes to compare.e.g: size_t 10

unsigned char var1[]="12345", var2[]="12346";
printf("%d",memcmp(var1,var2,__size_t n));  

size_t strlen(s) → returns the number of characters in s, excluding NULL character

strchr() → searchs a given string for a specified character first arg is the string to be searched (the address of a char array) second arg is the character to search for the function will search the string starting at the beginning and return a pointer to the first position in the string where character is found. the address of this position in memory is of type char* described as the pointer to char.

to store the value that's returned you must create a variable that can store the address of a character.

char * ptr = strchr(a,'d'); 

if the character is not found the function returns a special value NULL. NULL is the equivalent of 0 for a pointer and represents a pointer that does not point to anything.

example:

const char str[] = "http://www.tutorialspoint.com";
const char ch = '.';
char *ret;
ret = strchr(str, ch);
printf("String after |%c| is - |%s|\n", ch, ret);

String after |.| is - |.tutorialspoint.com|

strrchr(string,character) → searchs for the last occurence of the character c in string.

strstr() → the most usefull searching function, searchs one string for the first occurrence of a substring , returns a pointer to the position in the first string where the substring is found, if no match, returns NULL.

example:

char text[] = "evey dog has his day";
char word[] = "dog";
char *pFound = NULL;
pFound = strstr(text,word);

strtok() → function is used for tokenizing strings a token is a sequence of characters within a string that is bound by a delimiter. a delimiter can be anything, but should be unique to the string. spaces, commas, and periods are good examples.

breaking a sentence into words is called tokenizing

example:

char str[80] = "hello world - how are you - im w4lk3r";
const char s[2] = "-";
char *token;

token = strtok(str,s); // get the first token

while (token != NULL){
    printf("%s\n",token);
    token = strtok(NULL,s);
}

to extract all tokens:

int main() {
    char string[50] = "Hello! We are learning about strtok";
    // Extract the first token
    char * token = strtok(string, " ");
    // loop through the string to extract all other tokens
    while( token != NULL ) {
        printf( " %s\n", token ); //printing each token
        token = strtok(NULL, " ");
    }
    return 0;
}

c = getchar(); → gets a single character as input

putchar(c) → prints a single character as output

example:

 // copy any input as output
 int main(){
int c;
c= getchar();
while (c != EOF){
    putchar(c);
    c=getchar();

example:

// count the number of lines    
#include <stdio.h>

int main()
{

    int c, ln = 0;

    while((c = getchar()) != EOF){
        if(c == '\n'){
            ++ln;
            printf("number of lines: %d\n",ln);
        }
    }
    return 0;
}

Reversing a string

#include <stdio.h>
#include <string.h>

void reverse(char*, int, int);

int main()
{
    char a[100];
    gets(a);
    reverse(a, 0, strlen(a)-1);
    printf("%s\n", a);
    return 0;
}

void reverse(char *x, int begin, int end)
{
    char c;
    if (begin >= end)
        return;
    c          = *(x+begin);
    *(x+begin) = *(x+end);
    *(x+end)   = c;
    reverse(x, ++begin, --end);
}

Analyzing strings

example:

 #include <stdio.h>
#include <ctype.h>

int main(){

    char a[100] = "hello world";

    for (int i = 0; a[i] != '\0'; i++ ){
        if(islower(a[i]))
            printf("lower: %c\n",a[i]);
    }


    return 0;
}

Finding mixed character strings (without string.h)

 #include <stdio.h>
#include <stdbool.h>

int main(){

    char str[] = "Hello World";
        int   i;
    char  found_lower = false, found_upper = false;

    for (int i = 0; str[i] != '\0'; i++) {
        found_lower = found_lower || (str[i] >= 'a' && str[i] <= 'z');
        found_upper = found_upper || (str[i] >= 'A' && str[i] <= 'Z');

        if (found_lower && found_upper) break;
    }

    printf("%d",found_lower && found_upper);

    return 0;
}
PreviousFilesNextBit Manipulation

Last updated 2 years ago

🟧
🟠
🔸
https://en.cppreference.com/w/c/string/byte