Skip to main content
Loading...

More Python Posts

import re

def _map_ikev2_vendor_capabilities(message_type, input_string):
    # List of acceptable message types
    valid_message_types = ['IKE_SA_INIT', 'IKE_AUTH']
    
    # Validate message type
    if message_type not in valid_message_types:
        raise ValueError(f"Invalid message type: {message_type}. Must be one of {valid_message_types}")
    
    # Mapping dictionary for IKE values with RFC references
    value_map = {
        # IKE_SA_INIT capabilities
        'FRAG_SUP': 'IKE Fragmentation',  # RFC 7383, Section 3
        'REDIR_SUP': 'IKE Redirection',  # RFC 5685, Section 3
        'HASH_ALG': 'Hash Algorithms',  # RFC 7296, Section 3.3.2
        'NATD_S_IP': 'NAT Detection (Source IP)',  # RFC 7296, Section 2.23
        'NATD_D_IP': 'NAT Detection (Destination IP)',  # RFC 7296, Section 2.23
        'SIGN_HASH_ALGS': 'Signature Hash Algorithms',  # RFC 7296, Section 2.15
        'NON_FIRST_FRAGMENTS': 'Non-First IKE Fragments',  # RFC 7383, Section 3
        'CHILDLESS_IKEV2_SUP': 'Childless IKEv2',  # RFC 6023, Section 3
        'INTERMEDIATE': 'Intermediate Exchange',  # RFC 9242, Section 3
        'COOKIE': 'Cookie-Based DoS Protection',  # RFC 7296, Section 2.6
        # IKE_AUTH capabilities
        'ESP_TFC_PAD_N': 'ESPv3 TFC Padding Disabled',  # RFC 7296, Section 3.3.1
        'MOBIKE_SUP': 'MOBIKE',  # RFC 4555, Section 3
        'MULT_AUTH': 'Multiple Auth',  # RFC 4739, Section 3
        'EAP_ONLY': 'EAP-Only Auth',  # RFC 5998, Section 3
        'MSG_ID_SYN_SUP': 'Message ID Synchronization',  # RFC 6311, Section 3
        'IPCOMP_SUPPORTED': 'IP Payload Compression Support',  # RFC 7296, Section 3.3.2
        'ADD_4_ADDR': 'Additional IPv4 Addresses',  # RFC 4555, Section 3.2
        'ADD_6_ADDR': 'Additional IPv6 Addresses',  # RFC 4555, Section 3.2
        'INIT_CONTACT': 'Initial Contact',  # RFC 7296, Section 3.16
        'HTTP_CERT_LOOKUP_SUP': 'HTTP Certificate Lookup',  # RFC 7296, Section 3.7
    }
        
    # Regex to capture N(...) patterns
    pattern = r'N\([^)]+\)'
    matches = re.findall(pattern, input_string)
    
    # Parse matches and create result list
    result = []
    for match in matches:
        key = match[2:-1]  # Extract content inside N(...)
        # Only include keys valid for the message type
        if key in value_map:
            result.append(value_map[key])
    
    return ', '.join(result)

# Example usage
ike_sa_init_string = '2025-07-18 20:16:22.839 15[ENC] <4> parsed IKE_SA_INIT request 0 [ SA KE No N(NATD_S_IP) N(NATD_D_IP) N(FRAG_SUP) N(HASH_ALG) N(MULT_AUTH) ]'
ike_auth_string = '2025-07-18 20:16:22.898 07[ENC] <4> parsed IKE_AUTH request 1 [ IDi N(INIT_CONTACT) IDr AUTH N(ESP_TFC_PAD_N) SA TSi TSr N(MOBIKE_SUP) N(ADD_4_ADDR)N(MULT_AUTH) N(EAP_ONLY) N(MSG_ID_SYN_SUP) ]'

# Test with IKE_SA_INIT
print("IKE_SA_INIT Results:")
print(_map_ikev2_vendor_capabilities("IKE_SA_INIT", ike_sa_init_string))

# Test with IKE_AUTH
print("\nIKE_AUTH Results:")
print(_map_ikev2_vendor_capabilities("IKE_AUTH", ike_auth_string))
import os, json, boto3, requests
from flask import Flask, request, jsonify
from flask_cors import CORS, cross_origin
from random import shuffle

app = Flask(__name__)
cors = CORS(app)

dynamodb = boto3.resource("dynamodb", region_name="us-east-1")

app.url_map.strict_slashes = False
SECRET_KEY = os.environ.get("SECRET_KEY")


@app.route("/teks")
def teks_request():
    teks_file = open("teks.json", "r")
    data = json.load(teks_file)
    return jsonify(data)


@app.route("/teks/find/113.41.<int:teks_id>.<string:section_id>")
def teks_find_request(teks_id, section_id):
    teks_file = open("teks.json", "r")
    data = json.load(teks_file)
    for item in data:
        if item["id"] == teks_id:
            for child in item["children"]:
                if child["id"] == section_id:
                    return {"tek": item, "content": child["content"]}
    return jsonify(
        [
            f"Something went wrong. TEKS section id of {section_id} cannot be found within TEKS section {teks_id}."
        ]
    )

@app.route("/lessonplan/read/<id>")
def read_lesson_plan(id):
    lesson_table = dynamodb.Table("Lesson_Plans")
    items = lesson_table.scan()['Items']
    for lesson in items:
        if (lesson["uuid"] == id):
            return jsonify(lesson)
    return {"error": "id does not exist", "section": id}

@app.route("/teks/<int:teks_id>")
def teks_id_request(teks_id):
    teks_file = open("teks.json", "r")
    data = json.load(teks_file)
    for item in data:
        if item["id"] == teks_id:
            return jsonify(item)
    return jsonify([f"Something went wrong. TEKS id of {teks_id} cannot be found."])


@app.route("/assessment/write", methods=["GET", "POST"])
def assessment_write():
    assessment_json = request.json
    assessment_data = dict(assessment_json)
    assessment_table = dynamodb.Table("Assessments")
    assessment_table.put_item(Item=assessment_data)

    if assessment_data == get_assessment(assessment_data["id"]):
        return "Success"
    else:
        return "Failure"

@app.route("/students/read/<id>")
def students_read(id):
    return jsonify(get_students(id))

@app.route("/students/read")
def all_students_read():
    student_table = dynamodb.Table("Students") 
    items = student_table.scan()['Items']
    return jsonify(items)

@app.route("/assessment/read/<id>")
def assessment_read(id):
    return jsonify(get_assessment(id))


@app.route("/assessment/submit/<id>", methods=["POST"])
def submit_assessment(id):
    assessments_table = dynamodb.Table("Assessments")
    assessment = assessments_table.get_item(Key={"id": id})

    if not assessment.get("Item"):
        return {"error": "id does not exist", "section": id}

    responses = {
        question["id"]: question["response"]
        for question in request.json.get("questions")
    }

    correct_answers = 0

    for response in responses:
        # print(
        #     (
        #         responses[response],
        #         find_question(assessment.get("Item").get("questions"), response).get(
        #             "correctAnswer"
        #         ),
        #     )
        # )
        if responses[response] == find_question(
            assessment.get("Item").get("questions"), response
        ).get("correctAnswer"):

            correct_answers += 1

    score = correct_answers / len(request.json.get("questions"))

    users_table = dynamodb.Table("Students")

    users_table.update_item(
        Key={"uuid": request.json.get("student_id")},
        UpdateExpression="SET completedAssessments = list_append(completedAssessments, :i)",
        ExpressionAttributeValues={
            ":i": [
                {
                    "id": id,
                    "score": round(score * 100),
                }
            ]
        },
    )

    message = None
    if round(score * 100) > 70:
        message = f"Congratulations! You passed your assessment with a {round(score * 100)}%."
    else:
        message = f"You failed your assessment with a {round(score * 100)}%."

    sns = boto3.client("sns", region_name="us-east-1")
    number = "+15125967383"
    sns.publish(PhoneNumber=number, Message=message)

    return {"score": score, "message": message}


def find_question(all, id):
    #print("id to find: ", id)
    for question in all:
        if question["id"] == id:
            #print(question)
            return question


def get_assessment(id):
    assessment_table = dynamodb.Table("Assessments")
    results = assessment_table.get_item(Key={"id": id})

    if results.get("Item") is None:
        return {"error": "id does not exist", "section": id}
    else:
        quiz = results.get("Item")
        return {
            "title": quiz.get("title"),
            "id": quiz.get("id"),
            "questions": [
                {
                    "id": question.get("id"),
                    "title": question.get("title"),
                    "options": random_answers(
                        question.get("incorrectAnswers")
                        + [question.get("correctAnswer")]
                    ),
                }
                for question in quiz.get("questions")
            ],
        }

def get_students(id):
    students_table = dynamodb.Table('Students')
    results = students_table.get_item(Key = {
        "uuid": id
    })

    if(results.get("Item") is None):
        return {'error': 'id does not exist', 'section': id}
    else:
        student = results.get("Item")
        return student

def lesson_plans_read():
    student_table = dynamodb.Table("Lesson_Plans")
    items = student_table.scan()['Items']
    return jsonify(items)

def random_answers(answers):
    shuffle(answers)
    return answers

@app.route("/recommendations/<uuid>")
def get_recommendation(uuid):
    student_info_table = dynamodb.Table('Students')
    lesson_plans_table = dynamodb.Table('Lesson_Plans')
    student = get_students(uuid)
    tek = student.get("struggleTeks")[0]

    lesson_plans = lesson_plans_table.scan( Select='ALL_ATTRIBUTES', FilterExpression='tek = :s', ExpressionAttributeValues={ ":s": tek })

    #print(lesson_plans) 

    return jsonify({"student": student, "lesson_plans": lesson_plans.get("Items")})

if __name__ == "__main__":
    app.run(host="0.0.0.0", debug=True)